【问题标题】:How to get a list of directories or 'none'?如何获取目录列表或“无”?
【发布时间】:2016-06-19 04:24:04
【问题描述】:

使用 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:找不到与参数名称“属性”匹配的参数。
在 D:\Testing\Data\Powershell\LoadRunner\LRmain.ps1:52 char:62
+ $FailedTests = Get-ChildItem $PathOutput -Name -Attributes 

我在 Windows Server 2008 上使用 Powershell 2.0。

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

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案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 }
    

    您可以输出文件夹列表,如果没有,则输出“无”,如下所示:

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

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

    【讨论】:

    • 非常感谢,正是我所需要的,它也能正常工作!!
    【解决方案2】:

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

    $PathOutput = "C:\Users\David\Documents"
    $childitem = Get-ChildItem $PathOutput | ?{ $_.PSIsContainer } | select fullname, name
    
    if ($childitem.count -eq 0)
    {
    $FailedTests = "none"
    }
    else
    {
    $FailedTests = $childitem
    }
    $FailedTests
    

    【讨论】:

    • 似乎不起作用。如果有问题的目录不包含任何内容,则仍然使用 if 语句的“else”部分。在这种情况下,$FailedTests 是空的 ...
    猜你喜欢
    • 2020-07-24
    • 2011-04-22
    • 1970-01-01
    • 2012-06-28
    • 2013-11-18
    • 2013-02-02
    • 2011-07-15
    • 2017-01-18
    相关资源
    最近更新 更多