Powershell Out-File doesn't work as expected with backward string
I need to write a file backwards line by line to another file. I can get it to work fine in a PowerShell window, but when I try to connect it to Out-File
, it doesn't work. This is my script:
Get-Content C:\Users\Administrator\Desktop\files.txt | ForEach-Object {
$text = $_.toCharArray()
[Array]::Reverse($text)
-join $text | Out-File 'C:\Users\Administrator\Desktop\reversed.txt'
}
This actually creates the file on the desktop, but doesn't give it any content.
If I just don't connect to Out-File
on the last line, it works fine and prints the reverse file right into the PowerShell window.
I've tried it with and without single quotes and using the option -FilePath
. Nothing works. Any ideas out there?
Since the -Append parameter is not used, Out-File will overwrite the file every time it processes a line from the original file. I suspect the last line of the source file is an empty line, so you don't see anything in the output file.
The correct way to do it, as @TheMadTechnician suggests:
Get-Content C:\Users\Administrator\Desktop\files.txt |
ForEach-Object {
$text = $_.toCharArray()
[Array]::Reverse($text)
-join $text
} |
Out-File C:\Users\Administrator\Desktop\reversed.txt