尝试使用O365(和存储凭据)进行3次身份验证,然后退出

时间:2018-03-12 15:18:30

标签: powershell powershell-v3.0

我正在尝试使用以下函数存储/检索用户的O365凭据:

function Access-Credentials {    
    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSCredential])]

    param (
        [Parameter(Mandatory=$true)]
        [String]
        $App,

        [Switch]
        $Change
    )

    $App = Truncate-Filename -Filename $App
    $Filename = $PSScriptRoot + "\SecCred-" + $App + ".bin"

    # If we need to change the credentials, or if the current application's credentials don't exist, create
    If( $Change -or ((Test-PathEx -Path $Filename) -ne $True) ) {
        Try {
            Get-Credential | Export-CliXml -Path $Filename    
        }
        Catch [Exception] {
            Write-Log -err -text "Fatal error, unable to create credentials XML file: $Filename. Ran into error: $PSItem. Exiting..."
            exit
        }
    }

    return Import-CliXml -Path $Filename
}

在我的脚本中的以下行调用它:

$Cred = Access-Credentials -App "OWA Signatures"  #Credentials are now stored against a file called "SecCred-OWASignatures.bin" so don't need to be authenticated in future
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic –AllowRedirection -ErrorAction SilentlyContinue | Out-Null

基本上,如果凭证已经存在,请继续 - 否则,请求并存储它们。

这很好用。我现在想做的是......

  • a)测试凭据是否已成功验证
  • b)如果他们没有,请允许用户尝试重新输入他们的凭据三次
  • c)如果已存储凭据,请检查它们。如果他们不进行身份验证,会提示用户输入新凭据

我不确定从哪里开始。我尝试使用$attempts计数器进行while循环,但这似乎没有做任何事情 - 它只是重复请求凭据。

$attempts = 0
While ( (-not($Session)) -or ($attempts -eq 3) ) {
    Write-Log -warn -text "The credentials provided have not authenticated. Please try again..."
    $Cred = Access-Credentials -Change -App "OWA Signatures"  #Credentials are now stored against a file called "SecCred-OWASignatures.bin" so don't need to be authenticated in future
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic –AllowRedirection -ErrorAction SilentlyContinue | Out-Null

    #Increment the attempts counter
    $attempts++
}

If( ($attempts -eq 3) -and (-not($Session)) ) {
    Write-Log -err -text "Fatal error: unable to authenticate with O365 after three attempts. Please try different credentials."
    exit
}

有人能指出我正确的方向吗?

0 个答案:

没有答案