如何获取目录列表或'无'?
使用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
或仅使用一次。
错误实际上是相当不言自明的: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
。
你也许可以做这样的事情?这样你也不必两次得到这些子项。
$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在这种情况下是空的... – Alex
非常感谢,正是我需要的,它也工作得很好! – Alex