powershellrenamefile-renamebatch-rename

Renaming of files and content within files using Powershell


Can somebody please support for renaming of files and content within files using Powershell:

Tried a bit around including other parameters on the basis of other posts on the topic here but stumbled on access denied issues and others. It only worked - excluding the extra requirements mentioned - when providing the individual subfolders for $filePath using the following script. Please advice for making it work for the requirements mentioned:

$filePath = "C:\root_folder"
Get-ChildItem $filePath -Recurse | ForEach {
     (Get-Content $_ | ForEach  { $_ -creplace 'abc_123', 'def_123' }) |
     Set-Content $_
}

Solution


  • Therefore, you're probably looking for something like the following:

    $filePath = "C:\root_folder"
    $include = '*.txt', '*.xml' # adapt as needed
    Get-ChildItem -File $filePath -Recurse -Include $include | 
      Rename-Item -WhatIf -PassThru -NewName { $_.Name -replace 'uvw', 'xyz' } |
      ForEach-Object {
         # NOTE: You may have to use an -Encoding argument here to ensure
         #       the desired character encoding.
         ($_ | Get-Content -Raw) -replace 'abc_123', 'def_123' |
           Set-Content -NoNewLine -LiteralPath $_.FullName
      }
    

    Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf and re-execute once you're sure the operation will do what you want.