PowerShell 参数 - "param" 不被识别为 cmdlet 的名称

3

请考虑:

notepad # Starts Notepad
Get-Process notepad # Finds the processes named notepad
param(
    [Parameter(Mandatory=$true)][string]$ProcessID
) #This should request user input, and store it in a variable#
Stop-Process $ProcessID # Stops the input process ID#

当我尝试运行这个时,遇到:

param : The term 'param' 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:3 char:1
+ param(
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Stop-Process : Cannot bind parameter 'InputObject'. Cannot convert the "A" value of type "System.String" to type "System.Diagnostics.Process".
At line:6 char:14
+ Stop-Process $ProcessID
+              ~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Stop-Process], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.StopProcessCommand

我对PowerShell完全不熟悉,目前非常困惑。可能是因为我不理解它,也可能是因为现在还很早。


1
"Param" 需要在您的函数或脚本开头,可以出现在一些注释之后,但必须在任何其他命令之前。 - Micky Balladelli
有趣。 代码中是否有任何一种方式可以在稍后给予用户输入?最终行的功能依赖于字符串。 - AxisOfTechnology
2个回答

3

如果您的脚本需要参数,则Param关键字必须是脚本中的第一条语句。

但是,您可以使用Read-Host命令让用户稍后输入:

$processId = Read-Host "Enter the PID of the process to kill"

太好了!非常感谢! - AxisOfTechnology

0

移除参数并使用Read-Host cmdlet后的最终结果:

notepad
Get-Process notepad
$ProcessID = Read-Host "Enter the PID of the process to kill"
Stop-Process $ProcessID

它运行得非常顺畅。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接