arrayspowershellfor-loopforeachpscp

PSCP cant retrieve from an array of ip in FOR loop but works in FOREACH?


I have a powershell script so basically I need to transfer files from multiple source to one local. I don't want to use pslurp in this case.

Basically, i get more than one remote source...error if i run my array in for loop, however it works in for each why?

Now the problem is I can't change my destination path as I have no idea where to let my Destination Array run in foreach loop. If I specify one source ip, it can loop to send to diff destination. So my array and loop technically is working fine.

Overall code (not working, got more thqn one remote source not supported error)

$ArrayIP=@("root@10.0.0.1","root@10.0.0.2")
$ArrayDestination=@("C:/Users/me/save01","C:/Users/me/save01"}

for (i=0; i -le2; i++){
pscp -pw testing -r $ArrayIP[i]":"/cf/conf/backup/* $ArrayDestination[i]
}

So I changed to FOREACH... but now I dont know how to let it save to different destination? Either way I specified one single destination for the sake of testing and it works. I am not getting the more than one remote source error anymore.

foreach ($IP in $ArrayIP){
pscp -pw testing -r $IP":"/cf/conf/backup/* <insert destination? dk how to make it run an arrayDestination>
}

Now I am thinking if i should do a 2D array...will that help me to run different variables in foreach loop? Or if anyone can guide me using the object command...I have read through forums about it but still not sure on how to use it


Solution

  • There are two things preventing your first sample from working:

    First up, your current for loop isn't valid - variable names in PowerShell are prefixed with $:

    for ($i=0; $i -le 2; $i++){
       ...
    }
    

    Second, PowerShell treats command line arguments as expandable strings, and an array index operation won't expand correctly in a string - enclose in a subexpression $() to correctly expand the referenced array index:

    for ($i=0; $i -le 2; $i++){
        pscp -pw testing -r "$($ArrayIP[$i]):/cf/conf/backup/*" "$($ArrayDestination[$i])"
    }