PowerShell批量配置用户壁纸遇op_Addition方法错误求助
解决PowerShell添加.DEFAULT用户配置文件时的op_Addition报错问题
错误原因
报错Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'的核心问题是:当系统中只有一个用户配置文件时,Get-ItemProperty返回的是单个PSObject对象而非数组。此时用+=运算符尝试添加.DEFAULT配置文件对象会失败——因为单个PSObject实例没有定义加法操作。
修复方案
1. 强制将用户配置文件转为数组
在获取用户配置文件的语句外层包裹@(...),确保$UserProfiles始终是数组类型,哪怕只返回一个对象:
$UserProfiles = @(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*" | Where {$_.PSChildName -match "S-1-5-21-(\d+-?){4}$" } | Select-Object @{Name="SID"; Expression={$_.PSChildName}}, @{Name="UserHive";Expression="$($_.ProfileImagePath)\NTuser.dat"})
2. 完整修复后的脚本
# Get each user profile SID and Path to the profile - 强制转为数组 $UserProfiles = @(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*" | Where {$_.PSChildName -match "S-1-5-21-(\d+-?){4}$" } | Select-Object @{Name="SID"; Expression={$_.PSChildName}}, @{Name="UserHive";Expression="$($_.ProfileImagePath)\NTuser.dat"}) # Add in the .DEFAULT User Profile $DefaultProfile = "" | Select-Object SID, UserHive $DefaultProfile.SID = ".DEFAULT" $DefaultProfile.UserHive = "C:\Users\Public\NTuser.dat" $UserProfiles += $DefaultProfile # Loop through each profile on the machine Foreach ($UserProfile in $UserProfiles) { # 先检查NTuser.dat文件是否存在 if (-not (Test-Path $UserProfile.UserHive)) { continue } # Load User ntuser.dat if it's not already loaded If (($ProfileWasLoaded = Test-Path Registry::HKEY_USERS\$($UserProfile.SID)) -eq $false) { Start-Process -FilePath "CMD.EXE" -ArgumentList "/C REG.EXE LOAD HKU\$($UserProfile.SID) $($UserProfile.UserHive)" -Wait -WindowStyle Hidden } # Write to the registry $key = "Registry::HKEY_USERS\$($UserProfile.SID)\Control Panel\Desktop" # 确保注册表路径存在,不存在则创建 if (-not (Test-Path $key)) { New-Item -Path $key -Force | Out-Null } Set-ItemProperty -Path $key -Name Wallpaper -Value "$WallpaperPath" Set-ItemProperty -Path $key -Name TileWallpaper -Value "0" Set-ItemProperty -Path $key -Name WallpaperStyle -Value "$Style" -Force # Unload NTuser.dat If ($ProfileWasLoaded -eq $false) { [gc]::Collect() Start-Sleep 1 Start-Process -FilePath "CMD.EXE" -ArgumentList "/C REG.EXE UNLOAD HKU\$($UserProfile.SID)" -Wait -WindowStyle Hidden | Out-Null } }
额外优化点
- 添加了
NTuser.dat文件存在性检查,避免尝试加载不存在的文件 - 增加注册表路径检查,不存在则自动创建,避免
Set-ItemProperty报错
内容的提问来源于stack exchange,提问作者Adam Kohne
相关产品推荐
相关产品推荐

