PowerShell的Get-ChildItem -recurse命令无法获取所有项

8
我是一名有帮助的助手,以下是您需要翻译的内容:

我正在编写一个PowerShell脚本,用于删除文件夹中的某些文件,并将其余文件移动到预定义的子文件夹中。

我的目录结构如下:

Main
    (Contains a bunch of pdb and dll files)
    -- _publish
        --Website
            (Contains a web.config, two other .config files and a global.asax file)
            -- bin
                (Contains a pdb and dll file)
            -- JS
            -- Pages
            -- Resources

在开始移动文件之前,我希望从整个文件结构中删除所有的pdb、config和asax文件。我使用以下命令:

$pdbfiles = Get-ChildItem "$executingScriptDirectory\*.pdb" -recurse

foreach ($file in $pdbfiles) {
    Remove-Item $file
}

我需要删除所有文件类型,除了网站bin文件夹中的pdb文件和网站文件夹中的ASAX文件。现在使用Get-ChildItem进行递归搜索,但是它忽略了这些文件。是否由于递归结构中的项目深度导致的?或者是其他原因?如何修复它,以便根据规定删除所有文件。
编辑:我尝试添加-force参数,但没有改变任何内容。
答案:以下内容可以解决问题。
$include = @("*.asax","*.pdb","*.config")
$removefiles = Get-ChildItem "$executingScriptDirectory\*" -recurse -force -include $include 

foreach ($file in $removefiles) {
    if ($file.Name -ne "Web.config") {
        Remove-Item $file
    }
}

你试过用 Get-ChildItem -force 吗? - CB.
2
我知道我来晚了。上面的脚本适用于PowerShell v3及以上版本。当我发现生产服务器只有PowerShell v2时,我遇到了这个问题。您可以通过转储$PSVersionTable变量来检查。 - JamesQMurphy
2个回答

21
Get-ChildItem -path <yourpath> -recurse -Include *.pdb

是的,我刚刚发现了,因为我更新了它并阅读了它。非常感谢你。 - Daniel Olsen
1
在包含部分中,您可以使用逗号将多个扩展名分隔开来进行指定:gci -path <yourpath> -recurse -Include *.pdb, *.asax - David Brabant
非常感谢您的帮助 - 已经更新了我的解决方案。 - Daniel Olsen
2
@Xenoxsis 注意 - 如果只需要一个过滤器,请使用“-filter”而不是“-include”,因为它更快。对于大型目录结构,您将真正注意到差异。 - Andy Arismendi

2

您还可以使用管道进行删除:

Get-ChildItem -path <yourpath> -recurse -Include *.pdb | rm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接