我正在尝试使用以下函数存储/检索用户的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
基本上,如果凭证已经存在,请继续 - 否则,请求并存储它们。
这很好用。我现在想做的是......
我不确定从哪里开始。我尝试使用$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
}
有人能指出我正确的方向吗?