代码之家  ›  专栏  ›  技术社区  ›  John Wu

如何在Powershell命令行中输入搜索掩码?

  •  0
  • John Wu  · 技术社区  · 4 年前

    我正在用c#编写PowerShell驱动器提供程序,如下所示 these instructions .

    我被困在执行 GetChildItems ,这是PowerShell调用的方法,用于确定目录中包含哪些文件。例如,当用户键入 dir *.* .

    我希望能够通过以下方式过滤结果集 *.* 命令的一部分,但据我所知,它没有暴露在 GetChildItems 我在哪里可以买到?

    protected override void GetChildItems(string path, bool recurse)
    {
        var searchOption = recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
        var searchMask = //Where do I get this from?
    
        foreach (var itemPath in Directory.GetFiles(path, searchMask, searchOption))
        {
            var file = GetFile(itemPath); 
            WriteItemObject(file, itemPath, false);
        }
    }
    

    TLDR:在上面的代码中,我如何填充 searchMask 用命令行上输入的论点?

    更多信息

    这就是提供者类的声明方式。

    [CmdletProvider("Foo", ProviderCapabilities.Filter | ProviderCapabilities.Include)]
    public class FooDriveProvider : NavigationCmdletProvider, IContentCmdletProvider
    {
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Ruslan Gilmutdinov    4 年前

    为了能够进行筛选,您的提供者类必须:

    1. 包含属性 CmdletProviderAttribute 包含 ProviderCapabilities.Filter 在类声明中,即。 [CmdletProvider("Foo", ProviderCapabilities.Filter)] ;

    2. 衍生自 ContainerCmdletProvider (或 NavigationCmdletProvider )基层阶级;

    3. 实施方法 IsValidPath , ItemExists ,以及 GetChildItems .执行 项目存在 GetChildItems 方法需要确保传递给方法的路径满足过滤器要求。这些方法应该访问 CmdletProvider.Filter 属性并将其用于过滤。

    作为实现的示例,您可以查看 ZipFileProvider ,它提供了列出zip存档内容的能力。

    您可以使用以下命令使用此提供程序:

    // Import module compiled from the sources to the current session
    Import-Module ./PSZip.dll
    
    // Create new drive referring to .zip archive
    New-PSDrive -Name "ZIP" -PSProvider "ZipFile" -Root "D:\files\archive.zip"
    
    // List zip archive contents
    Get-ChildItem -Path ZIP: -Recurse
    
    // List only *.txt files
    Get-ChildItem -Path ZIP: -Recurse -Filter *.txt
    
    // ...or
    dir ZIP: -Recurse *.txt