我正在尝试编写PS脚本以在参数指定的目录中查找空目录。 “空目录”不应包含任何文件和子目录。
这是剧本:
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”的输出而不是下面没有文件/子目录的目录的名称。
答案 0 :(得分:2)
尝试一下:
Get-ChildItem $Path -Recurse -Force |
Where-Object {$_.PSIsContainer -and (Get-ChildItem $_.FullName -Force | Measure-Object).Count -eq 0}