带有参数的 Powershell 函数抛出 null 异常

Sof*_*ant 4 powershell

该脚本抛出空异常,我不确定为什么会出现这种情况......

Function StopServices{    
    Param
    (
        $ServiceName,     
        $Remoteserver
    )
    write-host($Remoteserver)
    write-host($ServiceName)
    [System.ServiceProcess.ServiceController]$service = Get-Service -Name $ServiceName -ComputerName $Remoteserver
}
Run Code Online (Sandbox Code Playgroud)

写主机写入变量。Get-Service -ComputerName 方法抛出此异常:

powershell cannot validate argument on parameter 'computername' the argument is null or empty
Run Code Online (Sandbox Code Playgroud)

我想知道他们在说什么,两者都不空……

StopServices("DUMMY","VALUES")
Run Code Online (Sandbox Code Playgroud)

这些都不是空的。为什么它会抛出异常?

小智 6

与大多数语言不同,PowerShell 不使用括号来调用函数。

这意味着三件事:

  1. ("DUMMY","VALUES")实际上被解释为一个数组。换句话说,您只给出了StopServices 一个参数,而不是它所需要的两个参数。

  2. 该数组被分配给$ServiceName.

  3. 由于缺少参数,$Remoteserver被分配为 null。


要解决该问题,您需要StopServices像这样调用:

PS > StopServices DUMMY VALUES
Run Code Online (Sandbox Code Playgroud)


mik*_*kol 5

实际上,$RemoteServer空。

StopServices("Dummy", "Values")没有做你认为它在做的事情 - PowerShell 不像其他编程语言那样接受函数的参数。PowerShell 将您使用的语法解释为表达式,以创建一个包含两个值(“DUMMY”和“VALUES”)的数组,并将该数组存储在 $ServiceName 中,将 $RemoteServer 保留为 $null。

以下示例之一将为您提供您所追求的行为:

StopServices "Dummy" "Values"
Run Code Online (Sandbox Code Playgroud)

-或者-

StopServices -ServiceName "Dummy" -RemoteServer "Values"
Run Code Online (Sandbox Code Playgroud)