Posh-SSH icon indicating copy to clipboard operation
Posh-SSH copied to clipboard

problem with for loop in posh-ssh

Open mehranr81 opened this issue 1 year ago • 4 comments

Dear my friend I wrote a short code to connect multiple servers using posh-ssh new-sshsession to download from a folder, but this cmdlet doesn't identify changing IP addresses, could you obviate the problem? $User = "toor" $PWord = ConvertTo-SecureString -String "oZPS" -AsPlainText -Force $Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord foreach($switchip in Get-Content d:\ips.txt) { New-SSHSession -ComputerName $switchip -Credential $Credential -AcceptKey -force -Verbose -ConnectionTimeout 2 Get-scpitem -ComputerName $switchip -Path "/ram" -PathType Directory -Destination "d:\temp2" -Credential $Credential -AcceptKey -Verbose -force -ConnectionTimeout 25 Remove-SSHSession -Index 0 }

$switchip is not changed using loop inside New-SSHSession. I will be grateful. image

image

mehranr81 avatar May 16 '23 14:05 mehranr81

  1. You do not need SSHSession with SCP
  2. Try to $switchip = '10.48.192.68'; Get-scpitem -ComputerName $switchip -Path ..... manually
  3. if previous step was succesful, Write-Host $switchip before Get-SCPItem, there might be something wrong with it.

MVKozlov avatar May 17 '23 08:05 MVKozlov

Thanks for your response , if I defined like this $switchip = '10.48.192.68' , In this case there's no loop, it was working fine but whenever I had to read bunch of ip addresses through foreach, it could not handle it. Finally I defined an array of IPs and solved the case. image

mehranr81 avatar May 17 '23 19:05 mehranr81

This looks more like a PowerShell programming issue than a module issue.

  1. You don't need the New-sshsession since you are not using it.
  2. your $ipaddresses ... just create a an empty array and add to it what matches the regex, my take the txt does not contain only IPs if you are doing the regex and saving it into a different array.
  3. I would use test-connection cmdlet and check the port and Ip are reachable before attempting a connection.
  4. instead of write-host use -verbose on get-scpitem, you will get more information.

My take is that you are not getting a IP address as the value of ComputerName and that is why you get the error, or the host is not reachable and you get the error message. Also if you download the same folder to the same destination from all the hosts will you not be overwriting the information?

darkoperator avatar May 17 '23 21:05 darkoperator

Thanks Darkoperator

mehranr81 avatar May 20 '23 10:05 mehranr81