powershell - Powershell 脚本根据其结束域在多台服务器上执行不同的操作
问题描述
我一直在尝试编写一个脚本,该脚本将在以文本形式(来自 .txt 或 .csv)给出的所有主机上执行一些操作 --> 演示:
**## C:\hosts.txt**
- Machine4.Int.ecom.domain
- Machine3.emea.domain.com
- Machine1.production.domain.com
- Machine2.quality.domain.com
理想情况下,脚本的任务是使用 Get-Date
Clear-Host
Set-ExecutionPolicy RemoteSigned
$Now = Get-Date
$Days = @("90","30","14","7") ## THIS LINE SHOULD BE DEPENDING DOMAIN IN HOSTNAME
$TargetFolder = @("C:\Windows\SoftwareDistribution\Downloads","C:\Windows\Temp","C:\Windows\CCMCache")
$Extension = @("*.vhk*","*.txt*")
$LastWrite = $Now.AddDays(-$Days)
$Files = Get-ChildItem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
例如,假设我有以下主机名:
- Machine1.production.domain.com
- Machine2.quality.domain.com
- Machine3.emea.domain.com
- Machine4.Int.ecom.domain
现在,基于域“.production”或“.quality”或“.emea”或“.int”,我想执行以下操作。
- 在生产服务器中 -> 删除超过 90 天的文件。
- 在质量服务器 -> 删除超过 30 天的文件。
- 在 emea 服务器中 -> 删除超过 14 天的文件。
- 在 INT 服务器中 -> 删除超过 7 天的文件。
删除后,它还会将文件路径保存在 CSV 文件中,以便我可以在必要时仔细检查并恢复它们。
你能帮我解决这个问题吗?提前致谢。
解决方案
如果您使用的是包含服务器的文本文件,则可以在遍历服务器的循环中添加 use 开关,并在那里设置清理参考日期:
$servers = Get-Content -Path 'C:\hosts.txt'
$targetFolders = "C:\Windows\SoftwareDistribution\Downloads","C:\Windows\Temp","C:\Windows\CCMCache"
$extensions = "*.vhk","*.txt"
$today = (Get-Date).Date
foreach ($machine in $servers) {
# determine the reference date by the machine's name
$refDate = switch -Regex ($machine) {
'\.production\.' { $today.AddDays(-90); break }
'\.quality\.' { $today.AddDays(-30); break }
'\.emea\.' { $today.AddDays(-14); break }
'\.int\.' { $today.AddDays(-7) }
}
Invoke-Command -ComputerName $machine -ScriptBlock {
$Files = Get-ChildItem -Path $using:targetFolders -File -Include $using:extensions -Recurse |
Where-Object {$_.LastWriteTime -le $using:refDate}
# do your clean-up here on the files you have gathered
# maybe write a log first or simply delete these files?
}
}