Powershell下载给定日期的所有可能文件
问题描述:
我第一次使用Powershell从客户端的网页下载前一天的文件。网页来自数据记录器,而不是来自供应商的skid。数据记录器始终以yyMMdd##.CSV
格式保存文件,其中##
是该给定日(从00开始)的序列号文件。查看网页时,我只看到特定日期的CSV文件的最大数量为1(因此,8/31/17的文件将为17083100.CSV)。我已经写了Powershell代码给我昨天的文件,假设00是当天唯一的文件,但我希望有一种方法可以使用通配符或for循环来下载任何可能存在的额外文件前一天。请参阅下面的代码我目前有:Powershell下载给定日期的所有可能文件
$a = "http://10.109.120.101/logs/Log1/"
$b = (get-date).AddDays(-1).ToString("yyMMdd") + "00.CSV"
$c = "C:\"
$url = "$a$b"
$WebClient = New-Object net.webclient
$path = "$c$b"
$WebClient.DownloadFile($url, $path)
答
$a = "http://10.109.120.101/logs/Log1/"
$c = "C:\"
# From 0 to 99 loop.
# In this loop, `$_` contains 0,1,2,...
0..99 | ForEach-Object {
# `-f` is a format operator.
# For more information, see the following url:
# <https://social.technet.microsoft.com/wiki/contents/articles/7855.powershell-using-the-f-format-operator.aspx>
$b = "{0:yyMMdd}{1:d2}.CSV" -f (get-date).AddDays(-1), $_
$url = "$a$b"
# check exist by using HTTP HEAD method
$req = [System.Net.WebRequest]::Create($url)
$req.Method = 'HEAD'
$req.Timeout = 10000
try {
$res = $req.GetResponse()
} catch [System.Net.WebException] {
$res = $_.Exception.Response
}
if ($res.StatusCode -eq 'OK') {
# exist -> download
$WebClient = New-Object System.Net.WebClient
$path = "$c$b"
$WebClient.DownloadFile($url, $path)
# 1sec interval
Start-Sleep 1
} else {
# not exist -> exit loop
Write-Host $_
Write-Host $res.StatusCode
break
}
}
答
尝试这样:
$Date=(get-date).AddDays(-1).ToString("yyMMdd")
$URLFormat ='http://10.109.120.101/logs/Log1/{0}{1:D2}.CSV'
$WebClient = New-Object net.webclient
#build destination path
$PathDest="C:\Temp\$Date"
New-Item -Path $PathDest -ItemType Directory -ErrorAction SilentlyContinue
1..99 | %{
$Path="$PathDest\{0:D2}.CSV" -f $_
$URL=$URLFormat -f $Date, $_
try
{
Write-Host ("Try to download '{0}' file to '{1}'" -f $URL, $Path)
$WebClient.DownloadFile($Path, $URL)
}
catch
{
}
}
$WebClient.Dispose()