PowerShell BitsTransfer基本身份验证语法

5

我是一名初学者,正在学习PowerShell脚本。我在阅读微软官方文档和寻找可用的示例方面遇到了困难。

我尝试使用BitsTransfer脚本自动下载ntis.gov的一个大型txt文件,而我使用的是.ps1脚本,因为显然SSIS不能在不编写.NET代码的情况下完成此操作。

访问此文本文件需要通过https:使用由NTIS发行的用户名和密码进行身份验证。我该如何在认证字符串中指定(硬编码)密码?我知道这是不好的做法。有更好的方法吗?

我的脚本如下:

    $date= Get-Date -format yyMMdd
    Import-Module BitsTransfer
    $Job = Start-BitsTransfer `
    -DisplayName DMFweeklytrans `
    -ProxyUsage AutoDetect `
    -Source https://dmf.ntis.gov/dmldata/weekly/WA$date `
    -Destination D:\Test.txt `
    -Authentication Basic `
    -Credential "myIssuedUsername" `
    -Asynchronous

While (($Job.JobState -eq "Transferring") -or ($Job.JobState -eq "Connecting")) {sleep 5}
Switch($Job.JobState)
    {
        "Transfer Completed" {Complete-BitsTransfer -BitsJobs $Jobs}
        default {$Job | Format-List} 
    }
1个回答

8

当您需要在非交互模式下提供凭据时,可以按照以下方式创建PSCredential对象。

$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$yourcreds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)

$Job = Start-BitsTransfer `
    -DisplayName DMFweeklytrans `
    -ProxyUsage AutoDetect `
    -Source https://dmf.ntis.gov/dmldata/weekly/WA$date `
    -Destination D:\Test.txt `
    -Authentication Basic `
    -Credential $yourcreds `
    -Asynchronous

谢谢。非常有帮助。我相信你的例子也会帮助其他人。 - Colin
有没有直接设置头信息的方法?例如,Azure Devops希望将令牌(PAT)设置为授权标头。它基本上是一个base-64编码的字符串,但不是<username>:<password>。 - Marc
@Marc,你尝试过像这样使用-CustomHeaders吗:$MyPat = 'yourPAT' $B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$MyPat"))"Authorization: Basic ${B64_PAT}" - JPBlanc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接