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

SSH公钥认证远程执行带变量的PowerShell Get-Counter命令遇问题

问题分析

远程通过SSH执行带自定义格式化的Get-Counter命令时,变量$_.CookedValue和$env:NUMBER_OF_PROCESSORS失效,本质是本地Shell会预先解析命令中的$符号,导致远程PowerShell收到的命令里变量被破坏或丢失,而非远程PowerShell本身无法解析变量。

解决方案

根据本地执行环境(Windows Cmd/Linux/macOS Bash)选择对应的转义方式,确保$符号完整传递给远程PowerShell:

1. 本地为Windows Cmd环境

用^转义所有$,让Cmd不解析这些符号:

ssh user@win-host "Get-Counter '\Process(*)\% Processor Time' | Select-Object -ExpandProperty CounterSamples | Select-Object InstanceName, @{Name='CPU'; Expression={[math]::Round(^$_.CookedValue / ^$env:NUMBER_OF_PROCESSORS, 2)}}, CookedValue"

2. 本地为Linux/macOS Bash环境

两种可行方式:

  • 用单引号包裹整个PowerShell命令(需转义命令内部的单引号):
ssh user@win-host 'Get-Counter '\''\Process(*)\% Processor Time'\'' | Select-Object -ExpandProperty CounterSamples | Select-Object InstanceName, @{Name="CPU"; Expression={[math]::Round($_.CookedValue / $env:NUMBER_OF_PROCESSORS, 2)}}, CookedValue'
  • 用双引号包裹命令,并用\转义所有$:
ssh user@win-host "Get-Counter \"\\Process(*)\\% Processor Time\" | Select-Object -ExpandProperty CounterSamples | Select-Object InstanceName, @{Name='CPU'; Expression={[math]::Round(\$_.CookedValue / \$env:NUMBER_OF_PROCESSORS, 2)}}, CookedValue"

3. 自动化场景推荐方案(更可靠)

将命令封装为PowerShell脚本上传至远程机器,再通过SSH执行脚本,彻底避免转义问题:

  1. 本地创建get-cpu.ps1脚本:
Get-Counter '\Process(*)\% Processor Time' | 
    Select-Object -ExpandProperty CounterSamples | 
    Select-Object InstanceName, 
        @{Name='CPU'; Expression={[math]::Round($_.CookedValue / $env:NUMBER_OF_PROCESSORS, 2)}}, 
        CookedValue
  1. 上传脚本到远程机器:
scp get-cpu.ps1 user@win-host:C:\scripts\
  1. SSH执行脚本:
ssh user@win-host "powershell -ExecutionPolicy Bypass -File C:\scripts\get-cpu.ps1"

内容的提问来源于stack exchange,提问作者WatAmIDoing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:01:21