如何从 PowerShell 检索递归目录和文件列表,不包括某些文件和文件夹? [英] How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

查看:45
本文介绍了如何从 PowerShell 检索递归目录和文件列表,不包括某些文件和文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 PowerShell 脚本,该脚本将递归搜索目录,但排除指定的文件(例如,*.logmyFile.txt),并且还排除指定的目录及其内容(例如,myDirmyDir 下的所有文件和文件夹).

我一直在使用 Get-ChildItem CmdLet,以及 Where-Object CmdLet,但我似乎无法得到这个确切的行为.

解决方案

Get-ChildItem cmdlet 有一个 -Exclude 参数,很容易使用,但它不能用于过滤掉整个目录据我所知.尝试这样的事情:

<前>函数 GetFiles($path = $pwd, [string[]]$exclude){foreach(Get-ChildItem $path 中的 $item){if ($exclude | Where {$item -like $_}) { continue }如果(测试路径 $item.FullName -PathType 容器){$itemGetFiles $item.FullName $exclude}别的{$item}}}

I want to write a PowerShell script that will recursively search a directory, but exclude specified files (for example, *.log, and myFile.txt), and also exclude specified directories, and their contents (for example, myDir and all files and folders below myDir).

I have been working with the Get-ChildItem CmdLet, and the Where-Object CmdLet, but I cannot seem to get this exact behavior.

解决方案

The Get-ChildItem cmdlet has an -Exclude parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:

function GetFiles($path = $pwd, [string[]]$exclude) 
{ 
    foreach ($item in Get-ChildItem $path)
    {
        if ($exclude | Where {$item -like $_}) { continue }

        if (Test-Path $item.FullName -PathType Container) 
        {
            $item 
            GetFiles $item.FullName $exclude
        } 
        else 
        { 
            $item 
        }
    } 
}

这篇关于如何从 PowerShell 检索递归目录和文件列表,不包括某些文件和文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆