我需要检查目录中是否存在受密码保护的Web文件。
我不断收到(401) Unauthorized
错误,因此第5-6行无效。
脚本代码:
$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()
我做错了什么?
答案 0 :(得分:0)
您使用WebClient和WebRequest这两个对象,只需要一个。
您可以将凭据设置为WebClient,但您可以通过WebRequest进行响应,而无需凭据。
将您的代码修改为:
$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()