Kahn Kah
Kahn Kah

Reputation: 1453

Remove leading trailling spaces in PowerShell returns error

My script should loop folders and remove leading/trailing spaces in a folder name. However when I do this :

$path = "E:\Folders\Bravo\"
$files = Get-ChildItem -Path $path -Recurse |?{_.PSIsContainer}
Foreach($file in $files)
{
    Rename-Item -Path $file.FullName -NewName ($file.Name).Trim()
}

I get the following error:

Rename-Item : Source and destination path must be different.

Why is this?

Upvotes: 0

Views: 370

Answers (2)

js2010
js2010

Reputation: 27408

This is how I would do it, filtering out names that don't need fixing. Although even in cmd, I couldn't make a directory name ending in a space.

get-childitem -recurse -directory | 
  where name -match '^ | $' | 
  rename-item -newname { $_.name.trim() } -whatif

What if: Performing the operation "Rename Directory" on target
      "Item: C:\users\admin\foo\ foo1 
Destination: C:\users\admin\foo\foo1".

What if: Performing the operation "Rename Directory" on target
      "Item: C:\users\admin\foo\ foo1\ foo3 
Destination: C:\users\admin\foo\ foo1\foo3".

Upvotes: 0

Theo
Theo

Reputation: 61013

First thing I noticed was that you omitted the $ in ?{_.PSIsContainer}. Also, nowadays you can use switch -Directory on Get-ChildItem, so there is no need for doing the Where-Object clause to filter for folders afterwards.

Then, If you add -ErrorAction SilentlyContinue to the Rename-Item cmdlet, you won;t see that error anymore.

$path = "E:\Folders\Bravo"
$folders = Get-ChildItem -Path $path -Recurse -Directory
foreach($folder in $folders) {
    Rename-Item -Path $folder.FullName -NewName ($folder.Name).Trim() -ErrorAction SilentlyContinue
}

However, it may be a better approach to not silence the errors, but to filter on foldernames that actually have leading and/or trailing whitespace characters:

$path = "E:\Folders\Bravo"
$folders = Get-ChildItem -Path $path -Recurse -Directory | Where-Object { $_.Name -match '^\s|\s$' }
foreach($folder in $folders) {
    Rename-Item -Path $folder.FullName -NewName ($folder.Name).Trim()
}

I have also changed some variable names, as you are interested in folders, not files

Regex details:

           Match either the regular expression below (attempting the next alternative only if this one fails)
   ^       Assert position at the beginning of the string
   \s      Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
|          Or match regular expression number 2 below (the entire match attempt fails if this one fails to match)
   \s      Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   $       Assert position at the end of the string (or before the line break at the end of the string, if any)

Upvotes: 2

Related Questions