也许这是一个粗糙的问题,但是我在powershell中有一个代码,该代码返回每个逻辑CPU内核的CPU使用率:
(Get-WmiObject -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor") | foreach-object { write-host "$($_.Name): $($_.PercentProcessorTime)" };
在powershell中,此代码返回以下内容:
0: 0
1: 6
10: 6
11: 0
2: 0
3: 19
4: 0
5: 12
6: 0
7: 0
8: 0
9: 12
_Total: 4
现在,我一直在尝试通过格式化命令以避免错误,在命令提示符下运行此命令来获得相同的输出。这就是我现在所拥有的:在CMD中:
Powershell.exe 'Get-WmiObject -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor"' ^| foreach-object { write-host "$($_.Name): $($_.PercentProcessorTime)" };
返回:
:
与powershell输出不同。我几乎可以肯定这是由于某种格式问题引起的,但是问题是什么呢?
"%__AppDir__%\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -Command "(Get-WmiObject -Query \"Select Name,PercentProcessorTime From Win32_PerfFormattedData_PerfOS_Processor\")|ForEach-Object{\"$($_.Name): $($_.PercentProcessorTime)\"}"
您会注意到我删除了Write-Host
命令,因为它不是必需的。
PowerShell -Help
以获取PowerShell.exe
有效参数。-Command
…
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.
注意inner双引号转义为
powershell -nopro -command "& {(Get-WmiObject -Query \"select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor\") | foreach-object { write-host \"$($_.Name): $($_.PercentProcessorTime)\" };}"
或powershell -nopro -command "& {(Get-WmiObject -Query """"select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor"""") | foreach-object { write-host """"$($_.Name): $($_.PercentProcessorTime)"""" };}"