设想:
我对 Powershell 有点陌生,我希望在这里能得到一点帮助。运行此脚本后,Powershell 似乎存在会话内存泄漏。它在尝试删除第 58 个日志位置后停止(如果我使用批处理文件运行此脚本,则为 56 个),总共应该有 93 个要删除。经过一番研究,我发现这是微软的一个已知错误,powershell 在当前会话执行后不会完全关闭命令。
目标:
目标是编写一个自动化脚本,该脚本将删除日期早于用户在执行命令时输入的日期(使用天数)的文件夹和文件。
test1.ps1 内容:
# Gets number of days input by user as a variable
param($NumberOfDays)
If ($NumberOfDays -eq $null) {
Write-Output "Please enter number of days you want to keep logs for"
Write-Output "Example: test1.ps1 30"
Exit
}
elseif ($NumberOfDays -ge 0) {
Write-Output "You have entered $NumberOfDays days to keep logs"
}
#*Note* I use the -whatif switch to see if it will delete the folders and files without actually deleting them.
dir \\server\dir1\dir2\logs -recurse | where { ((get-date)-$_.creationTime).days -ge $NumberOfDays} | remove-item -force -recurse -whatif
Write-Output "Exiting Script"
运行命令“test1.ps1 18”后的输出:
What if: Performing operation "Remove Directory" on Target "\\server\dir1\dir2\logs\192716".
What if: Performing operation "Remove Directory" on Target "\\server\dir1\dir2\logs\192981".
What if: Performing operation "Remove Directory" on Target "\\server\dir1\dir2\logs\193046".
What if: Performing operation "Remove Directory" on Target "\\server\dir1\dir2\logs\193063".
What if: Performing operation "Remove Directory" on Target "\\server\dir1\dir2\logs\193065".
What if: Performing operation "Remove Directory" on Target "\\server\dir1\dir2\logs\191335".
Freezes once it gets to the 58th folder (should be a total of 93 folders)
问题:
我想知道如何让这个 dir 命令:
- 最多执行 20 个删除命令
- 运行检查以查看是否有更多文件夹/文件要删除
- 如果有更多文件夹/文件要删除,请关闭 powershell 会话并打开一个新会话,然后重新运行 dir/del 命令并进行检查。
- elsif 没有要删除的文件夹/文件,退出脚本。
PS如果有比步骤1-4更好的算法,请随时添加有用的输入。