1
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

上面的脚本可以正常工作,现在我想把它和下面的脚本合并成一个脚本:

$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

任何人都可以帮助我吗?

4

1 回答 1

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-Itemcmdlet,例如:

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
于 2013-01-03T02:30:50.630 回答