Powershell Copy-Item caching

2019-08-11 06:15发布

问题:

I am having an issue with Powershell not copying the latest files across servers when using the below code.

$dir="\\MyServer\SQLBackups\SQL Backup*.bak"
$FileLocation = "E:\SQLRestore\SQL Backup Latest.bak"

If (Test-Path $FileLocation){
    Remove-Item $FileLocation
}

If (Test-Path $dir){
    $latest = Get-ChildItem -Path $dir | Sort-Object CreationTime -Descending | Select-Object -First 1
    Copy-Item -Path "$latest" -Destination $FileLocation
}

The code should locate the latest .bak file with the prefix "SQL Backup" and transfer this locally.

This process was working for over a month and with no changes to either servers or the process when suddenly the transfer time dropped from 5 mins to 3 seconds and the same file was being transferred.

Many Thanks

回答1:

Add some logging statements to your script to see what really happens. Like so,

$logfile = "c:\myLogFile.txt"
If (Test-Path $dir){
    $latest = Get-ChildItem -Path $dir | Sort-Object CreationTime -Descending | Select-Object -First 1
    add-content $logfile "Latest file: is $($latest.FullName)"
    Copy-Item -Path "$latest" -Destination $FileLocation
}