Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

powershell Rename-Item fail to 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
}

The problem

On my first run I get this:

PS C:Temp> C:TempRenameFolders.ps1
C:Tempm1 -> C:Tempm1 [1]

On my second run I get this:

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

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

Can someone explain me why is that a problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are running PS 3+ add -LiteralPath switch to your rename:

Rename-Item -LiteralPath $folder.FullName $newname

otherwise use Move-Item

Move-Item -LiteralPath $folder.FullName $newname

Powershell doesn't like square brackets in filenames, more in the following post:

This became an issue with V2 when they added the square brackets to the wildcard character set to support "blobbing".

From get-help about_wildcards:

Windows PowerShell supports the following wildcard characters.

Wildcard Description Example Match No match


  • Matches zero or a* A, ag, Apple banana more characters

    ? Matches exactly ?n an, in, on ran one character in the specified position

    [ ] Matches a range [a-l]ook book, cook, look took of characters

    [ ] Matches specified [bc]ook book, cook hook characters

[ and ] are special characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...