如何修改PowerShell脚本以排除指定文件夹移动文件
修复PowerShell脚本:排除指定文件夹的文件移动
你原来的脚本用来按指定过滤器移动数据库文件,现在想排除\\Server1\Databases\AMG里的文件,但修改后的代码没生效对吧?问题出在你用了一个不存在的属性$_.source——Get-ChildItem返回的文件对象根本没有这个属性,所以那个过滤条件等于没起作用,自然还是会移动所有匹配过滤器的文件。
给你两种可行的修改方案,都能实现排除目标文件夹的需求:
方案一:通过文件目录路径过滤
这个方案检查文件所在的目录是否包含要排除的文件夹路径,逻辑更直观:
$filters = Get-Content "c:\customerName.txt" $source = "\\Server1\Databases" $destination = "\\Server2\Databases" # 定义要排除的文件夹路径 $excludeFolder = "\\Server1\Databases\AMG" foreach($filter in $filters) { Get-ChildItem $source -Include *.* -Recurse | # 先排除AMG文件夹下的文件,同时确保是文件不是文件夹 Where-Object { !$_.PsIsContainer -and $_.DirectoryName -notlike "$excludeFolder*" } | # 再按过滤器匹配文件 Where-Object { $_.FullName -match $filter } | ForEach-Object { # 用Join-Path拼接目标路径,避免字符串拼接的路径问题 $targetPath = Join-Path -Path $destination -ChildPath $filter # 提前创建目标文件夹,防止移动时因为文件夹不存在报错 if (-not (Test-Path -Path $targetPath)) { New-Item -ItemType Directory -Path $targetPath | Out-Null } Move-Item $_.FullName -Destination $targetPath } }
方案二:通过完整文件路径判断
这个方案直接检查文件的完整路径是否以排除文件夹的路径开头,匹配更精准(注意给排除路径加个结尾的斜杠,避免误匹配类似AMGTest这种名字相近的文件夹):
$filters = Get-Content "c:\customerName.txt" $source = "\\Server1\Databases" $destination = "\\Server2\Databases" # 结尾加斜杠,避免匹配名称包含AMG的其他文件夹 $excludeFolder = "\\Server1\Databases\AMG\" foreach($filter in $filters) { Get-ChildItem $source -Include *.* -Recurse | Where-Object { !$_.PsIsContainer -and -not $_.FullName.StartsWith($excludeFolder) } | Where-Object { $_.FullName -match $filter } | ForEach-Object { $targetPath = Join-Path $destination $filter if (-not (Test-Path $targetPath)) { New-Item -ItemType Directory -Path $targetPath | Out-Null } Move-Item $_.FullName -Destination $targetPath } }
额外提两个小优化点:
- 用
Join-Path拼接路径比直接写$destination"\$filter"更可靠,能自动处理路径末尾的斜杠问题 - 提前创建目标文件夹,避免因为目标路径不存在导致移动操作失败
内容的提问来源于stack exchange,提问作者Immortal
相关产品推荐
相关产品推荐

