【问题标题】:temp files in error with 7zip in powershellpowershell中的7zip错误的临时文件
【发布时间】: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


    【解决方案1】:

    不要使用&,而是使用Start-Process 并传递-wait 开关或使用-PassThru 开关和返回的System.Diagnostics.Process 来检查该过程是否已完成。两者都将获得与您的 Start-Sleep -Milliseconds 500 测试相同的结果,但它只会等待 7z.exe 完成其执行所花费的时间。


    附注 - 您可以一次附加多个文件。总体而言,这可能比单独添加每个文件更快。

    【讨论】:

    • 理论上你的答案正是我想要的。但我仍然有“文件存在”错误。
    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2017-07-22
    相关资源
    最近更新 更多