Powershell参数错误?

时间:2015-01-26 10:44:14

标签: variables powershell input parameters

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很新,我因为这个问题而感到非常困惑。要么是因为我不理解,要么是因为它是在清晨。

2 个答案:

答案 0 :(得分:0)

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

但是,您可以稍后使用Read-Host cmdlet:

要求用户输入
$processId = Read-Host "Enter the PID of the process to kill"

答案 1 :(得分:0)

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

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

完美无瑕地工作。 谢谢!