使用 Get-ChildItem 排除文件夹 - 需要帮助调试脚本

问题描述 投票:0回答:0

我搜索了 StackOverflow 和 SuperUser 以试图解决这个问题,但我仍然被无法解决的问题所困扰。我知道这很简单,但玩了一个小时后我仍然很困惑。简单的问题:我怎么告诉 Get-Childitem 排除文件夹?

前面是不起作用的代码:

$sourceDir="E:\Deep Storage"
$targetDir="W:\Deep Storage"
$excludeThese = 'Projects2','Projects3','Projects4';

Get-ChildItem -Path $sourceDir -Directory -Recurse | 
  where {$_.fullname -notin $excludeThese} |
    Get-ChildItem -Path $sourceDir | ForEach-Object {
        $num=1
        $nextName = Join-Path -Path $targetDir -ChildPath $_.name
    
        while(Test-Path -Path $nextName)
        {
           $nextName = Join-Path $targetDir ($_.BaseName + "_$num" + $_.Extension)    
           $num+=1   
        }

        $_ | Move-Item -Destination $nextName -Force -Verbose -WhatIf
    }
}

这里的基本概念已经起作用:

$sourceDir="E:\Deep Storage"
$targetDir="W:\Deep Storage"

Get-ChildItem -Path $sourceDir -File -Recurse | ForEach-Object {
    $num=1
    $nextName = Join-Path -Path $targetDir -ChildPath $_.name

    while(Test-Path -Path $nextName)
    {
       $nextName = Join-Path $targetDir ($_.BaseName + "_$num" + $_.Extension)    
       $num+=1   
    }

    $_ | Copy-Item -Destination $nextName -Verbose
}

基本上它的作用是将文件夹从一个地方移动到另一个地方,如果两个地方都存在文件,它会重命名传入的文件。它有助于保持我的存档驱动器清晰。但是我想排除那里的三个文件夹,因为我仍然定期从它们中提取资产,所以我不需要移动这些文件。

因此两个代码示例之间的区别:在第一个代码示例中,我试图让 Get-Childitem 排除特定的三个文件夹,而第二个代码示例只是一次获取所有内容。

我尝试直接使用 $excludeThese 作为变量进行排除,但没有成功;我尝试完全跳过变量方法,只是将文件夹名称放在 -Exclude 之后。仍然没有用。我还尝试输入要排除的文件夹的完整路径。不好——无论我做什么,-WhatIf 显示脚本正在尝试移动所有内容,包括我理论上排除的文件夹。

我尝试的最后一个技巧是我在 SO 上遇到的一个技巧,那就是首先使用排除参数进行 gci,然后再执行另一个 gci。那还是失败了,所以现在我不得不求助于专家。

powershell
© www.soinside.com 2019 - 2024. All rights reserved.