今天在编写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/