You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell仅移动同时包含.zip和.txt文件的文件夹?

修改PowerShell代码实现目标需求

原代码仅筛选了包含.txt文件的文件夹,未校验是否同时存在.zip文件,会误移动只含单一类型文件的文件夹。以下是两种可行的修改方案:

方案一:通过文件计数判断

# 筛选出同时包含.txt和.zip文件的子文件夹
$targetFolders = Get-ChildItem -Path N:\Download -Directory | Where-Object {
    # 检查当前文件夹下至少有1个.txt文件
    (Get-ChildItem -Path $_.FullName -File -Filter *.txt).Count -gt 0 -and
    # 同时至少有1个.zip文件
    (Get-ChildItem -Path $_.FullName -File -Filter *.zip).Count -gt 0
}

# 移动符合条件的文件夹(-WhatIf为预览模式,确认无误后可删除)
if ($targetFolders) {
    Move-Item -LiteralPath $targetFolders.FullName -Destination N:\Zip -Force -WhatIf
}

方案二:用Test-Path高效判断(推荐)

Test-Path找到第一个匹配文件后就会返回结果,比遍历所有文件计数更高效:

$targetFolders = Get-ChildItem -Path N:\Download -Directory | Where-Object {
    # 验证当前文件夹存在.txt文件
    Test-Path -Path (Join-Path $_.FullName "*.txt") -PathType Leaf -and
    # 同时存在.zip文件
    Test-Path -Path (Join-Path $_.FullName "*.zip") -PathType Leaf
}

Move-Item -LiteralPath $targetFolders.FullName -Destination N:\Zip -Force -WhatIf

关键说明

  • -WhatIf参数:仅预览移动操作,不会实际修改文件系统,确认逻辑正确后可删除该参数执行真实移动。
  • -Force参数:允许覆盖目标目录中已存在的同名文件夹,不需要此功能可直接删除该参数。

内容的提问来源于stack exchange,提问作者Shahpari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:50:46