Share via


powershell directory in foreach loop

Question

Monday, February 19, 2018 3:25 PM

I'm trying to copy files form one folder to another (using ls as  test to check the correct path and filename, but I'm getting error that $directoryPathEMP does not exist.  How can I correctly next these two variables to result in the desired path?

$directoryPathEMP = "C:\Users\newuserID\NewFolder"
foreach ($file in get-ChildItem C:\Users\oldUserID\oldFolder\) {

    ls '$directoryPathEMP'$file.name

  }

    

All replies (2)

Monday, February 19, 2018 3:38 PM | 1 vote

Please do not use aliasses in scripts. It's just harder to read and to understand.

With single quotes you stop evaluating variables. If you want to "construct" a path you can use Join-Path. But you will get an error for each file as long as they don't exist in the new folder.

$directoryPathEMP = "C:\Users\newuserID\NewFolder"
foreach ($file in get-ChildItem C:\Users\oldUserID\oldFolder\*) {
    $FilePath = Join-Path -Path $directoryPathEMP -ChildPath $file.Name
    Get-ChildItem -Path $FilePath
}

Best regards,

(79,108,97,102|%{[char]$_})-join''


Monday, February 19, 2018 6:07 PM

I would do it like this (note that this will match subdirectories too):

$directoryPathEMP = 'C:\Users\newUserID\NewFolder'foreach ($file in get-ChildItem C:\Users\oldUserID\OldFolder\*) {
  "$directoryPathEMP\$($file.name)"  ls "$directoryPathEMP\$($file.name)"
}