如何获取目录列表或'none'?

How to get a list of directories or 'none'?

使用 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

我在 Windows Server 2008 上使用 Powershell 2.0。

我更喜欢使用 Get-ChildItem 或仅使用一次的解决方案。

你也许可以做这样的事情?这样您也不必两次获取子项。

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

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

该错误实际上是不言自明的: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 }

你可以输出文件夹列表,或者"none"如果没有,像这样:

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

因为空结果 ($null) 是 interpreted as $false