1

I am lost with simple rename-item. Need to remove string contents from title of subfolders and rename the object (i.e. remove [4K]). I tried but I’m getting a “Rename-item: Cannot rename because item at … does not exist”. Sorry for dumb question but I’m trying to learn Powershell.

$path = "E:\test data" 

Get-ChildItem $path -Directory | Foreach-Object { 

    $file = $_.Fullname
    $file = $file -replace ('4K','')

    Write-Output $file

    Rename-Item -Path $_.Fullname -NewName $file
    Get-ChildItem "E:\test data"
} 
mklement0
  • 382,024
  • 64
  • 607
  • 775
ogcurtis
  • 21
  • 2
  • 2
    Use `Rename-Item -LiteralPath $_.FullName` - otherwise PowerShell will interpret `[4K]` in the original file path as a wildcard expression – Mathias R. Jessen Jul 19 '22 at 12:45
  • Alternatively, use the pipeline: `$_ | Rename-Item -NewName $file`, which is equivalent to using `-LiteralPath $_.FullName` for file-system items (and also works with non-file-system items supported by other providers). – mklement0 Jul 19 '22 at 15:41
  • As an aside: To remove substring `[4K]`, possibly preceded by spaces, use `$file -replace '\s+\[4K], ''` or just `$file -replace '\s+\[4K]` – mklement0 Jul 19 '22 at 15:46

0 Answers0