Powershell 通过排除移动文件夹

标签 powershell except get-childitem file-move

我有很多文件夹,其中的内容我想移动到另一个文件夹 下面我想将 3 个文件夹移动到 ARKIV 文件夹 - 它可以工作,但脚本最后会崩溃。我是否以错误的方式使用排除标志?如果我使用 -Whatif 它似乎也想移动该文件夹 - 请参阅图片 2

我的代码如下:

$current_logfiles = "H:\FAKTURA\"
$destination = "H:\FAKTURA\ARKIV\"
$excludes = "H:\FAKTURA\ARKIV\"

if ((Test-Path -Path $destination)) 
{
    Get-ChildItem -Exclude $excludes  -Path H:\FAKTURA  | Move-Item  -Destination 
    H:\FAKTURA\ARKIV -Whatif
}

enter image description here

enter image description here

最佳答案

Am I using the Exclude flag the wrong way?

是的:

  • -Exclude (如 -Include )仅对项目(文件或目录)名称进行操作,而不是整个路径

  • -Excludes 仅排除匹配项本身。这意味着当使用 -Recurse 并且排除目录时,其内容(子树)不是

就您而言,由于您没有使用 -Recurse,因此仅针对输入目录的直接子项,解决方案是使用仅名称,即 $excludes = 'ARKIV' :

$excludes = 'ARKIV'
Get-ChildItem -Exclude $excludes -Path H:\FAKTURA  | 
  Move-Item  -Destination H:\FAKTURA\ARKIV -Whatif

注意:由于 Windows PowerShell 中的错误,您必须在上面的命令中使用 -Path,即使 -LiteralPath 在概念上是合适的并且通常更可靠。 p>

(代码可以简化:您可以将 $destination-Destination(Split-Path -Leaf $destination) 一起使用作为 $excludes 值。
要跳过 $destination 中已存在的项目,请在 Move-Item 之前插入以下管道段:
Where-Object { -not (Test-Path -LiteralPath (Join-Path $destination $_.Name)) })


-Exclude 目前
支持递归用例:

由上可知,当使用-Recurse时:

  • 您无法按子树路径排除项目。

  • 您不能排除项目及其子树

这些限制适用于 Windows PowerShellPowerShell (Core),至少适用于撰写本文时的最新版本 v7.3.x。
下一部分链接到将来可能提供此功能的功能请求。

解决方法,基于通过 Where-Object 进行后过滤:

在最简单的情况下,如果要排除的路径可以通过 wildcard 表达式匹配,则使用 -notlike ;例如:

Get-ChildItem -Recurse -File -Filter *.txt |
  Where-Object FullPath -notlike Arkiv/* |
  Where-Object FullPath -notlike */sub/dir/* |

这适用于排除感兴趣目录的内容,但不适用于这些目录本身(在本示例中这不是问题,因为使用了 -File仅枚举文件)。

虽然您可以添加另一个 -notlike 操作来省略 /* 以便也匹配目录本身(例如 -notlike */sub/dir ),但这种重复显然很麻烦。
另一种方法是使用 regexes-notmatch 代替:

Get-ChildItem -Recurse -Directory |
  Where-Object FullPath -notmatch '(^|\\)node_modules(\\|$)'
  • 这不包括名为 node_modules 的目录及其子树,无论它们位于输入目录子树中。

  • 请注意, \\ 与逐字匹配 \ ,即 Windows 路径分隔符;在类 Unix 平台上使用 / 或使用 [\\/] 来实现跨平台兼容性。

  • This answer 展示了基于逐字排除路径数组构建这些正则表达式的编程方式。


future 潜在的增强功能:

有两个相关的功能请求可能会在未来克服 -Exclude 的限制:

关于Powershell 通过排除移动文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77229318/

相关文章:

azure - 是否可以通过单用户登录提示使用 MFA 对 Connect-AzAccount 和 Connect-AzureAD 进行身份验证?

linux - Powershell 无法在 VSCode Linux 上找到类型 [Pester.OutputTypes]

即使有尝试,Python 循环也会重新启动 : except:

php - 抛出自定义异常而没有消息

java - getChildren() add() 和 add()

Python 2.7——让测试脚本模拟 raw_input

powershell - 在Where语句中使用变量

python - except 之后如何继续

android - Recyclerview,我无法使用 getChildAt(position) 获取项目 View 。空对象引用

powershell - get-childitem 在格式之前截断名称、全名