Windows Power shell 脚本未按预期运行
WindowsPower shell script not working as expecting
大家好,我有脚本需要删除超过 90 天的时间 files.issue 没有时间计算 90 天的脚本工作 fine.if 我们添加条件来检查时间范围,例如:90 天不工作。
我有特定的文件夹,其中包含脚本下面的子文件夹不删除子文件夹下的文件脚本删除文件只指定文件夹它删除子文件夹文件。
我们有需求能力 shell 脚本,它应该删除超过 90 天的文件,它也应该删除子文件夹下的文件。
任何人都可以建议对以下脚本需要做的任何更改
Get-ChildItem -Path "D:\samples\" -Include *.* -Recurse -Force | where CreationTime -lt (Get-Date).AddDays(-10) | foreach {$_.Delete()}
您的 | where
需要大括号 {}
。该对象由 $_
引用。使用它,您的代码将如下所示:
Get-ChildItem -Path "D:\samples\" -file -Recurse -Force | where {$_.CreationTime -lt (Get-Date).AddDays(-10)} | foreach {$_.Delete()}
注意:我将 -Include "."
替换为 -file
以包含所有文件。这至少需要 3.0 版的 powershell。使用 $Host
检查版本
您对几个 powershell 标签(通常相互排斥)的使用不明确,
如果您想确保脚本在 PSv2 下可运行,请仅使用该标签。
Remove-Item
cmdlet 直接接受管道输入,因此我将使用它来代替 ForEach-Object 和对象 .delete()
方法。
-File
参数需要 PSv3+ ,替代方法是检查 (not=!
) $_.PSIsContainer
该脚本在 IMO 中更易于阅读 PowerShell 期望连续和缩进的断行:
## Q:\Test19\SO_54311383.ps1
$BasePath = "D:\samples\*"
$Treshold = (Get-Date).Date.AddDays(-10)
Get-ChildItem -Path $BasePath -Recurse -Force |
Where-Object {!$_.PSIsContainer -and
$_.CreationTime -lt $Treshold} |
Remove-Item -WhatIf # -Force
如果输出正常,请删除最后一行的 -WhatIf
。
最终必要的 -Force
参数暂时被注释掉。
大家好,我有脚本需要删除超过 90 天的时间 files.issue 没有时间计算 90 天的脚本工作 fine.if 我们添加条件来检查时间范围,例如:90 天不工作。
我有特定的文件夹,其中包含脚本下面的子文件夹不删除子文件夹下的文件脚本删除文件只指定文件夹它删除子文件夹文件。
我们有需求能力 shell 脚本,它应该删除超过 90 天的文件,它也应该删除子文件夹下的文件。
任何人都可以建议对以下脚本需要做的任何更改
Get-ChildItem -Path "D:\samples\" -Include *.* -Recurse -Force | where CreationTime -lt (Get-Date).AddDays(-10) | foreach {$_.Delete()}
您的 | where
需要大括号 {}
。该对象由 $_
引用。使用它,您的代码将如下所示:
Get-ChildItem -Path "D:\samples\" -file -Recurse -Force | where {$_.CreationTime -lt (Get-Date).AddDays(-10)} | foreach {$_.Delete()}
注意:我将 -Include "."
替换为 -file
以包含所有文件。这至少需要 3.0 版的 powershell。使用 $Host
您对几个 powershell 标签(通常相互排斥)的使用不明确,
如果您想确保脚本在 PSv2 下可运行,请仅使用该标签。
Remove-Item
cmdlet 直接接受管道输入,因此我将使用它来代替 ForEach-Object 和对象 .delete()
方法。
-File
参数需要 PSv3+ ,替代方法是检查 (not=!
) $_.PSIsContainer
该脚本在 IMO 中更易于阅读 PowerShell 期望连续和缩进的断行:
## Q:\Test19\SO_54311383.ps1
$BasePath = "D:\samples\*"
$Treshold = (Get-Date).Date.AddDays(-10)
Get-ChildItem -Path $BasePath -Recurse -Force |
Where-Object {!$_.PSIsContainer -and
$_.CreationTime -lt $Treshold} |
Remove-Item -WhatIf # -Force
如果输出正常,请删除最后一行的 -WhatIf
。
最终必要的 -Force
参数暂时被注释掉。