I'm new to powershell and wanted to know if there's a way to remove a character from a file name. The character I'm trying to remove is a dash "-" and sometimes there are 2 or 3 dashes in the file name. Is it possible to have it rename files that have a dash in them?
Asked
Active
Viewed 2.3k times
2 Answers
8
Get-Item .\some-file-with-hyphens.txt | ForEach-Object {
Rename-Item $_ ($_.Name -replace "-", "")
}
This question may be more suitable for SuperUser.

Ansgar Wiechers
- 193,178
- 25
- 254
- 328
-
Can I use a wildcard for the Get-Item: 'Get-Item .\*.tif' ? – Noesis Sep 25 '12 at 21:27
-
1Yes, you can use wildcards in `Get-Item`. And you format code by putting it between backticks: \`code\` – Ansgar Wiechers Sep 25 '12 at 21:37
-
Thank you, it worked!! I'm trying to format code in the comments with backticks ' this is code ' - it doesn't seem to work, i feel like a newb. – Noesis Sep 25 '12 at 22:16
-
Those are single quotes, not backticks. Not sure what keyboard layout you use, but on US keyboards the backtick is left of the <1>. – Ansgar Wiechers Sep 25 '12 at 22:23
6
To remove or replace characters in a file name use single quotes '
and for "special" characters escape them with a backslash \
so the regular expression parser takes it literally.
The following removes the $
(dollar sign) from all file names in your current directory:
Get-Item * | ForEach-Object { rename-item $_ ($_.Name -replace '\$', '') }
the following is the same as above using the shorter alias for each command:
gi * | % { rni $_ ($_.Name -replace '\$', '') }
The following is removing the standard character "Z
" from all file names in your current directory:
gi * | % { rni $_ ($_.Name -replace 'Z', '') }

Invictuz
- 61
- 1
- 4