How to catch “Access denied” using plink from powershell script

I have a powershell script that calls the following command:

plink -batch -ssh $defUser@$srv -pw $defPassword -m $executeCommandFile

The problem that $defPassword is not always the same/correct. How can I catch Access denied error from plink?

Something like this:

if (plink -batch -ssh $defUser@$srv -pw $defPassword -ne "Access denied") \\execute -m $executeCommandFile
else \\use different $defPassword(for example $defPassword2) and then execute

Think it's like try\catch but with plink used password

1 Answer

"Access is denied" message appears in error stream. You can use the Windows PowerShell redirection operators e.g as follows:

$aux = . plink -batch -ssh $defUser@$srv -pw $defPassword -m $executeCommandFile *>&1
if ( $aux -match '^Access.*denied' ) { ### the specified string found: use different $defPassword
} else { ### success $aux ### show plink results
}

Note that 2>&1 could suffice:

  • *>&1 sends all output types (*) to the success output stream;
  • 2>&1 sends errors (2) and success output (1) to the success output stream.
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like