我正试图编写一个PS脚本来查找由参数指定的目录中的空dirs。"空目录"不应该包含任何文件和子目录。
脚本如下:
param (
[parameter (mandatory=$true,position=0)]
[string]$Path
)
$dirInfo = get-childitem $Path -recurse | ? {$_.PSIsContainer -eq $True} | % {get-childitem $_} | Measure-Object
$dirInfo | ? {$dirInfo.count -eq 0} | Select-Object Fullname
当我在"C:'documents文件夹"上运行它时,我得到了以下错误:
**get-childitem : Cannot find path 'C:'Documents'ManualScripts'accounts' because it does not exist.
At C:'Documents'ManualScripts'Check-no-file-and-subdir-dir.ps1:5 char:79
+ $dirInfo = get-childitem $Path -recurse | ? {$_.PSIsContainer -eq $True} | % {ge ...
+ ~~
+ CategoryInfo : ObjectNotFound: (C:'Documents'ManualScripts'accounts:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand**
在C:'documents下的每个子文件夹中都有很多类似的错误。它将脚本本身所在的目录(C:'Documents'ManualScripts)附加到子目录名称。
我做了调查,还是没弄明白。任何输入赞赏。谢谢:)在上面的帖子之后,我对脚本做了一些更改,但到目前为止仍然没有工作:
param (
[parameter (mandatory=$true,position=0)]
[string]$Path
)
$Dirs = Get-ChildItem $Path -recurse | ? {$_.PSIsContainer -eq $True} | ForEach-Object -Process {$_.FullName} #get list of all directories with whole path
foreach ($Dir in $Dirs) {
$emptyDir = Get-ChildItem $Dir | Measure | where {$_.Count -eq 0} | select-Object
}
睡觉前,我相信我取得了一点进步。脚本现在看起来是这样的:
param (
[parameter (mandatory=$true,position=0)]
[string]$Path
)
$Dirs = Get-ChildItem $Path -recurse | ? {$_.PSIsContainer -eq $True} | ForEach-Object -Process {$_.FullName} #get list of all directories with whole path
#$Dirs | ForEach-Object {Get-ChildItem $_} | ForEach-Object {measure} | where {$_.Count -eq 0} | Select-Object $Dirs
ForEach ($Dir in $Dirs) {
$emptyDir = Get-ChildItem $Dir | Measure | where {$_.Count -eq 0} | Select-Object
$emptyDir
}
如果我运行的有输出的东西(虽然不是我所期望的)
PS C:'Documents'ManualScripts> .'Check-no-file-and-subdir-dir-rev01.ps1
cmdlet Check-no-file-and-subdir-dir-rev01.ps1 at command pipeline position 1
Supply values for the following parameters:
Path: C:'documents
Count : 0
Average :
Sum :
Maximum :
Minimum :
Property :
Count : 0
Average :
Sum :
Maximum :
Minimum :
Property :
......
......
像"Select-Object"这样的选项会选择"measure"的输出,而不是下面没有文件/子目录的目录名。
试一试:
Get-ChildItem $Path -Recurse -Force |
Where-Object {$_.PSIsContainer -and (Get-ChildItem $_.FullName -Force | Measure-Object).Count -eq 0}