2011-12-14 246 views
32

我開始使用PowerShell,並且正在'庫'文件中創建函數以提高可讀性,然後從我的'worker'腳本。如何在使用'使用PowerShell運行'執行PowerShell腳本時在另一個PowerShell腳本中調用函數

=================== Library file ========================== 
function ShowMessage($AValue) 
{ 
    $a = new-object -comobject wscript.shell 
    $b = $a.popup($AValue) 
} 
=================== End Library file ========================== 


=================== Worker file ========================== 
. {c:\scratch\b.ps1} 

ShowMessage "Hello" 
=================== End Worker file ========================== 

運行「工人」在PowerShell的IDE時,但是當我用鼠標右鍵單擊該工作人員文件,並選擇它無法找到函數「使用PowerShell運行」腳本正常工作「ShowMessage」。這兩個文件都在同一個文件夾中。這裏可能會發生什麼?

+0

另請注意,使用`&`調用腳本,例如。 `&「c:\ scratch \ b.ps1」`不會導入這些函數。 – ashes999 2017-08-10 21:57:11

回答

53

嘗試添加這樣的腳本:

=================== Worker file ========================== 
. "c:\scratch\b.ps1" 

ShowMessage "Hello" 
=================== End Worker file ========================== 
+2

工作正常,謝謝。 – 2011-12-14 09:26:59

+1

使用相對路徑時的注意事項:不要忘記在路徑前加上一個點。 」 \ b.ps1" `。對於psh來說,這是一個很新的東西,我不知道第一個點是修改範圍的操作符,在這個範圍內與路徑無關。請參閱[點來源表示法](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes)。 – 2017-11-03 13:02:04

11

在你的工人文件,點源庫文件,這將加載的所有內容(函數,變量等),以在全球範圍內,然後你將能夠從庫文件中調用函數。

=================== Worker file ========================== 
# dot-source library script 
# notice that you need to have a space 
# between the dot and the path of the script 
. c:\library.ps1 

ShowMessage -AValue Hello 
=================== End Worker file ======================