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

问题描述 投票:0回答:2

我很难理解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我有“测试”比较cert.pfx文件夹中的b:\lcerts\domain\wc\和当前时间之间的时间。如果证书在过去1天和1小时内已被修改,则脚本应继续:

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

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

我显然不明白PowerShell的命名法,因为我第一次运行这个脚本时,它运行正常。第二次在c:\certs\wc\$date\wc\cert.pfx中创建另一个文件夹。

如何让它失败并且"c:\certs\wc\$date\cert.pfx已经存在?“

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

powershell copy directory-structure
2个回答
0
投票

Copy-Item参数中指定目录时-Path的行为取决于-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

0
投票

您没有测试目标文件夹是否存在。看到您使用当前日期创建其名称,很可能此文件夹尚不存在,因此您需要先创建它。

此外,应该不需要使用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
}   
© www.soinside.com 2019 - 2024. All rights reserved.