Powershell变量翻译

时间:2019-02-15 17:23:43

标签: string powershell variables

我具有以下PS功能:

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
}

问题是,当我使echo $ State时,我收到正确的值:

PS C:\Users\vasyl.v> echo "$State"
400 BadRequest. {"errors":["invalid username or password"]}

但是当我稍后尝试使用此变量时:

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
}

我收到:

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

任何人都可以暗示我,如何摆脱“ [System.Management.Automation.ErrorRecord]”并像回声中那样接收值?

1 个答案:

答案 0 :(得分:1)

您要查找的.contains()方法属于String类。您的$ state变量引用了 System.Management.Automation.ErrorRecord 对象。我为您提供了一些选择,您只需执行以下一项操作即可:

  1. 使用.contains()以外的其他逻辑。您可以切换为使用-contains-in运算符。正则表达式可用于需要查找起始字符串的逻辑。
  2. 在进行比较之前,将$ state更改为字符串。如果输出不是数组,则可以在函数中运行$global:State = -join $state。如果您的对象具有toString()方法,则可以通过运行$global:State = $state.toString()来完成此操作。