10

PowerShellを使用すると、次のコマンドでディレクトリを取得できます。

Get-ChildItem -Path $path -Include "obj" -Recurse | `
    Where-Object { $_.PSIsContainer }

コマンドが読みやすくなるように関数を作成したいと思います。例えば:

Get-Directories -Path "Projects" -Include "obj" -Recurse

-Recurseそして、次の関数は、エレガントな処理を除いて、まさにそれを実行します。

Function Get-Directories([string] $path, [string] $include, [boolean] $recurse)
{
    if ($recurse)
    {
        Get-ChildItem -Path $path -Include $include -Recurse | `
            Where-Object { $_.PSIsContainer }
    }
    else
    {
        Get-ChildItem -Path $path -Include $include | `
            Where-Object { $_.PSIsContainer }
    }
}

Get-Directories関数からステートメントを削除するにはどうすればifよいですか、それともこれがより良い方法ですか?

4

3 に答える 3

13

これを試して:

# nouns should be singular unless results are guaranteed to be plural.
# arguments have been changed to match cmdlet parameter types
Function Get-Directory([string[]]$path, [string[]]$include, [switch]$recurse) 
{ 
    Get-ChildItem -Path $path -Include $include -Recurse:$recurse | `
         Where-Object { $_.PSIsContainer } 
} 

これは、-Recurse:$ falseが同じであり、-Recurseがまったくないために機能します。

于 2010-07-17T05:26:17.067 に答える
4

PowerShell 3.0では、-File -Directoryスイッチが組み込まれています。

dir -Directory #List only directories
dir -File #List only files
于 2013-01-24T21:18:00.913 に答える
2

Oisinが与える答えは的確です。私は、これがプロキシ機能になりたいと思っていることに近いことを付け加えたかっただけです。PowerShell Community Extensions 2.0がインストールされている場合は、すでにこのプロキシ機能があります。有効にする必要があります(デフォルトでは無効になっています)。Pscx.UserPreferences.ps1ファイルを編集し、次のように$trueに設定されるようにこの行を変更するだけです。

GetChildItem = $true # Adds ContainerOnly and LeafOnly parameters 
                     # but doesn't handle dynamic params yet.

動的パラメータに関する制限に注意してください。PSCXをインポートするときは、次のようにします。

Import-Module Pscx -Arg [path to Pscx.UserPreferences.ps1]

今、あなたはこれを行うことができます:

Get-ChildItem . -r Bin -ContainerOnly
于 2010-07-17T16:57:18.793 に答える