如何直接在powershell命令提示符下执行powershell函数,如下所示
>>PS C:\Users\tijo.scaria> Function Test-Demo
>> {
>> Param ($Param1)
>> Begin{ write-host "Starting"}
>> Process{ write-host "processing" $_ for $Param1}
>> End{write-host "Ending"}
>> }
我该如何调用此功能。 我通过按CNTRL + C并退出该功能并尝试执行以下命令
>>PS C:\Users\tijo.scaria> Echo Testing1, Testing2 | Test-Demo Sample
但我收到以下错误
Test-Demo : The term 'Test-Demo' is not recognized as the name of a cmdlet, function, script file, or operableprogram. 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:27+ Echo Testing1, Testing2 |Test-Demo Sample
如何直接从命令窗口
执行功能答案 0 :(得分:2)
你的问题是按下control-C来中止函数定义,而不是通过按下返回来完成它:
PS C:\Windows\system32> function Test-Demo
>> {
>> Param ($Param1)
>> Begin { Write-Host "Starting" }
>> Process { Write-Host "Processing" $_ for $Param1 }
>> End { Write-Host "Ending" }
>> }
>>
PS C:\Windows\system32> Test-Demo "Hello"
Starting
Processing for Hello
Ending
如果您想以交互方式使用功能定义,但应使用Powershell ISE v3或更高版本。它使这些事情变得更容易(在ISE中,您可以使用shift-return输入多行命令,然后将它们作为单个连贯命令拉回,编辑,插入和删除行)或只需键入文件窗口并执行任何选定的组()。
所以在Powershell ISE v3中:
PS C:\> function Test-Demo
{
Param ($Param1)
Begin { Write-Host "Starting" }
Process { Write-Host "Processing" $_ for $Param1 }
End { Write-Host "Ending" }
}
PS C:\> Test-Demo "Hello"
Starting
Processing for Hello
Ending
PS C:\>
然后向上箭头两次带回整个函数定义。
答案 1 :(得分:0)
我认为你必须创建一个包含该功能的PS1文件。然后只需加载该文件并调用您开发的函数:
. "FunctionFile.ps1"
Test-Demo "Testing1"