windows-ps1-脚本-删除文件

这里是目录标题

脚本部分代码

ps1 复制代码
 # 获取文件夹下的所有文件
$files = Get-ChildItem -Path $uncPath -File
 
 if ($files.Count -gt 0) {
     Write-Host "正在删除 $($files.Count) 个文件..." -ForegroundColor Yellow
     $files | Remove-Item -Force
     Write-Host "已删除文件夹下的所有文件" -ForegroundColor Green
     
     return @{
         Exists = $true
         Action = "deleted"
         FileCount = $files.Count
     }
 }
 else {
     Write-Host "文件夹为空,无需删除" -ForegroundColor Yellow
     
     return @{
         Exists = $true
         Action = "empty"
         FileCount = 0
     }
 }

🔧 功能说明

该脚本用于批量删除指定网络共享路径(UNC路径)下的所有文件,并返回操作结果。核心功能包括:

  • 自动检测目标文件夹是否存在文件
  • 强制删除文件(忽略确认提示)
  • 返回结构化操作结果(文件数量、操作状态)

📝 参数配置

参数 必填 示例值 说明
$uncPath \Server\Share 网络共享路径(需双反斜杠)

🚀 执行步骤

权限验证:

powershell 复制代码
Test-Path -Path $uncPath  # 验证访问权限

若返回False需检查:

  • 网络连接是否正常
  • 账户是否具有写权限
  • 防火墙是否阻止445端口

执行脚本:

powershell 复制代码
# 示例:删除\\FileServer\Temp下的文件
$uncPath = "\\FileServer\Temp"
& {
  $files = Get-ChildItem -Path $uncPath -File
  # 后续删除逻辑...
}

结果解读:

powershell 复制代码
@{
  Exists = $true     # 路径存在性
  Action = "deleted" # 操作类型(deleted/empty)
  FileCount = 15     # 处理文件数量
}

⚠️ 注意事项

强制删除风险:

使用-Force参数会跳过系统文件保护

不可恢复操作,建议先备份

特殊文件处理:

只读文件:自动移除只读属性后删除

隐藏文件:包含-File参数时自动包含

锁定文件:需配合Unlocker工具先解锁

性能优化:

powershell 复制代码
# 添加分批处理(超过1000文件时)
$files | ForEach-Object -Parallel {
  Remove-Item $_.FullName -Force
} -ThrottleLimit 50

🛠 错误处理

错误码 原因 解决方案
0x80070005 权限不足 检查共享权限和NTFS权限
0x80070035 网络路径无效 检查网络连接和路径拼写
0x80070020 文件被占用 使用Handle.exe工具解除占用

📊 操作日志示例

log 复制代码
正在删除 15 个文件...
已删除文件夹下的所有文件
返回结果:
Exists : True
Action : deleted
FileCount : 15
相关推荐
coding消烦员1 小时前
在 Windows 内网搭建 Git 仓库:共享普通仓库 vs 中心 bare 仓库
windows·git
xiaoliuliu123456 小时前
IE8-WindowsXP-x86-CHS_23253_BDdl.exe 安装步骤(XP 32位简体中文版)
windows
百事牛科技6 小时前
文件不想再加密了?取消Word 打开密码的方法
windows·word
love530love7 小时前
EPGF 新手教程 13在 PyCharm(中文版 GUI)中创建 Hatch 项目环境,并把 Hatch 做成“项目自包含”(工具本地化为必做环节)
开发语言·ide·人工智能·windows·python·pycharm·hatch
峰上踏雪8 小时前
Go(Golang)Windows 环境配置关键点总结
开发语言·windows·golang·go语言
lusasky8 小时前
在Windows上编译、安装Rust
开发语言·windows·rust
麻辣长颈鹿Sir9 小时前
CMAKE指令集
linux·运维·windows·cmake·cmake指令集
Alice10299 小时前
如何在windows本地打包python镜像
开发语言·windows·python
北京流年9 小时前
windows安装jenkins并且编译app
运维·windows·jenkins
抹香鲸之海10 小时前
Easyexcel 多级横向合并表头
java·开发语言·windows