Get-ChildItem -recurse | Where {!$_.PSIsContainer -and `
$_.LastWriteTime -lt (get-date).AddDays(-31)} | Remove-Item -whatif
Get-ChildItem -recurse | Where {$_.PSIsContainer -and `
@(Get-ChildItem -Lit $_.Fullname -r | Where {!$_.PSIsContainer}).Length -eq 0} |
Remove-Item -recurse -whatif
上面的脚本可以正常工作,现在我想将它与fllowing脚本合并到一个脚本中:
$path = "<path to file>"
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete")
这是我的组合脚本:
Get-ChildItem -recurse | Where {$_.PSIsContainer -and `
@(Get-ChildItem -Lit $_.Fullname -r | Where {!$_.PSIsContainer}).Length -eq 0} |
$path = $_.Fullname
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete") -recurse -whatif
但是,我总是收到错误消息:
Expressions are only allowed as the first element of a pipeline.
At line:3 char:7
You must provide a value expression on the right-hand side of the '-' operator.
At line:6 char:28
Unexpected token 'recurse' in expression or statement.
At line:6 char:29
Unexpected token '-whatif' in expression or statement.
At line:6 char:37
任何人都可以帮助我吗?
答案 0 :(得分:2)
您需要在管道的最后部分使用Foreach-Object
cmdlet(别名为foreach)。此外,您不希望每次在管道中创建Shell.Application对象:
$shell = new-object -comobject "Shell.Application"
Get-ChildItem -recurse |
Where {$_.PSIsContainer -and `
@(Get-ChildItem -Lit $_.Fullname -r | Where {!$_.PSIsContainer}).Length -eq 0} |
Foreach {
$item = $shell.Namespace(0).ParseName(($_.Fullname))
$item.InvokeVerb("delete")
}
那就是说,我不确定你为什么不使用Remove-Item
cmdlet,例如:
Get-ChildItem . -r | Where {$_.PSIsContainer -and !$(Get-ChildItem $_.fullname)} |
Remove-Item -WhatIf
要将其设为脚本,只需将上述命令放在.ps1文件中,如下所示:
-- Contents of DeleteEmptyDirs.ps1 --
param([string]$path, [switch]$whatif)
Get-ChildItem $path -r | Where {$_.PSIsContainer -and !$(Get-ChildItem $_.fullname)} |
Remove-Item -WhatIf:$whatif
然后像这样调用:
PS> .\DeleteEmptyDirs c:\temp -WhatIf
PS> .\DeleteEmptyDirs c:\temp