今天在編寫PowerShell腳本的過程中,發現某個函數在多個PowerShell腳本中都用到了。但是該如何方便的在多PowerShell腳本中使用這個公用的函數呢?
假設Test這個函數就是要在多個PowerShell腳本中用到,Test函數內容:
Function Test($Name,$Age){
Write-Host "Name is $Name.Age is $Age"
}
將此函數輸入到PowerShell命令行
調用此函數,可以看到下方的輸出結果:
現在test01.ps1、test02.ps1、test03.ps1這三個腳本,要使用Test這個函數,如何在這三個腳本中方便的使用Test函數呢?
方法一
將Test函數的內容另存爲Test.ps1。在PowerShell命令行下輸入 .+空格+Test.ps1路徑,即可使用Test函數
以下是test01.ps1腳本的內容:
. E:\Test.ps1
Test Tom 11
Write-Host "test01"
執行結果:
方法二
將Test函數的內容另存爲Test.psm1。在PowerShell命令行下輸入Import-Module+空格+Test.psm1路徑,即可使用Test函數
以下是test02.ps1腳本的內容:
Import-Module E:\Test.psm1
Test Tom 11
Write-Host "test02"
執行結果:
Test.psm1爲自定義Module,裏面可以自定義函數。通過Get-Module命令可以看到,當前PowerShell環境多了一個Test Module
參考資料:http://www.mikepfeiffer.net/2010/06/how-to-add-functions-to-your-powershell-session/