سؤال

I'im trying to dot-source a script file in PowerGui 3.0 , but all i get is ;


The term '.\PowerShell.Common.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spel ling of the name, or if a path was included, verify that the path is correct and try again. At D:\TFS\SharePoint\Dev\Deploy\AutoSPInstaller\SP2010\AutoSPInstaller\AutoSPInstallerFunctionsCustom.ps1:6 char:31 + .\PowerShell.Common.ps1 <<<< + CategoryInfo : ObjectNotFound: (.\PowerShell.Common.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException


And powerGui subsequently does not offer my script function within said file - in the context sensitive list in the parent script.

the file "PowerShell.Common.ps1" is in the same directory as AutoSPInstallerFunctionsCustom.ps1 Thank you for your assistance

هل كانت مفيدة؟

المحلول

To dot-source the file from PowerGUI's command line, make sure that your current working directory is at the script's directory. You can check this by typing $PWD at PowerGUI's command line.

To reference another script from a script you would do this:

# Get the current script's directory
$MyDir = Split-Path $MyInvocation.MyCommand.Definition

# Dot-source the external script by using the current script's directory
. "$MyDir\ScriptName.ps1"

Getting the script's directory ensures that even if your current working directory is not the same as the script's directory, you will be able to reference files relative to the script's location.

نصائح أخرى

@Rynant is certainly correct in pointing out that the problem is you need to reference the script's directory rather than your current directory. However, it is important to note that his code solution is only partially correct; in fact, whether it works depends on where you call it!

A more robust solution is this:

function Get-ScriptDirectory
{
    Split-Path $script:MyInvocation.MyCommand.Path
}

As it happens, I just wrote a detailed discussion analyzing this very point of correctly getting the script directory in another SO question. Rather than repeat my lengthy answer (complete with test vehicle and results matrix) I will provide this link.

This problem arises when you browse to the script you are working on from within PowerGUI.

Instead of changing the invocation paths to the other scripts you may prefer to run the script in-situ, i.e. with $PWD set to the directory of the script. This is most easily done by opening the script in PowerGUI through the Windows shell by using by the right-click context menu in Windows Explorer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top