invoke-webrequest使用Windows身份验证返回401

时间:2017-02-24 16:54:15

标签: powershell

我正在编写一个脚本来登录sharepoint 2013网站并导航到几个页面以确保该网站在更新和DR演练后正在运行。我这样调用Invoke-WebRequest:

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

当我拨打电话时,我收到了401 Unauthorized错误。我尝试过使用基本身份验证并构建如下标题:

$u = 'domain\user'
$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

具有相同的结果。我希望有人能提供另一种方式来建立这种联系吗?

2 个答案:

答案 0 :(得分:5)

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

我发现当抛出异常时,您可以从异常对象中获取Web服务器的实际响应,如下所示:

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

之后,我能够操作$ site变量以遵循重定向并根据需要提交凭据。

答案 1 :(得分:-1)

使用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
相关问题