将powershell脚本输出重定向到文件失败

将powershell脚本输出重定向到文件失败,powershell,Powershell,我试图将脚本输出重定向到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

我试图将脚本输出重定向到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
脚本的结果是正确的

二,

一百

71582788

由此产生的误差是:

术语“>”未被识别为cmdlet、函数、, 脚本文件或可执行程序。检查是否键入了名称 正确,或者如果包含路径,请验证路径是否正确,并 请重试。已发布7个字符:2
+>使用Out文件而不是插入符号


您不能对
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
}
或者在您的情况下,您可以使用
选择
命令并将其输出到文件中

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循环。很好的调用。因此,是的,使用变量是可行的。MadTechnician,第一个选项不会返回任何错误,也不会返回任何数据。第二个选项运行得很好。Ami,已经试用了文件,但没有对我起作用。感谢你们两位(对不起,我的por英语)。问候您。Emilio Sancha MS Access MVP 2006-2011Matt,使用导出CSV,我遇到了另一个错误:不允许使用空管道元素。