【问题标题】:How to run script for each element in pipe?如何为管道中的每个元素运行脚本?
【发布时间】:2012-12-17 10:02:01
【问题描述】:
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

谁能帮帮我?

【问题讨论】:

  • 什么是full组合脚本?
  • 嗨,我已经发布了组合脚本。
  • 哦,是的,这看起来非常无效:(看起来目标是“为管道中的每个元素”“执行”第二个 sn-p,是吗?如果是这样,请参阅ForEach -简而言之,.. | ForEach-Object { "2nd script" } - 但也请参阅foreach
  • 你能发布最终的脚本吗?

标签: shell powershell


【解决方案1】:

您需要在管道的最后一部分使用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

【讨论】:

  • 您的脚本可以正常运行,但我总是收到提示消息框,如何避免?
  • 你会得到哪个提示信息框?尝试在 Remove-Item cmdlet 上使用 -Force 参数。
  • 我正在使用 $item.InvokeVerb("delete"),MessageBox 是“您确定要将此文件夹移动到回收站吗?”
  • 为什么不用Remove-Item然后就不会提示了?
  • 因为我不想永久删除它们,所以我在做这样的事情时可能会出错。稍后,我可以检查回收站以避免出错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2014-02-06
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多