You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

远程删除用户配置文件夹(排除Administrator)的PowerShell脚本报错求助

批量删除多台计算机用户配置文件夹(排除Administrator)的PowerShell脚本报错修复

问题背景

需批量删除多台远程计算机的用户配置文件夹,但保留Administrator文件夹,使用的脚本运行时触发参数验证错误,单台本地执行同逻辑命令却正常。

原脚本

$Computerlist = get-content C:\windows\temp\pc.txt 
Foreach ($computer in $Computerlist) 
{Get–ChildItem –Path \\$computer\c$\users\*.* –Include *.*  –Force | Where-Object $_.Name -notmatch "Administrator" | Remove-Item -Force -Recurse
}

报错信息(已翻译为中文)

Where-Object : 无法验证参数“Property”的参数。参数为 null 或空。请提供一个非 null 或空的参数,然后重试该命令。
在行:4 字符:82
+ ... uter\c$\users\*.* -Include *.*  -Force | Where-Object $_.Name -ne "Ad ...
+                                                           ~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Where-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WhereObjectCommand

Where-Object : 无法验证参数“Property”的参数。参数为 null 或空。请提供一个非 null 或空的参数,然后重试该命令。
在行:4 字符:82
+ ... uter\c$\users\*.* -Include *.*  -Force | Where-Object $_.Name -ne "Ad ...
+                                                           ~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Where-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WhereObjectCommand

单台本地可正常执行的命令

Get–ChildItem –Path c:\users\*.* –Include *.*  –Force | Where-Object $_.Name -notmatch "Administrator" | Remove-Item -Force -Recurse

问题根源

Where-Object的语法错误:使用比较运算符(如-notmatch)时,必须将过滤表达式包裹在{}中。原脚本未加花括号,PowerShell错误地将$_.Name解析为Property参数的输入值,导致参数为空触发校验失败。

单台本地执行时可能因PowerShell的解析容错机制暂时规避了错误,但批量循环的严格参数校验会暴露该问题。

修正后的脚本

$Computerlist = Get-Content C:\windows\temp\pc.txt 
foreach ($computer in $Computerlist) {
    # 遍历远程计算机Users目录下所有对象,排除Administrator文件夹
    Get-ChildItem -Path "\\$computer\c$\users\*" -Force | 
        Where-Object { $_.Name -notmatch "Administrator" } | 
        Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}

优化说明

  • 移除冗余的-Include *.*:Get-ChildItem默认匹配所有文件和文件夹,无需额外指定
  • 添加-ErrorAction SilentlyContinue:避免因个别文件夹权限不足、不存在等异常导致脚本中断
  • 代码换行格式化:提升脚本可读性,便于维护

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:03:36