5

I'm new to PowerShell scripting. I'm struggling with the MS documentation and finding few examples to work with.

I'm trying to automate the weekly download of a large txt file from ntis.gov with a BitsTransfer script. I'm using .ps1 script because apparently SSIS can't do this without writing .NET code.

Access to this text file is via https: with an NTIS issued username and password. How can I specify (hard code) the password into the authentication string? I know this is bad practice. Is there a better way to do this?

My script looks like this-

    $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} 
    }
Colin
  • 930
  • 3
  • 19
  • 42

1 Answers1

8

When you have to provide credentials in non-interactive mode, you can create a PSCredential object in the following way.

$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
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • Thank you. Very helpful. I'm sure your example will help others too. – Colin Mar 28 '13 at 14:22
  • Is there any way to directly set headers? For example Azure Devops wants a token (PAT) set as the Authorization header. It's basically a base-64 encoded string but not :. – Marc May 12 '21 at 05:45
  • @Marc have you tried `-CustomHeaders` with something like : `$MyPat = 'yourPAT' $B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$MyPat"))` and `"Authorization: Basic ${B64_PAT}"` – JPBlanc May 12 '21 at 06:39