无法重命名目录powershell

时间:2016-06-28 19:15:22

标签: windows shell powershell command-line filesystems

我有一个powershell脚本,可以将文件夹复制到新目录,然后根据当前日期重命名该新目录。复制功能很好但是当它重命名目录时我收到以下错误信息:

Rename-Item : Access to the path '\\DPR320-W12-1600\PRTG\6212016 backup' is denied.

我认为这可能是由于在该行执行之前发生的复制,因为当该命令本身运行时我没有收到该错误消息。有没有办法可以在复制完成后立即重命名文件夹?任何帮助将不胜感激。我已完整地粘贴了以下脚本。

$targetdirectory = "\\DPR320-W12-1600\PRTG"
$sourcedirectory = "C:\Users\Public\Documents\PRTG Traffic Grapher"
$todaysdate=get-date
$minusoneweek=$todaysdate.adddays(-7)
$minusdate=($minusoneweek.Month).tostring(),($minusoneweek.day).tostring(),($minusoneweek.year).tostring()
$todaysdatestring=($todaysdate.Month).tostring(),($todaysdate.day).tostring(),($todaysdate.year).tostring()
$oldfilename=$minusdate[0]+$minusdate[1]+$minusdate[2]+" backup"
$newfilename=$todaysdatestring[0]+$todaysdatestring[1]+$todaysdatestring[2]+" backup"
$Threshold = (get-date).AddMonths(-18)
$culture = [Globalization.CultureInfo]::InvariantCulture
$count=0


Get-ChildItem $sourcedirectory\config | Where-Object { 
    $_.PsIsContainer -and 
    $_.BaseName -match '\d{6}' -and 
    ([DateTime]::ParseExact($_.BaseName, 'yyyyMMdd', $null) -gt (Get-Date).AddDays(-7)) 
} |Copy-Item -Recurse -Force -Destination $targetdirectory\$oldfilename\config

Copy-Item -Force $sourcedirectory\config.csv -Destination $targetdirectory\$oldfilename
Copy-Item -Force $sourcedirectory\config.prtg -Destination $targetdirectory\$oldfilename

rename-item $targetdirectory\$oldfilename $newfilename

$CleanupList = Get-ChildItem $targetdirectory\$newfilename\config

foreach ($DirName in $CleanupList)
{
try {
  If([datetime]::ParseExact($DirName.BaseName, 'yyyyMMdd', $culture) -lt $Threshold)

{
    write-host [datetime]::ParseExact($DirName.BaseName, 'yyyyMMdd', $culture)
  #Remove-Item $DirName.FullName -Force -Recurse

}

Write-Host $count
$count=$count+1

}


catch {

Write-Host $count
$count=$count+1

  continue
}

}

1 个答案:

答案 0 :(得分:1)

您可以放入一个while循环,尝试重命名该文件,直到成功为止:

while($true){
    try {
        rename-item $targetdirectory\$oldfilename $newfilename -ErrorAction Stop
        # It will only reach the break statement if rename-item was successful
        # The break statement will exit the while loop
        break
    }
    catch {
        write-host "couldn't rename file..."
        start-sleep -s 1
    }
}

如果在 n 尝试后它没有成功,您可能还想添加一个计数器并中断。否则,如果意外打开文件并保持文件打开或拒绝访问,例如阻止它的防病毒等,它可能会无限地重试文件。