Renaming a file into multiple different names
10 hours ago, Navje said:Hey minibois,
thanks for reply, but somehow I do not get it right, I attached image, could you please check, what am I doing it wrong?
Thank you
The line I wrote I only tested in CMD. That seems to use a different syntax as compared to Powershell.
This CMD code:
FOR /F %i IN (names.txt) DO copy /y FileToCopy.txt files\%i.txt
(posted previously) in Powershell would be:
$fileToCopy = "C:\FileToCopy.txt" $placeToCopyTo = "C:\Files\" $namesFile = "C:\names.txt" $fileExtension = $fileToCopy.extension foreach($name in Get-Content $namesFile) { $pathToCopyTo = "$placeToCopyTo$name.$fileExtension" if(($name -match $regex) -And (![System.IO.File]::Exists($pathToCopyTo))) { Copy-Item $fileToCopy -Destination $placeToCopyTo$name.$fileExtension } }
I added some more stuff to this script so there is less work for you to do.
You only have to tell the program:
- The file you want to copy (line 1)
- The place you want to copy it to (leave empty if you want it to copy in the folder the Powershell is currently in with cd) (line 2)
- The names file (line 3)
It also checks if the path you're trying to write to exists already. If the file name already exists, it just doesn't copy.
i.e. if you have "exampleA" in your names.txt file, but already have
Depending on your usage, you could consider saving the names of the files it couldn't make. The reason it couldn't create a file is because there was already a file with that name, but an older file; thus you might want a newer version or something..
That depends on your workflow.
Hope this code helps!
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now