Copy-Item 正在复制意外的文件夹

Copy-Item is copying unexpected folder

我很难理解 PowerShell 如何处理递归和 Copy-Item 命令。

$date=Get-Date -Format yyyyMMdd
$oldfolder="c:\certs\old$date"
New-PSDrive -Name "B" -PSProvider FileSystem -Root "\(server)\adconfig"
$lastwrite = (get-item b:\lcerts\domain\wc\cert.pfx).LastWriteTime
$timespan = new-timespan -days 1 -hours 1

Write-Host "testing variables..."
Write-Host " date = $date" `n "folder path to create = $oldfolder" `n 
"timespan = $timespan"

if (((get-date) - $lastwrite) -gt $timespan) {
#older
Write-Host "nothing to update."
}
else {
#newer
Write-Host "newer certs available, moving certs to $oldfolder"
copy-item -path "c:\certs\wc" -recurse -destination $oldfolder 
copy-item b:\lcerts\domain\wc\ c:\certs\ -recurse -force
}

现有文件存在于 c:\certs\wc\cert.pfx 我有 "test" 比较 b:\lcerts\domain\wc\ 文件夹中的 cert.pfx 和当前时间之间的时间。如果证书在过去 1 天 1 小时内被修改,那么脚本应该继续:

c:\certs\wc\ to c:\certs\old$date\cert.pfx

复制cert.pfx

b:\lcerts\domain\wc to c:\certs\wc\cert.pfx

复制cert.pfx

我显然不理解 PowerShell 的术语,因为我第一次 运行 这个脚本时,它工作正常。第二次它在 c:\certs\wc$date\wc\cert.pfx 中创建了另一个文件夹。

如何让它在 "c:\certs\wc$date\cert.pfx 已经存在的情况下失败?

我不想通过指定实际文件名将其限制为仅 cert.pfx 文件,我想要文件夹中的所有文件,因为最终会有多个文件。

-Path 参数中指定目录时 Copy-Item 的行为取决于 -Destination 参数中指定的目录是否存在。

Copy-Item -Path "c:\certs\wc" -Recurse -Destination "c:\certs\old$date"

如果c:\certs\old$date目录不存在,则复制wc目录并命名为c:\certs\old$date.

如果c:\certs\old$date目录存在,则wc目录复制到c:\certs\old$date目录下。因此,它变成了 c:\certs\old$date\wc.

所以你一定要提前检查一下目录是否存在

if(Test-Path $oldfolder) { throw "'$oldfolder' is already exists." }
Copy-Item -Path "c:\certs\wc" -Destination $oldfolder -Recurse

您没有测试目标文件夹是否存在。看到您正在使用当前日期创建它的名称,很可能这个文件夹还不存在,所以您需要先创建它。

此外,应该不需要使用 New-PSDrive cmdlet,因为 Copy-Item 完全可以使用 UNC 路径。

也许是这样的:

$server      = '<NAME OF THE SERVER>'
$serverPath  = "\$server\adconfig\lcerts\domain\wc"
$testFile    = Join-Path -Path $serverPath -ChildPath 'cert.pfx'
$localPath   = 'c:\certs\wc'
$date        = Get-Date -Format yyyyMMdd
$timespan    = New-TimeSpan -Hours 1 -Minutes 1
$oldfolder   = "c:\certs\old$date"

# check if this output path exists. If not, create it
if (!(Test-Path -Path $oldfolder -PathType Container)) {
    Write-Host "Creating folder '$oldfolder'"
    New-Item -ItemType Directory -Path $oldfolder | Out-Null
}

Write-Host "testing variables..."
Write-Host "date = $date`r`nfolder path to create = $oldfolder`r`ntimespan = $timespan"

# test the LastWriteTime property from the cert.pfx file on the server
$lastwrite = (Get-Item $testFile).LastWriteTime
if (((Get-Date) - $lastwrite) -gt $timespan) {
    #older
    Write-Host "Nothing to update."
}
else {
    #newer
    Write-Host "Newer cert(s) available; copying all from '$localPath' to '$oldfolder'"
    Copy-Item -Path $localPath -Filter '*.pfx' -Destination $oldfolder
    Copy-Item -Path $serverPath -Filter '*.pfx' -Destination $localPath -Force
}