2011-12-17 69 views
4

我有兩個問題在這裏,爲什麼在腳本下面的函數,當我運行該腳本無法識別:爲什麼函數在第一次運行之後纔在本地可用?

腳本:

$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 
    } 
} 

我得到錯誤:

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 

in。

但是,如果我加載並在Windows Powershell ISE中運行它,它會在第一次給我這個錯誤,然後就像它已經「註冊」了該功能並在此之後工作。

如果是程序問題,我嘗試在頂部列出函數,沒有更好的運氣。

注意我已經試過喜歡簡單的功能:

Write-host "Say " 
Hello 

function Hello { 
    Write-host "hello" 
} 

隨着完全相同的結果/錯誤,它抱怨說你好不是功能....

此外,它還是贏了」每個工作只需在PowerShell中運行腳本(僅在ISE初次嘗試後)。

回答

12

在嘗試使用它之前,您需要聲明您的Select-Folder函數。腳本是從上到下閱讀的,因此在第一次嘗試使用Select-Folder時,它不知道這意味着什麼。

當你將它加載到Powershell ISE中時,它會發現第一次運行時它的含義,它仍然知道你第二次嘗試運行它(所以你不會得到錯誤)。

所以,如果你改變你的代碼:

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 

應該每次運行時的工作。

相關問題