How do I reverse the order of the lines in multiple files of a folder with a PowerShell script?

Raam4 21 Reputation points
2021-07-29T00:11:25.747+00:00

This script, saved to a .ps1 file which I run as an admin is not working:-
$x = Get-Content -Path C:\Users\SKY\Desktop\curede*.*
$x | Out-File -FilePath C:\Users\SKY\Desktop\curede*.*

Please tell me how to reverse the order of the lines in multiple files of a folder with a PowerShell script.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,524 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 46,711 Reputation points
    2021-07-29T02:04:54.66+00:00

    How about this?

    Get-ChildItem c:\junk\123*.txt |
        ForEach-Object{
            $x = Get-Content $_
            [Array]::Reverse($x) 
            $x |
                Out-File $_
        }
    

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 46,711 Reputation points
    2021-07-29T14:48:06.41+00:00

    Are there sub-directories beneath "C:\Users\SKY\Desktop\curede\"? The Get-ChildItem, as written by you, will return not only files but also directories. If you only want files, add the "-File" parameter.

    Note that the code I posted had no need for the "-File" parameter, nor does it include any error checking (e.g., what if $x contains a $null value?).


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.