【发布时间】:2021-11-26 21:11:11
【问题描述】:
我目前正在努力使用一个简单的 powershell 脚本来存档文件。
我在一个文件夹中有数千个旧文件,我想根据它们在名为“YYYYMM”的档案中创建日期的月/年来归档它们。
我使用下面的代码
Get-ChildItem -Path $sourcePath -filter $filter |
Where-Object {(($_.CreationTime) -le $dateCriteria) -and ($_.psIsContainer -eq $false)}|
ForEach {
$archive = "{0:yyyy}{0:MM}.7z" -f $_.CreationTime
$archivePath= Join-Path -Path $destinationFolder -ChildPath $archive
& "C:\Program Files\7-Zip\7z.exe" a -mx9 -t7z -m0=lzma2 -sdel $archivePath$_.FullName |Out-Null
}
逻辑似乎很好,因为它创建了类似的文件 201809.7z 201810.7z ... 在我的目标文件夹中。
问题是我在控制台中看到错误:
System ERROR:
The file exists
或
System ERROR:
Access denied
或
System ERROR:
The file exists
ERROR: ********\202011.7z
Can not open the file as archive
因此,在我的目标文件夹中,除了预期的存档文件之外,我还有像“201810.7z.tmp1”这样的文件
我更改工作目录以通过添加 -w"{WORK_PATH}" 来隔离这些文件
到命令行。
我还加了Start-Sleep -Milliseconds 1
因为即使我的脚本是单线程的(可能 7zip 没有正确结束),它看起来也像是并发访问,但它不起作用。
Start-Sleep -Milliseconds 500它似乎可以工作,但出于显而易见的原因,我不想使用它。这样做的正确方法是什么?
编辑 1 按照 MisterSmith 的回答,我将代码更改为
Get-ChildItem -Path $emplacementSource -filter $filtreNomFichiers |
Where-Object {(($_.CreationTime) -le $dernierJour) -and ($_.psIsContainer -eq $false)}|
ForEach {
$archive = "{0:yyyy}{0:MM}.7z" -f $_.CreationTime
$cheminArchive= Join-Path -Path $dossierCible -ChildPath $archive
[Array]$arguments = "a" ,"-w$workDir", "-mx9" ,"-t7z" ,"-m0=lzma2" ,"-sdel" ,$cheminArchive, $_.FullName
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $sevenZip
$pinfo.RedirectStandardError = $true
$pinfo.CreateNoWindow= $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "$arguments"
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $pinfo
$process.Start()
$output = $process.StandardError.ReadToEnd()
$process.WaitForExit()
if(0 -ne $process.ExitCode){
Write-Output "$(Get-TimeStamp) Erreur: $output" | Out-file $fichierLogs -append
}
}
我的临时文件夹中仍有File exists 错误和.tmpX 档案。
【问题讨论】:
标签: powershell scripting 7zip