【问题标题】:Redirecting powershell script output to a file fails将 powershell 脚本输出重定向到文件失败
【发布时间】:2015-11-09 19:33:26
【问题描述】:

我正在尝试将脚本输出重定向到 txt,但它失败了

Clear-Host
$Elementos =Get-WmiObject Win32_Battery -namespace 'root\CIMV2' 
foreach ($Elemento in $Elementos) { 
$Elemento.BatteryStatus 
$Elemento.EstimatedChargeRemaining 
$Elemento.EstimatedRunTime}     >C:\temp\Prueba.txt

脚本的结果是正确的

2

100

71582788

由此产生的错误是:

"术语 '>' 未被识别为 cmdlet、函数的名称, 脚本文件或可执行程序。检查您是否输入了名称 正确,或者如果包含路径,请验证路径是否正确,并且 再试一次。已发表 7 字符:2 +> : String) [], CommandNotFoundException + FullyQualifiedErrorId: CommandNotFoundException"

我不用说路径是正确的。

例如,如果我跑步:

PowerShell (Get-WmiObject win32_battery).estimatedChargeRemaining > C:\temp\Prueba.txt

运行正常

知道我做错了什么吗?

提前致谢。

亲切的问候。

埃米利奥·桑查 MS Access MVP 2006-2011

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您不能通过管道输出 ForEach 循环。您可以在变量中捕获它,或者在循环内通过管道传输内容,但通常不能通过管道传输整个循环的输出。您可以尝试几件事...

    将循环的所有输出捕获到一个变量中,然后将该变量输出到一个文件中:

    Clear-Host
    $Elementos =Get-WmiObject Win32_Battery -namespace 'root\CIMV2' 
    $Output = foreach ($Elemento in $Elementos) { 
        $Elemento.BatteryStatus 
        $Elemento.EstimatedChargeRemaining 
        $Elemento.EstimatedRunTime
    }
    $Output>C:\temp\Prueba.txt
    

    或者你可以在循环内输出:

    Clear-Host
    $Elementos =Get-WmiObject Win32_Battery -namespace 'root\CIMV2' 
    foreach ($Elemento in $Elementos) { 
        $Elemento.BatteryStatus>>C:\temp\Prueba.txt
        $Elemento.EstimatedChargeRemaining>>C:\temp\Prueba.txt
        $Elemento.EstimatedRunTime>>C:\temp\Prueba.txt
    }
    

    或者在您的情况下,您可以使用 Select 命令并将其输出到文件

    Clear-Host
    $Elementos =Get-WmiObject Win32_Battery -namespace 'root\CIMV2' 
    $Elementos | Select BatteryStatus,EstimatedChargeRemaining,EstimatedRunTime | Export-CSV C:\Temp\Prueba.txt -notype
    

    【讨论】:

    • Export-CSV 可能更适合您的最后一个示例
    • 我没有看到 For-Each 循环。好决定。所以是的,使用变量将是要走的路。
    • TheMadTechnician,第一个选项不返回任何错误,也不返回任何数据。第二个完美运行。 Ami,已经尝试过使用 Out-File 并没有为我工作。谢谢你们两个(对不起我的英语)。亲切的问候。 Emilio Sancha MS Access MVP 2006-2011
    • Matt,使用 Export-CSV 我遇到了另一个错误:不允许使用空管道元素。
    【解决方案2】:

    使用 Out-File 代替插入符号。

    https://technet.microsoft.com/en-us/library/ee176924.aspx

    【讨论】:

    • 虽然建议可以,但根本解决不了他的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 2017-08-31
    相关资源
    最近更新 更多