$timeout = new-timespan -Minutes 1
$sw = [diagnostics.stopwatch]::StartNew()
$path = "d:\powershell\test.csv"
"Processor Load, Available Memory(MB), Max Memory(Bytes)" >> $path
while ($sw.elapsed -lt $timeout)
{
$a = gwmi -query "Select * from win32_processor"
$b = gwmi -query "Select * from win32_perfrawdata_perfOS_memory"
$c = gwmi -query "Select * from win32_physicalmemory"
$date = Get-Date -format s
$a.loadpercentage + "," + $b.availableMbytes + "," + $c.capacity >> $path
start-sleep -seconds 5
}
所以我只是想了解一下发生了什么的快照。我不只是因为理由而在perfmon中打开它。基本上我希望在提到的CSV文件中得到逗号分隔的输出。它适用于单个变量,但是当我尝试添加第二个变量或文本时,我会收到以下错误。
Cannot convert value ", test" to type "System.Int32". Error: "Input string was not in a
correct format."
At D:\powershell\VDIPerfMon.ps1:14 char:21
+ $a.loadpercentage + <<<< ", test" >> $path
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
如何解决此问题?
答案 0 :(得分:3)
使用+
运算符时,左侧的PowerShell查找确定表达式的结果类型。它在+
的左侧看到一个int,在右侧看到一个字符串(不能转换为int)。试试这种方式:
"$($a.loadpercentage), $($b.availableMbytes), $($c.capacity)" >> $path
同样在你编写标题的地方,你可能不想附加,即为了覆盖旧的尝试:
"Processor Load, Available Memory(MB), Max Memory(Bytes)" > $path
答案 1 :(得分:2)
错误是因为$a.loadpercentage
是一个int。然后,您尝试添加int和字符串。
一种解决方法是显式调用.ToString()
$a.loadpercentage.ToString() + "," + $b.availableMbytes.ToString() + "," + $c.capacity.ToString() >> $path
另一种方法是PowerShell数组连接运算符。它很容易,类型无关紧要:
($a.loadpercentage, $b.availableMbytes, $c.capacity) -join "," |
Add-Content $path
另一种方法是使用字符串格式化程序。这将使您可以轻松控制每个值的精度和显示:
'{0},{1},{2}' -f $a.loadpercentage, $b.availableMbytes, $c.capacity