Powershell Rename-Item cannot rename

My powershell script:

$dst = 'C:\Temp'

#Get all folders in $dst
$folders = Get-ChildItem $dst | ?{ $_.PSIsContainer }

foreach($folder in $folders)
{
    $cnt = (Get-ChildItem -filter *.txt $folder | Measure-Object).Count

    $base = ($folder.FullName -split " \[.*\]$")[0]
    $newname = $("{0} [{1}]" -f $base,$cnt)

    Write-Host $folder.FullName "->" $newname

    Rename-Item $folder.FullName $newname
}

Problem

In my first run, I get the following:

PS C:\Temp> C:\Temp\RenameFolders.ps1
C:\Temp\m1 -> C:\Temp\m1 [1]

On my second run, I get the following:

PS C:\Temp> C:\Temp\RenameFolders.ps1
C:\Temp\m1 [1] -> C:\Temp\m1 [0]
Rename-Item : Cannot rename because item at 'C:\Temp\m1 [1]' does not exist.
At C:\Temp\RenameFolders.ps1:15 char:5
+     Rename-Item $folder.FullName $newname
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

I know the problem is in '[' and ']', but I really can't understand why.

Can someone explain to me why this is a problem?

+4
source share
1 answer

If you use the PS 3+ add-LiteralPath switch for your renaming:

Rename-Item -LiteralPath $folder.FullName $newname

otherwise use Move-Item

Move-Item -LiteralPath $folder.FullName $newname

Powershell does not like square brackets in file names, in more detail post :

This became a problem with V2 when they added square brackets to the wildcard set to support "blobbing".

get-help about_wildcards:

Windows PowerShell .


  • * A, ag, Apple banana         

    ? ? N a, in, on ran                           

    [] [a-l] ook book, cook, look taken         

    [] [bc] ook book, cook hook         

[ ] .

+14

Source: https://habr.com/ru/post/1537879/


All Articles