anrpry anrpry - 1 month ago 5
HTTP Question

Check if password-protected web file exists

I need to check to see if a password-protected web file exists in a directory.

I keep getting a

(401) Unauthorized
error so, Lines 5-6 are not working.

Script Code:

$currdate = Get-Date -format "yyyyMMdd"
$Username = "username"
$Password = "password"
$url = "http://some.website/" + $currdate + "/somedirectory/some.file.txt"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)
$HTTP_Request = [System.Net.WebRequest]::Create($url)
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "File exists!"
}
Else {
Write-Host "File does not exist..."
}
$HTTP_Response.Close()


What am I doing wrong?

Answer

You use two objects WebClient and WebRequest, you need only one.

You set the credential to WebClient, but you do response by WebRequest without credential.

Modify your code as:

    $currdate = Get-Date -format "yyyyMMdd"
    $Username = "xxxxx"
    $Password = "xxxxxx"
    $url = "http://some.website/" + $currdate + "/somedirectory/some.file.txt"      

    # comment these lines,you use WebRequest
    #$WebClient = New-Object System.Net.WebClient
    #$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)

    $HTTP_Request = [System.Net.WebRequest]::Create($url)

    #add this line
    $HTTP_Request.Credentials = new-object system.net.networkcredential($Username, $Password)

    $HTTP_Response = $HTTP_Request.GetResponse()
    $HTTP_Status = [int]$HTTP_Response.StatusCode
    If ($HTTP_Status -eq 200) { 
        Write-Host "File exists!" 
    }
    Else {
        Write-Host "File does not exist..."
    }
    $HTTP_Response.Close()