Powershell script to move and rename files and storing into a variable

Eoghan Kerry 21 Reputation points
2022-04-11T22:27:18.31+00:00

Honestly I'm going into powershell pretty cold with a very basic knowledge. I've been searching but I'm having trouble finding out how to do specific elements of what I'm looking to do, namely grab a filename, put it into a variable and use that variable several times before the script ends.

I want to read the filename of MainImage.jpg and store it into a variable.

Then copy it to z:\WEB1

then copy-tem \path\image2.jpg to z:WEB2

then rename image2 in z:\WEB2 to the filename stored in the variable.

and so on 2 more times, image3 to WEB3, rename from variable, image 4 to WEB4, rename from variable

Any help to get me unstuck? Brain is a bit melted and having trouble figuring it out on my own.

Thanks.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,355 questions
{count} votes

Accepted answer
  1. Rich Matheisen 44,696 Reputation points
    2022-04-12T01:45:18.913+00:00

    Is this what you mean?

    $n = Read-Host "Enter file name (MainImage.jpg)"
    Copy-Item -Path .\$n -Destination z:\WEB1   # <=== ASSUMES the current directory (".") in the Path value. Change it to whatever is correct!
    Copy-Item -Path \path\image2.jpg -Destination "z:\WEB2\$n"
    Copy-Item -Path \path\image3.jpg -Destination "z:\WEB3\$n"
    Copy-Item -Path \path\image4.jpg -Destination "z:\WEB4\$n"
    

    The "\path\" part used in the Copy-Item doesn't look correct for a UNC name, and it should have either a "." or a "X:" if it's a file system path (where "X" is, of course, whatever drive letter is appropriate)

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful