How to move a series of files to a folder using variables in Powershell?

1939 views powershell
1

I am struggling to move a series of files to a folder in Powershell. I have managed to do it when explicitly referencing the path name but can't manage to do the same when using a variable name.

This is a simplified version of my code.

files = Get-ChildItem C:\Users\edward.muldrew\Documents\35759175  
$pathDestination = "C:\Users\edward.muldrew\Documents\35759175\Test"
for ($i=0; $i -lt $files.Count; $i++) {
     $pathSource = "C:\Users\edward.muldrew\Documents\35759175\$files[$i]"
     Move-Item $pathSource -Destination $pathDestination

Any help would be much appreciated

answered question

1 Answer

7

Instead of put the variable inside of your string you can set it outside of the string and concat the value of it and your string:

files = Get-ChildItem C:\Users\edward.muldrew\Documents\35759175  
$pathDestination = "C:\Users\edward.muldrew\Documents\35759175\Test"
for ($i=0; $i -lt $files.Count; $i++) {
     $pathSource = "C:\Users\edward.muldrew\Documents\35759175\" + $files[$i]
     Move-Item $pathSource -Destination $pathDestination

EDIT: I have seen that powershell let you put the variables inside the string without concatening by surrounding them inside $()

files = Get-ChildItem C:\Users\edward.muldrew\Documents\35759175  
$pathDestination = "C:\Users\edward.muldrew\Documents\35759175\Test"
for ($i=0; $i -lt $files.Count; $i++) {
     $pathSource = "C:\Users\edward.muldrew\Documents\35759175\$($files[$i])"
     Move-Item $pathSource -Destination $pathDestination

posted this

Have an answer?

JD

Please login first before posting an answer.