2016-03-05 48 views
1

使用PowerShell我想檢查一個目錄(全名在$PathOutput),如果它包含其他目錄。如果此路徑不包含其他目錄,我希望變量$FailedTests具有字符串'none',否則變量$FailedTests應該包含每個找到的目錄(非遞歸),可以是不同的行,也可以是逗號分隔的或任何其他目錄。如何獲取目錄列表或'無'?

我曾嘗試下面的代碼:

$DirectoryInfo = Get-ChildItem $PathOutput | Measure-Object 
if ($directoryInfo.Count -eq 0) 
{ 
    $FailedTests = "none" 
} else { 
    $FailedTests = Get-ChildItem $PathOutput -Name -Attributes D | Measure-Object 
} 

,但它會生成以下錯誤:

Get-ChildItem : A parameter cannot be found that matches parameter name 'attributes'. 
At D:\Testing\Data\Powershell\LoadRunner\LRmain.ps1:52 char:62 
+ $FailedTests = Get-ChildItem $PathOutput -Name -Attributes <<<< D | Measure-Object 
    + CategoryInfo   : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException 
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

我使用PowerShell 2.0的Windows Server 2008上

我寧願該解決方案使用Get-ChildItem或僅使用一次。

回答

1

錯誤實際上是相當不言自明的:Get-ChildItem(使用PowerShell V2)沒有一個參數-Attributes。該參數(以及參數-Directory)隨PowerShell v3一起添加。在PowerShell v2中,您需要使用Where-Object過濾器來移除不需要的結果,例如像這樣:

$DirectoryInfo = Get-ChildItem $PathOutput | Where-Object { 
    $_.Attributes -band [IO.FileAttributes]::Directory 
} 

或像這樣:

$DirectoryInfo = Get-ChildItem $PathOutput | Where-Object { 
    $_.GetType() -eq [IO.DirectoryInfo] 
} 

或(更好的)是這樣的:

$DirectoryInfo = Get-ChildItem $PathOutput | Where-Object { $_.PSIsContainer } 

您可以輸出文件夾列表,或 「無」,如果有間沒有」 t any,like this:

if ($DirectoryInfo) { 
    $DirectoryInfo | Select-Object -Expand FullName 
} else { 
    'none' 
} 

因爲空結果($null)是interpreted as $false

+0

非常感謝,正是我需要的,它也工作得很好! – Alex

1

你也許可以做這樣的事情?這樣你也不必兩次得到這些子項。

$PathOutput = "C:\Users\David\Documents" 
$childitem = Get-ChildItem $PathOutput | ?{ $_.PSIsContainer } | select fullname, name 

if ($childitem.count -eq 0) 
{ 
$FailedTests = "none" 
} 
else 
{ 
$FailedTests = $childitem 
} 
$FailedTests 
+0

似乎沒有工作。如果相關目錄中不包含任何內容,仍然使用if語句的'else'部分。 $ FailedTests在這種情況下是空的... – Alex

相關問題