PowerShell条件执行

编程语言 2026-07-11

我写了这个(忽略 'LOCATION!!!' )

$zipInputFolder = LOCATION!!!
$zipOutputFolder = LOCATION!!!
$archivePath = LOCATION!!!
$zipFiles = Get-ChildItem $zipInputFolder -Filter *.zip
foreach ($zipFile in $zipFiles) {
$destinationPath = "$zipOutputFolder"
Expand-Archive -Path $zipFile.FullName -DestinationPath $destinationPath -Force
Write-Host "Extracted: $($zipFile.Name) to $destinationPath" -ForegroundColor Green
Move-Item -Path $zipFile.FullName -Destination $archivePath -Force
Write-Host "Moved: $($zipFile.Name) to $archivePath" -ForegroundColor Yellow
}

基本上,它会把一个位置中的所有ZIP文件解压到一个位置,然后把这些ZIP文件放到第三个位置。怎么改才能让移动步骤只有在解压步骤确实解压出内容时才执行?

解决方案

这在很大程度上取决于你使用的PowerShell版本,因为在PowerShell 7+中,-PassThru switch 已被加入该命令中,使任务变得相当简单:

$zipFiles = Get-ChildItem $zipInputFolder -Filter *.zip
foreach ($zipFile in $zipFiles) {
    $destinationPath = $zipOutputFolder
    $extracted = Expand-Archive -Path $zipFile.FullName -DestinationPath $destinationPath -Force -PassThru
    Write-Host "Extracted: $($zipFile.Name) to $destinationPath" -ForegroundColor Green
    # move only if `$extracted` is not null
    if ($extracted) {
        Move-Item -Path $zipFile.FullName -Destination $archivePath -Force
        Write-Host "Moved: $($zipFile.Name) to $archivePath" -ForegroundColor Yellow
    }
}

在PowerShell 5.1中,你需要寻找一个替代方案,例如,你可以把当前时间存入一个变量,先展开归档,然后在 $destinationPath 中查找在该存储时间之后新创建的项;如果有,则移动ZIP文件:

$zipFiles = Get-ChildItem $zipInputFolder -Filter *.zip
foreach ($zipFile in $zipFiles) {
    $destinationPath = $zipOutputFolder
    $now = [datetime]::Now
    Expand-Archive -Path $zipFile.FullName -DestinationPath $destinationPath -Force
    Write-Host "Extracted: $($zipFile.Name) to $destinationPath" -ForegroundColor Green
    # move only if there is at least 1 new item after `$now` in the `$destinationPath`
    if (Get-ChildItem $destinationPath | Where-Object CreationTime -GT $now) {
        Move-Item -Path $zipFile.FullName -Destination $archivePath -Force
        Write-Host "Moved: $($zipFile.Name) to $archivePath" -ForegroundColor Yellow
    }
}

另一种在5.1下的选项是在 $destinationPath 内构造一个新的路径,指示命令将归档解压到一个新的目录;为此,你可以使用ZIP存档 .BaseName(名称去掉扩展名);然后你可以检查该新文件夹中是否有任何新项:

$zipFiles = Get-ChildItem $zipInputFolder -Filter *.zip
foreach ($zipFile in $zipFiles) {
    # construct a path to extract to specific directory inside `$zipOutputFolder`
    $destinationPath = Join-Path $zipOutputFolder -ChildPath $zipFile.BaseName
    Expand-Archive -Path $zipFile.FullName -DestinationPath $destinationPath -Force
    Write-Host "Extracted: $($zipFile.Name) to $destinationPath" -ForegroundColor Green
    # check if any file or directory exists in the constructed path
    if (Get-ChildItem $destinationPath) {
        Move-Item -Path $zipFile.FullName -Destination $archivePath -Force
        Write-Host "Moved: $($zipFile.Name) to $archivePath" -ForegroundColor Yellow
    }
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章