2010-07-17 62 views
10

使用PowerShell我可以用下面的命令目錄:如何編寫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-目錄功能刪除if陳述或者這是一個更好的辦法做它?

+1

考慮使用-Filter代替-Include,除非你需要包含多個項目。對於* .txt之類的內容,-Filter可以顯着加快。或者你可以隨時添加。 – 2010-07-17 16:51:24

回答

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可言。

+1

謝謝您的答案,並修復函數名稱和參數聲明。學到了比我更多的問題。 – 2010-07-17 05:36:49

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 
+0

感謝您提醒PowerShell社區擴展。我本可以用它作爲參考。由於這是構建過程的一部分,我會堅持我所得到的,因爲我不想添加其他依賴項。 – 2010-07-18 01:39:33

4

在PowerShell中3.0,它是烘烤與-File-Directory開關:

dir -Directory #List only directories 
dir -File #List only files 
+0

Get-ChildItem -Directory – chris31389 2016-10-21 10:00:07