【问题标题】:How to add print to console in PowerShell script?如何在 PowerShell 脚本中将打印添加到控制台?
【发布时间】:2017-03-28 10:51:51
【问题描述】:

我是 PowerShell 新手,我创建了以下代码来删除特定文件和文件夹:

$myFolderPath = "C:\Test"
$myLimit = (Get-Date).AddDays(-14)

# Delete files according to filter.
Get-ChildItem -Path $myFolderPath -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $myLimit} | Remove-Item -Force

# Delete empty folders.
Get-ChildItem -Path $myFolderPath -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

是否可以在执行实际的 Remove-Item 操作之前将要删除的每个项目的完整路径打印到控制台?

我猜……必须在这里添加....

... | Remove-Item -Force

这里……

... | Remove-Item -Force -Recurse

但我不知道如何以优雅的方式实现它(没有代码重复)。

【问题讨论】:

  • 我猜这是how-to-delete-empty-subfolders-with-powershell 的编辑不当的副本。无论如何,当文件夹被删除时,打印文件夹有什么用。也许你应该看看 Remove-Item 的 -whatif 选项
  • 我想将它们打印到控制台,以便能够查看大树中的哪些文件夹已被例程删除。
  • 感谢您对 -whatif 选项的提示。但这不是我需要的。

标签: powershell


【解决方案1】:

您可以将remove-Item-Parts 替换为

Foreach-Object { $_.fullname; Remove-Item -Path $_.Fullname (-Recurse) -Force}

LotPings 评论可能是更好的主意,如果这是您想要的。

【讨论】:

  • 当我运行它时,它返回“cmdlet Remove-Item at command pipeline position 1 Supply values for the following parameters: Path[0]:”。看来 Remove-Item 不知道要删除什么...
  • 试试Remove-Item -Path $_.Fullname ...
  • @LotPings。谢谢。现在它起作用了。相应地修改了代码。
  • 是的,错过了$_
【解决方案2】:

它没有引起太多关注,但Tee-Object 可能是这里管道的一个简单补充。将输出重定向到稍后可以打印的变量。

...Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $myLimit} |
    Tee-Object -Variable removed | Remove-Item -Force
$removed | Write-Host

所有通过管道传输的文件对象都将发送到$removed,然后再发送到Remove-Item。由于您有多个删除管道,您还可以使用-Append 参数,以便根据需要将所有文件保存在一个变量中。

但这并不意味着它们已被删除。只是他们让它通过了管道。如果您真的想确定是否应该使用其他实用程序,例如具有日志记录功能的 robocopy。

【讨论】:

    猜你喜欢
    • 2012-09-04
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多