通过Windows身份验证,Invoke-Webrequest返回401



我正在使用脚本来登录SharePoint 2013网站,并导航到几页,以确保该站点在更新后和DR Drills后工作。我正在称呼这样的命令 -

$site = Invoke-WebRequest -uri 'https://spsite' -Credential $(Get-Credential) -SessionVariable s

当我拨打电话时,我会收到401个未经授权的错误。我尝试使用基本身份验证并这样构建标题:

$u = 'domainuser'
$p = 'password'
$header = @{ Authorization = "Basic {0}" -f [convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $u,$p))) }
$site = Invoke-WebRequest -uri 'https://spsite' -Headers $header

,结果相同。我希望有人可以提供另一种方式来建立这种联系?

,所以我找到了一种在我的情况下进行这项工作的方法,并希望发布基本知识,以防其他人遇到这一点。

我发现,当抛出异常时,您可以从这样的异常对象从Web服务器获得实际响应:

try{
    $site = Invoke-WebRequest -uri 'https://spsite' -Credential $(Get-Credential) -SessionVariable s
}
catch{
    $site = $_.Exception.Response
}

之后,我能够操纵$站点变量以跟随重定向并根据需要提交凭据。

使用wftools中的Export-PSCredentialImport-PSCredential - 您只需要每个盒子输入一次凭据,只要您的密码不更改:https://github,它就会持续下去.com/ramblingcookiemonster/powershell

Install-Module -Name WFTools -RequiredVersion 0.1.44
Import-Module WFTools;
$getCredentialMessage = "Please provide your Windows credentials";
$importedCredential = Import-PSCredential;
if ($importedCredential) {
    Write-Host -ForegroundColor Yellow "Imported your cached credential."
    while (-not $(Test-Credential -Credential $credential)) {
        Write-Host -ForegroundColor Yellow "Your cached credentials are not valid. Please re-enter."
        $credential = Get-Credential -Message $getCredentialMessage;
    }
    $credential = $importedCredential;
}
else {
    $credential = Get-Credential -Message $getCredentialMessage;
    while (-not $(Test-Credential -Credential $credential)) {
        $credential = Get-Credential -Message $getCredentialMessage;
    }
    Export-PSCredential $credential;
}
# Here is where the magic happens
$site = Invoke-WebRequest -uri 'https://spsite' -Credential $credential

最新更新