Reputation: 1603
I have a following PS function:
function Ask-Creds {
param(
[ValidateNotNull()]
$Creds = (Get-credential -message 'Please enter Technician`s login & password for Terminal registration:')
)
$vault="http://1.1.1.1:8200"
#Here I store error message in $State variable inside function:
$rawcontent=(New-VltAuth -va $vault -AuthMethod userpass -PathData $creds.Username -AuthData @{ password = $creds.GetNetworkCredential().Password } -KeepSecretWrapper -verbose -ErrorVariable State)
#here I make $State variable global, to access its value outside function
$global:State
}
Problem is that, when I make echo $State, I receive correct value:
PS C:\Users\vasyl.v> echo "$State"
400 BadRequest. {"errors":["invalid username or password"]}
But When I try to use this variable later:
if ( $state.contains("") ) {
echo "Technician is authenticated!"
} elseif ( $state.startswith("400 BadRequest") ) {
echo "Bad credentials!" | Ask-Creds
} elseif ( $state.startswith("An error occurred while") ) {
echo "Connection failed!" | exit 1
}
I receive:
Method invocation failed because [System.Management.Automation.ErrorRecord] does not contain a method named 'contains'.
At line:1 char:6
+ if ( $state.contains("") ) {
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Anyone can hint me, how to get rid of "[System.Management.Automation.ErrorRecord]" and receive value as in an echo?
Upvotes: 0
Views: 294
Reputation: 25001
The .contains()
method you are looking for belongs to class String. Your $state variable references a System.Management.Automation.ErrorRecord object. I see a few options for you, and you only need to do one of them:
.contains()
. You could switch to using the -contains
or -in
operator. Regex could be used for the logic where you need to find starting strings.$global:State = -join $state
in your function if the output is not an array. This could also be done if your object has a toString()
method by running $global:State = $state.toString()
.Upvotes: 1