首页 > 解决方案 > Powershell - 将下载的文件保存在网络共享上

问题描述

PS1 需要从远程 HTTP 服务器下载 XML 文件并将其保存在网络共享中。脚本摘要如下

$timer = (Get-Date -Format yyyyMMdd_hhmmss)
$storageDir = "\\10.16.99.99\what\ever\Folder"
$filename1 = "John_" + "$timer.xml"
$webclient = New-Object System.Net.WebClient
$url1 = "http://whateverURL/John.xml"
$file1 = "$storageDir\$filename1"

$webclient.DownloadFile($url1,$file1)

$source = "\\10.16.99.99\what\ever\Folder"
$target = "\\10.16.99.99\what\ever\TargetFolder"
$files = get-childitem $source -Recurse
foreach ($file in $files){
    if ($file.LastWriteTime -ge (get-date).AddMinutes(-10)){
        $targetFile = $target + $file.FullName.SubString($source.Length)
        New-Item -ItemType File -Path $targetFile -Force
        Copy-Item $file.FullName -destination $targetFile
        Start-Sleep -s 3
    }
}

当我运行脚本时,我通过 PowerShell CMD 收到以下错误

Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient 
request."
At D:\StagisEE\GlobalListing\GL_download.ps1:318 char:3
+         $webclient.DownloadFile($url1,$file1)
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException

因此,我添加了以下几行以查看将在 webClient 命令中使用的变量

Write-Host $url1
Write-Host $file1

这给了我以下额外的结果

http://whateverURL/John.xml
\\10.16.99.99\what\ever\Folder\John_20191224_103412.xml

我的问题是为什么 webClient 失败而变量似乎没问题?还是因为网络位置而苦苦挣扎?

标签: powershell

解决方案


推荐阅读