如何获取目录列表或者没有'?

时间:2016-03-05 10:22:38

标签: powershell powershell-v2.0

使用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或仅使用一次的解决方案。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

错误实际上是不言自明的:Get-ChildItem(在PowerShell v2中)没有参数-Attributes。使用PowerShell v3添加了该参数(以及参数-Directory)。在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 }

您可以输出文件夹列表,或者&#34;无&#34;如果没有,就像这样:

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

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