How do I remove Blank Space from File Names
Solution 1
Your code should work just fine, but since Get-ChildItem *.txt
lists only .txt files the last statement should remove the spaces from just the text files, giving you a result like this:
Cable Report 3413109.pdf
ControlList3.txt
Test Result Phase 2.doc
This should remove spaces from the names of all files in the folder:
Get-ChildItem -File | Rename-Item -NewName { $_.Name -replace ' ','' }
Prior to PowerShell v3 use this to restrict processing to just files:
Get-ChildItem | Where-Object { -not $_.PSIsContainer } |
Rename-Item -NewName { $_.Name -replace ' ','' }
Solution 2
something like this could work
$source = 'C:\temp\new'
$dest = 'C:\temp\new1'
Get-ChildItem $source | % {copy $_.FullName $(join-path $dest ($_.name -replace ' '))}
Solution 3
I think your script should almost work, except $_
isn't going to be defined as anything. By using the for-each cmdlet (%
), you assign it and then can use it.
Get-ChildItem *.txt | %{Rename-Item -NewName ( $_.Name -replace ' ','' )}
EDIT:
That interpretation was totally wrong. Some people seem to have found it useful, but as soon as you have something being piped, it appears that $_
references the object currently in the pipe. My bad.
Sohel
I love reading good books, fiction and non fiction, programming, testing and music. Traveling and seeing this beautiful world as much as I can is also one of my passions. I love to hang around with the loved ones.
Updated on June 04, 2022Comments
-
Sohel about 2 years
I am trying to remove blank spaces from many file names using PowerShell 3.0. Here is the code that I am working with:
$Files = Get-ChildItem -Path "C:\PowershellTests\With_Space" Copy-Item $Files.FullName -Destination C:\PowershellTests\Without_Space Set-Location -Path C:\PowershellTests\Without_Space Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace ' ','' }
For example: the With_Space directory has these files:
Cable Report 3413109.pdf Control List 3.txt Test Result Phase 2.doc
The Without_Space directory will need the above file name to be:
CableReport3413109.pdf ControlList3.txt TestResultPhase 2.doc
Currently, the script shows no error but it only copies the source files to the destination folder, but doesn't remove the spaces in file names.