如何修改PowerShell脚本实现从计算机列表批量执行任务?
批量处理多计算机的PowerShell脚本修改方案
原脚本已实现清除错误日志、连接网络驱动器、删除10天前文件、断开网络驱动器、记录操作日志这5项功能,以下是修改后的脚本,可从计算机列表中逐个读取目标主机并执行任务:
修改后的完整脚本
# 定义要处理的计算机列表,可直接写数组或从文本文件读取(示例为数组) $computers = @("Computer1", "Computer2", "Computer3") # 文件保留天数:删除超出该天数的文件 $retentionDays = 10 # 日志文件路径 $date = Get-Date -Format dd-MM-yyyy $logFilePath = "C:\LOGS\Log_$date.txt" # 确保日志目录存在,不存在则自动创建 if (-not (Test-Path "C:\LOGS")) { New-Item -Path "C:\LOGS" -ItemType Directory -Force | Out-Null } # 遍历每个计算机执行任务 foreach ($computer in $computers) { # 每次处理前清空错误记录 $Error.Clear() $currentTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $logPrefix = "[$currentTime] 计算机 $computer :" try { # 1. 连接网络驱动器(使用临时驱动器名,避免冲突) $driveName = "T" # 选择未被占用的驱动器字母即可 $networkPath = "\\$computer\c`$\Folder" # 先检查驱动器是否已存在,存在则移除 if (Get-PSDrive -Name $driveName -ErrorAction SilentlyContinue) { Remove-PSDrive -Name $driveName -Force -ErrorAction Stop } New-PSDrive -Name $driveName -PSProvider FileSystem -Root $networkPath -ErrorAction Stop | Out-Null Add-Content -Path $logFilePath -Value "$logPrefix 成功连接网络驱动器:$driveName -> $networkPath" # 2. 删除10天前的文件(改用PowerShell原生命令,兼容性更强) $filesToDelete = Get-ChildItem -Path "$driveName:\" -Recurse -File -Force -ErrorAction Stop | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$retentionDays) } if ($filesToDelete.Count -gt 0) { $filesToDelete | Remove-Item -Force -ErrorAction Stop Add-Content -Path $logFilePath -Value "$logPrefix 成功删除 $($filesToDelete.Count) 个过期文件" } else { Add-Content -Path $logFilePath -Value "$logPrefix 未找到符合条件的过期文件" } # 3. 断开网络驱动器 Remove-PSDrive -Name $driveName -Force -ErrorAction Stop Add-Content -Path $logFilePath -Value "$logPrefix 成功断开网络驱动器:$driveName" } catch { # 捕获操作中的异常并记录详细错误信息 Add-Content -Path $logFilePath -Value "$logPrefix 操作失败,错误详情:$_" # 尝试清理已连接的驱动器(若存在) if (Get-PSDrive -Name $driveName -ErrorAction SilentlyContinue) { Remove-PSDrive -Name $driveName -Force | Out-Null } } # 用分隔线区分不同计算机的日志记录 Add-Content -Path $logFilePath -Value "-----------------------------------------" }
关键改动说明
- 计算机列表灵活配置:直接用数组定义目标计算机,也可改为从文本文件读取(如
$computers = Get-Content -Path "C:\hosts.txt"),方便批量维护主机清单。 - 动态适配网络路径:将固定的
\\Computer1\c$\Folder替换为\\$computer\c$\Folder,自动匹配当前遍历的计算机。 - 避免驱动器冲突:每次处理前检查目标驱动器是否存在,存在则先移除;同时移除
-Persist参数,使用临时映射而非持久化驱动器,防止影响后续操作。 - 替换forfiles为PowerShell原生命令:
Get-ChildItem比forfiles兼容性更好,支持更灵活的筛选规则,且便于捕获操作错误。 - 细化日志记录:每条日志添加时间戳和计算机标识,清晰区分不同主机的操作结果;记录文件删除数量、错误详情等关键信息,便于排查问题。
- 异常处理增强:用
try/catch包裹整个任务流程,确保单台机器操作失败时不中断整个批量任务,同时自动清理已连接的驱动器。 - 日志目录预检查:自动创建日志目录,避免因目录不存在导致日志写入失败。
内容的提问来源于stack exchange,提问作者Дмитрий Захаров
相关产品推荐
相关产品推荐

