I need to check to see if a password-protected web file exists in a directory.
我需要检查目录中是否存在受密码保护的Web文件。
I keep getting a (401) Unauthorized
error so, Lines 5-6 are not working.
我一直收到(401)未经授权的错误,因此,第5-6行无效。
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?
我究竟做错了什么?
1 个解决方案
#1
0
You use two objects WebClient and WebRequest, you need only one.
您使用两个对象WebClient和WebRequest,您只需要一个。
You set the credential to WebClient, but you do response by WebRequest without credential.
您将凭据设置为WebClient,但是您在没有凭据的情况下通过WebRequest进行响应。
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()
#1
0
You use two objects WebClient and WebRequest, you need only one.
您使用两个对象WebClient和WebRequest,您只需要一个。
You set the credential to WebClient, but you do response by WebRequest without credential.
您将凭据设置为WebClient,但是您在没有凭据的情况下通过WebRequest进行响应。
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()