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执行脚本,彻底避免转义问题:
- 本地创建
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
- 上传脚本到远程机器:
scp get-cpu.ps1 user@win-host:C:\scripts\
- SSH执行脚本:
ssh user@win-host "powershell -ExecutionPolicy Bypass -File C:\scripts\get-cpu.ps1"
内容的提问来源于stack exchange,提问作者WatAmIDoing
相关产品推荐
相关产品推荐

