PowerShell删除文件夹前判断存在性及导出现存目录的实现方法
PowerShell两项任务实现方案
1. 批量删除list.txt中存在的文件夹
你原有代码的问题:Get-Content读取txt返回的是每行路径组成的数组,直接把整个数组传入Test-Path无法完成逐个校验,必须搭配foreach循环逐行处理。
正确实现代码:
# 读取list.txt中的所有路径,自动忽略空行 $folderList = Get-Content -Path "c:\SCO_scripts\homedirectory_delete\list.txt" | Where-Object { $_ -notmatch '^\s*$' } foreach ($folder in $folderList) { # 校验当前路径是存在的文件夹 if (Test-Path -Path $folder -PathType Container) { # 存在则执行删除,-Force可以跳过权限提示、删除隐藏/只读文件 Remove-Item -Path $folder -Force -Recurse # 可选:输出删除日志方便核对 Write-Host "已删除文件夹:$folder" } }
2. 筛选存在的文件夹路径写入新文件
你原有代码的问题:PowerShell中没有exists命令,判断路径存在需要用Test-Path,且需要加if判断,仅当路径存在时才执行写入操作。
正确实现代码:
$folderList = Get-Content -Path "c:\SCO_scripts\homedirectory_delete\list.txt" | Where-Object { $_ -notmatch '^\s*$' } # 提前清空目标文件内容,避免重复写入 $outputPath = "C:\SCO_scripts\homedirectory_delete\newFile.txt" if (Test-Path -Path $outputPath) { Clear-Content -Path $outputPath } foreach ($folder in $folderList) { if (Test-Path -Path $folder -PathType Container) { Add-Content -Path $outputPath -Value $folder } }
如果想要更简洁的写法,也可以直接用管道一行完成筛选写入:
Get-Content "c:\SCO_scripts\homedirectory_delete\list.txt" | Where-Object { (Test-Path $_ -PathType Container) -and ($_ -notmatch '^\s*$') } | Set-Content "C:\SCO_scripts\homedirectory_delete\newFile.txt"
内容的提问来源于stack exchange,提问作者rolfderwolf
相关产品推荐
相关产品推荐

