Reputation: 33
I need to write a file backwards line by line to another file. I can get it to work fine in the PowerShell window, but when I try to pipe it to an 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 a file on the Desktop, but doesn't give it any content.
If I simply don't pipe to Out-File
on the last line, it works fine, and prints the reversed file straight to the PowerShell window.
I have tried it with and without the single quotes, as well as using the -FilePath
option. Nothing's working. Any ideas out there?
Upvotes: 3
Views: 2571
Reputation: 201992
Since the -Append parameter is not used, Out-File will overwrite the file each time it processes a line from the source file. I suspect the last line of the source file is an empty line which is why you see nothing in the output file.
The proper way to do this is 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
Upvotes: 5