Write-Error 帮助信息

本文介绍 PowerShell 中 Write-Error 命令的使用方法,包括语法、参数及示例。通过此命令可以输出错误信息到错误管道,便于进行错误处理。
 
如下说明是翻译 : help write-error 产生的帮助信息 .
译者 : Edengundam( 马涛 )
 
Write-Error
 
大纲
输出一个对象到错误管道 (error pipeline).
 
语法
Write-Error [-message] <string> [-category {<NotSpecified> | <OpenError> | <CloseError> | <DeviceError> | <DeadlockDetected> | <InvalidArgument> | <InvalidData> | <InvalidOperation> | <InvalidResult> | <InvalidType> | <MetadataError> | <NotImplemented> | <NotInstalled> | <ObjectNotFound> | <OperationStopped> | <OperationTimeout> | <SyntaxError> | <ParserError> | <PermissionDenied> | <ResourceBusy> | <ResourceExists> | <ResourceUnavailable> | <ReadError> | <WriteError> | <FromStdErr> | <SecurityError>}] [-errorId <string>] [-targetObject <Object>] [-recommendedAction <string>] [-categoryActivity <string>] [-categoryReason <string>] [-categoryTargetName <string>] [-categoryTargetType <string>] [<CommonParameters>]
 
Write-Error [-message] <string> -exception <Exception> [-category {<NotSpecified> | <OpenError> | <CloseError> | <DeviceError> | <DeadlockDetected> | <InvalidArgument> | <InvalidData> | <InvalidOperation> | <InvalidResult> | <InvalidType> | <MetadataError> | <NotImplemented> | <NotInstalled> | <ObjectNotFound> | <OperationStopped> | <OperationTimeout> | <SyntaxError> | <ParserError> | <PermissionDenied> | <ResourceBusy> | <ResourceExists> | <ResourceUnavailable> | <ReadError> | <WriteError> | <FromStdErr> | <SecurityError>}] [-errorId <string>] [-targetObject <Object>] [-recommendedAction <string>] [-categoryActivity <string>] [-categoryReason <string>] [-categoryTargetName <string>] [-categoryTargetType <string>] [<CommonParameters>]
 
Write-Error -errorRecord <ErrorRecord> [-recommendedAction <string>] [-categoryActivity <string>] [-categoryReason <string>] [-categoryTargetName <string>] [-categoryTargetType <string>] [<CommonParameters>]
 
详细描述
输出一个对象到错误管道 (error pipeline). 使得你可以输出消息以及其他的信息 , : id, 对象数据 , 和遇到此信息后的建议办法 .
 
参数
 
-message <string>
指定该错误的文本信息 .
 
强制参数 ?
true
参数位置 ?
1
默认值
 
允许从管道绑定输入 ?  
true ( 传值 )
允许通配符扩展
false
 
-category <ErrorCategory>
指定错误的类别 .
 
如下列出了此参数可接受的值 :
 
·          NotSpecified
·          OpenError
·          CloseError
·          DeviceError
·          DeadlockDetected
·          InvalidArgument
·          InvalidData
·          InvalidOperation
·          InvalidResult
·          InvalidType
·          MetadataError
·          NotImplemented
·          NotInstalled
·          ObjectNotFound
·          OperationStopped
·          OperationTimeout
·          SyntaxError
·          ParserError
·          PermissionDenied
·          ResourceBusy
·          ResourceExists
·          ResourceUnavailable
·          ReadError
·          WriteError
·          FromStdErr
·          SecurityError
 
强制参数 ?
false
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-errorId <string>
指定一个与该错误关联的 ID. 每个错误应该对应一个独特的字符串 .
 
强制参数 ?
false
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-targetObject <Object>
指定错误所关联的对象 ( 译者注 : 一般是引起该错误的对象 ).
 
强制参数 ?
false
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-recommendedAction <string>
描述该错误的推荐解决办法 .
 
强制参数 ?
false
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-categoryActivity <string>
描述行为 , 该值将会覆盖 ErrorCategoryInfo 的默认值 .
 
强制参数 ?
false
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-categoryReason <string>
描述 ErrorCategoryInfo 的默认值为覆盖的原因 .
 
强制参数 ?
false
参数位置 ?
named
默认值
ErrorCategoryInfo 取得
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-categoryTargetName <string>
指定用来覆盖 ErrorCategoryInfo 默认值的目标名称 .
 
强制参数 ?
false
参数位置 ?
named
默认值
ErrorCategoryInfo 取得
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-categoryTargetType <string>
指定用来覆盖 ErrorCategoryInfo 默认值的目标类型 .
 
强制参数 ?
false
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-exception <Exception>
指定错误的异常类型 . 此参数可以用在 Message ErrorRecord 的位置 , 此时此参数应该是所有参数中的第一个 .
 
强制参数 ?
true
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
-errorRecord <ErrorRecord>
指定一个用于描述错误细节的错误记录 (error record). 此参数可以用在 Message Exception 的位置 , 此时此参数应该是所有参数中的第一个 .
 
强制参数 ?
true
参数位置 ?
named
默认值
 
允许从管道绑定输入 ?  
false
允许通配符扩展
false
 
< 公共参数 >
此命令支持公共参数 : -Verbose, -Debug, -ErrorAction, -ErrorVariable, and -OutVariable. 更多信息 , 输入 , "get-help about_commonparameters".
 
输入类型
任意
 
返回类型
错误对象
 
注意
 
更多信息 , 输入 "Get-Help Write-Error -detailed". 需要技术信息 , 输入 "Get-Help Write-Error -full".
 
如果需要为该命令提供多个参数 , 请使用逗号进行分隔 . 例如 , "<parameter-name> <value1>, <value2>".
 
1
 
C:/PS>get-childitem | foreach-object { if ($_.gettype().tostring() -eq "Microsoft.Win32.RegistryKey")
{write-error "Out-of-band object" -errorID B1 -targetobject $_ } else {$_ } }
 
如果 Get-ChildItem 返回一个 Microsoft.Win32.Registry 类型的对象 , 则输出一个对象到错误管道 , 当在注册表 provider 的名字空间中 , 执行此命令会引起该类型的对象被返回 .
 
相关链接
Write-Debug
Write-Verbose
Write-Output
Write-Host
Write-Progress
 
 
 
此命令较为晦涩 , 具体使用法方法有待调查 .
 
# 卸载模块 $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 if ($module) { $moduleDir = $module.ModuleBase Write-Host "正在卸载 CurlTools 模块..." -ForegroundColor Yellow Write-Host "模块位置: $moduleDir" # 检查是否以管理员权限运行(Windows) if ($env:OS -like "Windows*" -and -not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Warning "建议使用管理员权限运行卸载脚本" } # 确保卸载前移除模块 try { Remove-Module CurlTools -Force -ErrorAction Stop Write-Host "✅ 模块已从会话中移除" -ForegroundColor Green } catch { Write-Warning "无法从会话中移除模块: $_" } # 删除模块目录 try { Write-Host "正在删除模块文件..." Remove-Item -Path $moduleDir -Recurse -Force -ErrorAction Stop Write-Host "✅ 模块文件已删除" -ForegroundColor Green # 清理配置文件 $configDir = switch (Get-Platform) { "Linux" { Join-Path $HOME ".config" "curltools" } "macOS" { Join-Path $HOME "Library" "Application Support" "CurlTools" } default { Join-Path $env:APPDATA "CurlTools" } } if (Test-Path $configDir) { Remove-Item -Path $configDir -Recurse -Force Write-Host "✅ 配置文件已清理" -ForegroundColor Green } Write-Host "`n✅ 模块已成功卸载" -ForegroundColor Green exit 0 } catch { Write-Error "❌ 卸载失败: $_" Write-Host "请手动删除目录: $moduleDir" -ForegroundColor Red exit 1 } } else { Write-Warning "未找到 CurlTools 模块" exit 0 } 我按完回车 这里小蓝窗就闪退出去了!!(然后我再重新启动powershell,复制粘贴# ===== 安装后测试 ===== try { # 重新加载模块 Write-Host "`n重新加载模块..." -ForegroundColor Cyan Remove-Module CurlTools -ErrorAction SilentlyContinue -Force Import-Module $moduleDir -Force -ErrorAction Stop # 创建测试状态变量 $global:TestFailed = $false # 基本功能测试 $tests = @( { Write-Host "测试: Get-CurlPath" -ForegroundColor Cyan $path = Get-CurlPath if (-not $path) { throw "返回空路径" } if (-not (Test-Path $path)) { throw "路径不存在: $path" } Write-Host "✅ 成功 | 路径: $path" -ForegroundColor Green $path } { Write-Host "测试: Get-CurlVersion" -ForegroundColor Cyan $version = Get-CurlVersion if (-not $version) { throw "返回空版本" } if (-not $version.Version) { throw "版本号解析失败" } Write-Host "✅ 成功 | 版本: $($version.Version)" -ForegroundColor Green $version } { Write-Host "测试: Invoke-SecureDownload" -ForegroundColor Cyan $url = "https://www.example.com" $out = Join-Path $env:TEMP "test_$(Get-Date -Format 'yyyyMMddHHmmss').html" $result = Invoke-SecureDownload -Url $url -OutputPath $out if (-not (Test-Path $out)) { throw "文件未创建" } $fileSize = (Get-Item $out).Length if ($fileSize -eq 0) { throw "文件大小为0字节" } Write-Host "✅ 成功 | 文件大小: $fileSize bytes" -ForegroundColor Green $out } { Write-Host "测试: 卸载功能" -ForegroundColor Cyan $uninstallPath = Join-Path $moduleDir "Uninstall.ps1" if (-not (Test-Path $uninstallPath)) { throw "卸载脚本不存在" } # 测试卸载函数是否存在 $uninstallCmd = Get-Command Uninstall-CurlTools -ErrorAction SilentlyContinue if (-not $uninstallCmd) { throw "卸载命令未注册" } Write-Host "✅ 成功 | 卸载功能正常" -ForegroundColor Green $uninstallPath } ) foreach ($test in $tests) { try { $result = & $test if (-not $result) { Write-Warning "⚠️ 测试返回空结果: $($test.ToString())" } } catch { Write-Error "❌ 测试失败: $($test.ToString()) - $_" $global:TestFailed = $true } } if ($global:TestFailed) { Write-Error "❌ 模块安装完成,但部分测试失败" -ForegroundColor Red exit 1 } else { Write-Host "`n✅ 模块安装成功并通过所有测试" -ForegroundColor Green # 显示卸载说明 Write-Host "`n卸载说明:" -ForegroundColor Magenta Write-Host "1. 运行命令: Uninstall-CurlTools" -ForegroundColor Yellow Write-Host "2. 或执行脚本: . '$uninstallPath'" -ForegroundColor Yellow exit 0 } } catch { Write-Error "❌ 模块加载失败: $_" exit 1 } 然后回车 然后小蓝窗又闪退出去了)
08-13
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值