PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] How do I remove a leading or trailing blank space in file name with PowerShell?

 September 05, 2022     powershell, trim     No comments   

Issue

I'm basically trying to trim() any filenames that have a leading or trailing space at the end of the name. This is the code I've got so far

$foldersToCheck = "$env:userprofile\documents", "$env:userprofile\pictures", "$env:userprofile\desktop"
foreach ($folder in $foldersToCheck) {
    get-childitem -path $folder -recurse | foreach-object {
        if ($_.name.startswith(" ") -or $_.name.endswith(" ")) {
            $newName = $_.name.trim()
            rename-item -path $_ -newName $newname
        }
    }
}

If I create a test file (c:\users\someusername\desktop\ test.txt), then I receive this error

rename-item : Cannot rename because item at ' test.txt' does not exist.
    At line:6 char:13
    +             rename-item -path $_ -newName $newname
    +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
        + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

So, it looks like it found the file that needs to be renamed, but then says it doesnt exist.


Solution

The problem here is that PowerShell resolves $_ to just the file name when attempting to convert it to a string it can bind to -Path.

Explicitly pass the full path of the file and it'll work:

Rename-Item -Path $_.FullName -NewName $newname

Alternatively, pipe the $_ file object to Rename-Item and PowerShell will automatically figure out that it needs to bind $_.FullName to Rename-Item's -LiteralPath parameter:

$_ |Rename-Item -NewName $newname

You can also turn the whole loop into a single pipeline, and then take advantage of a pipeline-bound expression against -NewName:

$foldersToCheck |Get-ChildItem -Recurse |Rename-Item -NewName { $_.Name.Trim() }

If the existing Name and the -NewName values are the same, Rename-Item will just leave the files alone anyway :)



Answered By - Mathias R. Jessen
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing