![](/img/trans.png)
[英]Copy Recently Modified Files with Folder Structure Using PowerShell
[英]Download file from URL if not modified recently using Powershell
我有一個 Powershell 腳本,它正在從 URL 公共目錄連續下載文件。 該腳本應該從我們本地目錄中當前不存在的目錄下載文件。 該腳本如下所示:
$outputdir = 'C:\mydir\public\demos'
$url = 'https://xxx.xxx.net/fastdl/xxx/xxx/public/'
# enable TLS 1.2 and TLS 1.1 protocols
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls11
$WebResponse = Invoke-WebRequest -Uri $url
# get the list of links, skip the first one ("../") and download the files
$WebResponse.Links | Select-Object -ExpandProperty href -Skip 0 | ForEach-Object {
Write-Host "Downloading file '$_'"
$filePath = Join-Path -Path $outputdir -ChildPath $_
$fileUrl = '{0}/{1}' -f $url.TrimEnd('/'), $_
if (Test-Path($filePath))
{
Write-Host 'Skipping file, already downloaded' -ForegroundColor Yellow
return
}
Invoke-WebRequest -Uri $fileUrl -OutFile $filePath
}
現在,因為我想從$url目錄下載所有文件,所以我需要再檢查一個條件。 $url中的文件在最后 10 分鍾內不能修改,如果有,則腳本應跳過該文件並在最后修改時間大於 10 分鍾后下載它。
我還沒有找到任何似乎能夠適合這樣的 if 語句的語法。 有任何想法嗎?
我會將Test-Path
更改為Get-Item
,這樣如果它返回某些內容,則該文件存在並且您可以檢查其 LastWriteTime 屬性:
$WebResponse.Links | Select-Object -ExpandProperty href -Skip 0 | ForEach-Object {
$filePath = Join-Path -Path $outputdir -ChildPath $_
$fileUrl = '{0}/{1}' -f $url.TrimEnd('/'), $_
# set up a boolean fag to download or not
$downloadThis = $true
if ($file = Get-Item -Path $filePath -ErrorAction SilentlyContinue) {
# $file exists, check the LastWriteTime property
if ($file.LastWriteTime -ge (Get-Date).AddMinutes(-10)) {
Write-Host 'Skipping file, already downloaded' -ForegroundColor Yellow
$downloadThis = $false
}
}
if ($downloadThis) {
Write-Host "Downloading file '$($file.Name)'"
Invoke-WebRequest -Uri $fileUrl -OutFile $filePath
}
}
我想你所需要的只是計算從現在到文件的最后修改時間的時間。 我曾經寫過一個 function 來檢查創建時間少於 10 分鍾或超過 10 分鍾的文件並采取相應措施,希望它能有所幫助
#function to check whether a file is more than 10 mins age, if yes, return TRUE. If not, return FALSE
function file_age ($file){
#$file_info = Get-Item $file
$createtime = $file.CreationTime
$now = get-date
if (($now - $createtime).totalminutes -ge 10) {
Write-host "file [$file] created equal or more than 10 mins ago"
return $true
}
else
{#Write-host "file [$file] created within the 10 mins"
return $false
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.