【问题标题】:Powershell is not returning the right values for csvPowershell 没有为 csv 返回正确的值
【发布时间】:2019-05-05 11:09:39
【问题描述】:

我有一个小脚本,可以每 60 秒升级一次 PC 电池电量并写入一个文本文件(我试过 export-csv)。但是,脚本只是不断将相同的值写入文件,并且不会更改或正确递增。

$csvfile = "c:\Users\PC-battery.csv"
$Battstatus = (Get-WmiObject -Class Win32_Battery).estimatedchargeremaining 
while ($true) 
    {
        "$Battstatus" | Add-Content $csvfile   
    Start-Sleep -Seconds 60
    }

【问题讨论】:

  • 您只阅读源一次。我不认为结果将是一个实时 WMI 对象,所以你总是会看到相同的结果。 ///// 尝试将查询移动到while 循环... [grin]

标签: powershell export-to-csv


【解决方案1】:

您遇到的问题是,$Battstatus 的值在您第一次设置后从未更新。您向系统询问电池状态一次,然后进入一个无限循环,您只需返回该值即可。

相反,您需要检索循环内的值,如下所示:

$csvfile = "c:\Users\PC-battery.csv"
while ($true) 
    {
        $Battstatus = (Get-WmiObject -Class Win32_Battery).estimatedchargeremaining 
        $Battstatus | Add-Content $csvfile   
        Start-Sleep -Seconds 60
    }

我还从您的变量引用中去掉了引号,因为我认为它们没有必要(除非我误解了变量的值,如果需要,您可以将它们重新加上)。

还要注意:Add-Content 只是附加到一个文件,它不支持 CSV。您可以利用 PowerShell 对对象的使用,并将所有电池信息放入适当的 CSV,如下所示:

$csvfile = "c:\Users\PC-battery.csv"
while ($true) 
    {
        $Battstatus = Get-WmiObject -Class Win32_Battery
        $Battstatus | Export-Csv $csvfile -NoTypeInformation -Append   
        Start-Sleep -Seconds 60
    }

(未经测试,可能有一些怪癖)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2014-11-26
    • 2019-03-21
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    相关资源
    最近更新 更多