PowerShell启动文件夹运行时偶现Add-Printer错误80070057求助
解决启动文件夹中Add-Printer偶尔失败(HRESULT 0x80070057)的问题
针对启动文件夹运行脚本时Add-Printer偶发报错(错误代码0x80070057)的问题,可从以下几个方向排查解决:
1. 等待系统服务与网络就绪
启动文件夹执行脚本时,用户会话刚初始化,Print Spooler服务或网络连接可能未完全就绪,导致调用时机过早。
- 直接添加固定延迟(可根据实际环境调整时长):
# 延迟10秒,确保服务与网络初始化完成 Start-Sleep -Seconds 10 - 或等待Print Spooler服务启动后再执行操作:
# 循环检查Print Spooler状态,直到服务运行 while ((Get-Service -Name Spooler).Status -ne 'Running') { Start-Sleep -Seconds 2 }
2. 验证网络连通性与打印机共享存在性
偶发失败可能是启动时无法访问打印服务器,可添加连通性检查:
$serverName = 'FQDMN.dmn' $maxRetries = 5 $retryCount = 0 # 检查打印服务器是否可达 while (-not (Test-Connection -ComputerName $serverName -Count 1 -Quiet) -and $retryCount -lt $maxRetries) { Start-Sleep -Seconds 3 $retryCount++ } if ($retryCount -eq $maxRetries) { Write-Error "无法连接到打印服务器 $serverName" exit 1 } # 验证目标共享打印机是否存在 $fullPrinterPath = Join-Path -Path $serverPath -ChildPath $printer if (-not (Get-WmiObject -Class Win32_SharedPrinter -Filter "Name='$printer' and ServerName='\\$serverName'")) { Write-Error "共享打印机不存在:$fullPrinterPath" exit 1 }
3. 添加重试逻辑
针对偶发的参数错误,可在捕获到对应异常时重试添加操作:
$fullPrinterPath = "$serverPath$printer" $maxAddRetries = 3 $addRetryCount = 0 $addSuccess = $false while ($addRetryCount -lt $maxAddRetries -and -not $addSuccess) { try { Add-Printer -ConnectionName $fullPrinterPath -ErrorAction Stop $addSuccess = $true } catch [Microsoft.Management.Infrastructure.CimException] { if ($_.Exception.HResult -eq 0x80070057) { $addRetryCount++ Start-Sleep -Seconds 2 } else { # 非目标异常直接抛出 throw $_ } } } if (-not $addSuccess) { Write-Error "尝试$maxAddRetries次后仍无法添加打印机:$fullPrinterPath" }
4. 确认脚本执行上下文
启动文件夹中的脚本可能受执行策略限制,可修改快捷方式的启动参数:
右键启动文件夹内的脚本快捷方式,将目标修改为:
powershell.exe -ExecutionPolicy Bypass -File "C:\路径\到\你的\脚本.ps1"
内容的提问来源于stack exchange,提问作者x-men
相关产品推荐
相关产品推荐

