PowerShell远程进程关闭函数调用Invoke-Command出现参数验证错误
远程PowerShell进程关闭函数的错误原因分析
原函数代码
function close-process { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$comp, [String] $procname ) $procItems = Invoke-Command -ComputerName $comp -ScriptBlock {Get-Process -ComputerName $comp | Where-Object Name -Like "*$procname*"} if ($procItems) { Write-Host "Mentioned process has been found" -ForegroundColor DarkBlue }else { Write-Host "No process found with mentioned name" } Invoke-Command -ComputerName $comp -ScriptBlock {Get-Process -ComputerName $comp | Where-Object Name -Like "*$procname*" | Stop-Process} } close-process -comp COMPUTER01 -procname notepad
报错信息
Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. + CategoryInfo : InvalidData: (:) [Get-Process], ParameterBindingValida tionException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell. Commands.GetProcessCommand + PSComputerName : COMPUTER01
错误原因
- 变量作用域隔离:
Invoke-Command的脚本块运行在远程计算机的独立会话中,默认无法直接访问本地函数的$comp和$procname参数。脚本块内的$comp会被解析为远程会话中未定义的变量,因此为空,触发Get-Process的ComputerName参数非空验证错误。 - 冗余参数调用:已经通过
Invoke-Command -ComputerName $comp指定了目标远程机器,脚本块内执行Get-Process时无需再添加-ComputerName $comp——脚本块本身就是在目标机器上运行,直接调用Get-Process即可获取该机器的进程列表。
修正后的函数代码
使用PowerShell的Using:作用域将本地变量传递到远程脚本块中,同时移除冗余参数:
function close-process { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$comp, [String] $procname ) $procItems = Invoke-Command -ComputerName $comp -ScriptBlock { Get-Process | Where-Object Name -Like "*$Using:procname*" } if ($procItems) { Write-Host "Mentioned process has been found" -ForegroundColor DarkBlue Invoke-Command -ComputerName $comp -ScriptBlock { Get-Process | Where-Object Name -Like "*$Using:procname*" | Stop-Process } } else { Write-Host "No process found with mentioned name" } } close-process -comp COMPUTER01 -procname notepad
内容的提问来源于stack exchange,提问作者Stan Di
相关产品推荐
相关产品推荐

