1
votes

I'm trying to redirect the script output to a txt but it fails

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

the result of the script is correct

2

100

71582788

And the resulting error is:

"The term '>' is not recognized as the name of a cmdlet, function, script file or executable program. Check if you typed the name correctly, or if a path included, verify that the path is correct and try again. Published 7 Character: 2 +> <<<< C: \ temp \ Test.txt + CategoryInfo: ObjectNotFound: (>: String) [], CommandNotFoundException + FullyQualifiedErrorId: CommandNotFoundException"

I can't need to say that the path is correct.

If I run for instance:

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

that run's OK

Any idea what I'm doing wrong?

Thanks in advance.

Kind Regards.

Emilio Sancha MS Access MVP 2006-2011

2

2 Answers

3
votes

You can not pipe output of a ForEach loop. You can capture it in a variable, or pipe things inside the loop, but you cannot pipe the output of the entire loop in general. There's a couple things you could try...

Capture all output from the loop in a variable, and then output that variable to a file:

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

Or you could output inside the loop:

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
}

Or in your case you could just use a Select command and output that to a file

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