You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

错误原因

  1. 变量作用域隔离:Invoke-Command的脚本块运行在远程计算机的独立会话中,默认无法直接访问本地函数的$comp和$procname参数。脚本块内的$comp会被解析为远程会话中未定义的变量,因此为空,触发Get-Process的ComputerName参数非空验证错误。
  2. 冗余参数调用:已经通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 22:05:59