为什么函数在第一次运行之后才在本地可用?

pgh*_*ech 4 powershell powershell-2.0

我在这里有两个问题,为什么在运行脚本时脚本中的以下函数无法识别:

脚本:

$pathN = Select-Folder
Write-Host "Path " $pathN

function Select-Folder($message='Select a folder', $path = 0) { 
  $object = New-Object -comObject Shell.Application  

  $folder = $object.BrowseForFolder(0, $message, 0, $path) 
    if ($folder -ne $null) { 
        $folder.self.Path 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

我收到错误:

The term 'Select-Folder' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try aga
Run Code Online (Sandbox Code Playgroud)

在.

但是,如果我在Windows Powershell ISE中加载并运行它,它将在第一次给我错误,然后表现得已经"注册"了该功能并在此之后工作.

如果这是一个程序问题,我已经尝试将功能列在顶部而没有更好的运气.

注意 我尝试过简单的函数:

Write-host "Say "
Hello

function Hello {
  Write-host "hello"
}
Run Code Online (Sandbox Code Playgroud)

具有相同的确切结果/错误,它抱怨Hello不是功能....

此外,它仍然不会在PowerShell中运行脚本(仅在第一次初始尝试后的ISE中).

Wil*_*lka 12

Select-Folder在尝试使用它之前,需要声明您的函数.脚本是从上到下阅读的,所以当你尝试使用Select-Folder它的第一遍时,不知道这意味着什么.

当你将它加载到Powershell ISE中时,它会Select-Folder在第一次运行时发现它意味着什么,它仍然会知道你第二次尝试运行它(所以你不会得到错误).

因此,如果您将代码更改为:

function Select-Folder($message='Select a folder', $path = 0) { 
  $object = New-Object -comObject Shell.Application  

  $folder = $object.BrowseForFolder(0, $message, 0, $path) 
    if ($folder -ne $null) { 
        $folder.self.Path 
    } 
} 

$pathN = Select-Folder
Write-Host "Path " $pathN
Run Code Online (Sandbox Code Playgroud)

每次运行它都应该工作.