具有多个 session 的 Powershell 独立脚本

标签 powershell

场景:

我对 Powershell 有点陌生,我希望能在这里得到一点帮助。运行此脚本后,Powershell 似乎出现了 session 内存泄漏。它在尝试删除第 58 个日志位置后停止(如果我使用批处理文件运行此脚本,则为 56 个),总共应该删除 93 个。经过一些研究,我发现这是微软的一个已知错误,在当前 session 中执行命令后,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 命令:

  1. 执行最多 20 个删除命令
  2. 检查是否有更多文件夹/文件要删除
  3. 如果有更多文件夹/文件要删除,请关闭 powershell session 并打开一个新 session ,然后重新运行 dir/del 命令并进行检查。
  4. elsif 没有更多的文件夹/文件要删除,退出脚本。

附言如果有比步骤 1-4 更好的算法,请随时添加有用的输入。

最佳答案

你如何运行命令 powershell 调用命令 ( http://technet.microsoft.com/en-us/library/hh849719.aspx )

查看后台执行的-AsJob部分

关于具有多个 session 的 Powershell 独立脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18707234/

相关文章:

powershell - 如何获取 tfs 构建服务器上的当前变更集 ID?

c# - 无法使用 PowerShell 通过管道传输控制台应用程序的无限输出

powershell - 永久点源文件?

date - 将格式化的日期值存储到命令行的环境变量中

Powershell - 从字符串中排除文件夹

powershell - 具有Powershell问题的ConvertTo-HTML

powershell - 如何构建属性数组以传递到 Powershell 中的 Invoke-Command 中?

powershell - 如何使用powershell调用SHGetKnownFolderPath?

windows - 同步windows文件夹

powershell - MySQLDUMP与CMD/Powershell的区别