PowerShell磁盘清理脚本非交互式运行确认提示问题求助
编写了一个磁盘空间阈值触发的PowerShell清理脚本,脚本从C:\paths2.txt读取待清理路径。使用PDQ Deploy非交互模式运行时出现错误:
"Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.
At C:\Windows\AdminArsenal\PDQDeployRunner\service-4\exec\Error Handling Wrapper.ps1:58 char:2"
交互模式测试时,会弹出删除确认提示:
Confirm
The item at Microsoft.PowerShell.Core\FileSystem::C:\LocalSlaveData\O has children and the Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
已添加-Force参数但仍出现提示,需修改脚本强制删除包含子文件夹的项,避免确认提示。
原脚本代码:
# Check if free space on local disk C is less than 20% $disk = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='C:'" $freeSpaceGB = [math]::Round(($disk.FreeSpace / 1GB), 2) $percentFree = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2) if ($percentFree -gt 20) { Write-Host "Free space on local disk C is greater than 20%. Script will exit." Exit } # Read the list of paths to delete files from the paths.txt file $paths = Get-Content "C:\paths2.txt" # Loop through each path and delete files that are more than 3 days old $totalDataDeleted = 0 foreach ($path in $paths) { $files = Get-ChildItem $path -Recurse -Force | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-3) } $dataDeleted = ($files | Measure-Object -Property Length -Sum).Sum $totalDataDeleted += $dataDeleted $files | Remove-Item -Force } # Display the total amount of data deleted in GB $totalDataDeletedGB = [math]::Round(($totalDataDeleted / 1GB), 2) Write-Host "$totalDataDeletedGB GB of data has been deleted."
问题核心是:删除包含子项的文件夹时,仅用-Force不足以跳过确认,必须明确指定-Recurse参数告知PowerShell递归删除所有子内容。同时可以添加错误处理避免非预期中断。
具体修改点
- 在
Remove-Item命令中补充-Recurse参数,彻底跳过子项删除确认 - 可选添加
-ErrorAction SilentlyContinue忽略删除不存在项等非致命错误 - 建议用更现代的
Get-CimInstance替代Get-WmiObject(PowerShell 5.1及以上支持),提升兼容性和性能
修改后的完整脚本
# 检查C盘剩余空间是否低于20% $disk = Get-CimInstance -Class Win32_LogicalDisk -Filter "DeviceID='C:'" $freeSpaceGB = [math]::Round(($disk.FreeSpace / 1GB), 2) $percentFree = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2) if ($percentFree -gt 20) { Write-Host "C盘剩余空间大于20%,脚本退出。" Exit } # 从paths2.txt读取待清理路径列表 $paths = Get-Content "C:\paths2.txt" # 遍历路径,删除3天前的文件和文件夹 $totalDataDeleted = 0 foreach ($path in $paths) { $items = Get-ChildItem $path -Recurse -Force | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-3) } $dataDeleted = ($items | Measure-Object -Property Length -Sum).Sum $totalDataDeleted += $dataDeleted $items | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue } # 显示清理的总空间(GB) $totalDataDeletedGB = [math]::Round(($totalDataDeleted / 1GB), 2) Write-Host "已清理 $totalDataDeletedGB GB 数据。"
内容的提问来源于stack exchange,提问作者Alan

