这是
的后续在PowerShell中编写cmdlet
我得到了关于如何将函数声明为cmdlet的链接:
https://learn.microsoft.com/en - us/powershell/scripting/learn/ps101/09 functions?view=powershell - 7.1 #先进功能
使用另一个页面
https://learn.microsoft.com/en us/powershell/module/microsoft.powershell.core/about/about_functions_advanced?view=powershell - 7.1
我试着
function Send-Greeting
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string] $Name
)
Process
{
Write-Host ("Hello " + $Name + "!")
}
}
我运行了这个脚本,但它没有像预期的那样工作:
PS > .Send-Greeting.ps1
PS > Send-Greeting Joe Send-Greeting : The term 'Send-Greeting' 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 again.
At line:1 char:1
+ Send-Greeting Joe
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Send-Greeting:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
如何将我的新cmd命令导出到PowerShell环境中,以便我可以将其用作内置cmd命令?
三件事:
- 将此代码放入一个模块,即.psm1文件
- 使用export - modulemember cmdlet导出函数
- 使用import - module cmdlet 将该模块导入PowerShell环境
保存为Send-Greeting.psm1:
function Send-Greeting
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string] $Name
)
Process
{
Write-Host ("Hello " + $Name + "!")
}
}
Export-ModuleMember -Function Send-Greeting
和调用
PS > Import-Module .Send-Greeting.psm1
在那之后,整个事情都工作了:
PS > Send-Greeting -Name Joe
Hello Joe!
文学:
https://learn.microsoft.com/en - us/powershell/module/microsoft.powershell.core/export modulemember?view=powershell - 7.1
https://superuser.com/a/1583330/216969