Creating a script in order to copy and rename files and folders from one location to another i was happy to find some easy Powershell Scripts. So I’d like to share some important and interesting ones.
If you like to copy a folder from location A to location B you can simply use this script:
Copy-Item -Recurse -LiteralPath $SourceFolder -Destination $TargetFolder
This one will just copy your complete folder. Cause of “-Recurse” it will also copy the complete subfolders and subitems.
Rename Files
If you like to rename Files inside a Folder and all subfolder you can use this script. The special thing is, that there is a filterscript. This filter is used in order to find all files which containing special characters. All other files we don’t care. After we get all files with special characters we use Rename-item with same expression.
Get-ChildItem -Recurse -path $baseTarget -File | Where-object -FilterScript { $_.Name -match '[^.^a-zA-Z0-9_]' } | Rename-Item -NewName { $(Convert-Umlaut -Text $_.Name) -replace '[^.^a-zA-Z0-9_]','_'
In this Script there is another special: In the rename-item area, we use a function for the filename and replace “Umlaute” like “ä ö ü” and replace them with ae, oe, ue.
Rename Folders
If you wish to rename Folders it’s almost the same but, we have to define first -Directory and we also make a filterscript.
Get-ChildItem -path $baseTarget -Directory -Recurse | Where-object -FilterScript { $_.Name -match '[^a-zA-Z0-9_]' } | Rename-Item -NewName { $(Convert-Umlaut -Text $_.Name) -replace '[^a-zA-Z0-9_]','_' }
Why Filterscript?
I am using the filter script for one reason. If i don’t use it, and the foldername does not contain special characters then the script tries to rename the folder anyway. But then it tries to change the Name from “Example1” to “Example1” and of course it will throw an error which tells you that the source and destination cannot be the same. And of course there is no need to change the foldername if it does not contain a special character.
Hope it helps you.