我正在使用一个脚本,该脚本应该首先检查 PC 是否处于活动状态,然后将文件 FTP 传输到服务器。但是,在运行脚本时,我收到以下错误:
使用“2”个参数调用“UploadFile”时发生异常:“对于此请求,无法将 Content-Type 标头设置为多部分类型。”
脚本如下:
$down = "C:\Script\log\down-hosts.log"
$computers = Get-Content "C:\Script\list\Computers.txt"
$sourcefileName = "source_file.csv"
#ftp server
$ftp = "sftp://servername"
$user = "user"
$pass = "pass"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
# Create empty log file for down hosts (overwrite if exists)
New-Item $down -type file -force
foreach ($computer in $computers) {
if ( Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue ) {
Write-Host "$computer is up"
Write-Host "Uploading \\$computer\c$\UPS CSV Exports\$sourcefile..."
$sourcefilePath = "\\$computer\c$\UPS CSV Exports"
$uri = New-Object System.Uri($ftp+$computer+"_"+$sourcefileName)
$webclient.UploadFile($uri,$sourcefilePath+"/"+$sourcefileName)
if($? -eq $True) {
write-host "$ftp$sourcefileName ok"
Remove-Item $sourcefilePath"\"$sourcefileName
}
} else {
Write-Host "$computer is down"
"$computer is down" | Out-File $down -append
}
}
这个想法是,脚本找到文件,然后上传到 FTP 服务器。如果 PC 不可用,它会写入日志文件,这样我就知道要手动检索文件。
谢谢!
答案1
我稍微重写了脚本,让它在不使用 FTP 协议的情况下运行。我将其改为使用 move 命令:
$down = "C:\Script\log\down-hosts.log"
$computers = Get-Content "C:\Script\list\Computers.txt"
$TargetPath = "\\ServerName\ShareName\Path"
$SourceFileName = "source_file.csv"
foreach ($computer in $computers) {
if ( Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
{
$sourcefilePath = "\\$computer\c$\UPS CSV Exports\$SourceFileName"
Write-Host "$computer is up"
Write-Host "Copying $SourceFilePath ..."
Try {
If (Test-Path $SourceFilePath) {
Move-Item $SourceFilePath "$TargetPath\$computer`_$SourceFileName" -force
} Else {
Throw "$SourceFilePath does not exist"
}
} Catch {
Write-Host "Error: $($Error[0].Exception.Message)"
}
} Else {
Write-Host "$computer is down"
"$computer is down" | Out-File $down -append
}
}
经过修改后,脚本运行完美!
答案2
您收到一个误导性错误,因为它可能正在尝试在您指定的 sftp 后端执行 POST 请求。
UploadFile 方法将本地文件发送到资源。此方法使用 STOR 命令上传 FTP 资源。对于 HTTP 资源,使用 POST 方法。
参考:http://msdn.microsoft.com/en-us/library/36s52zhs(v=vs.110).aspx