PS C:\Users\Administrator> # 加载必要程序集 - 确保使用正确的方法
PS C:\Users\Administrator> Add-Type -AssemblyName System.Net.Http -ErrorAction Stop
PS C:\Users\Administrator>
PS C:\Users\Administrator> function Invoke-EnhancedCurlRequest {
>> [CmdletBinding()]
>> param(
>> [Parameter(Mandatory=$true)]
>> [string]$Uri,
>> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')]
>> [string]$Method = 'GET',
>> [hashtable]$Headers = @{},
>> [object]$Body,
>> [int]$Timeout = 30,
>> [switch]$SkipCertificateCheck,
>> [switch]$UseGzipCompression
>> )
>>
>> $resultTemplate = [PSCustomObject]@{
>> StatusCode = 0
>> StatusMessage = "NotExecuted"
>> Headers = [ordered]@{}
>> Content = $null
>> IsSuccess = $false
>> Technology = "None"
>> ErrorMessage = $null
>> ElapsedMs = 0
>> }
>>
>> $timer = [System.Diagnostics.Stopwatch]::StartNew()
>> $result = $resultTemplate.PSObject.Copy()
>> $result.Technology = "HttpClient"
>>
>> try {
>> $handler = New-Object System.Net.Http.HttpClientHandler
>>
>> # 修复证书验证 - 兼容旧版 .NET
>> if ($SkipCertificateCheck) {
>> $handler.ServerCertificateCustomValidationCallback = {
>> param($sender, $cert, $chain, $sslPolicyErrors)
>> return $true
>> }
>> }
>>
>> if ($UseGzipCompression) {
>> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip
>> }
>>
>> $client = New-Object System.Net.Http.HttpClient($handler)
>> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout)
>>
>> $request = New-Object System.Net.Http.HttpRequestMessage(
>> [System.Net.Http.HttpMethod]::Parse($Method),
>> $Uri
>> )
>>
>> # 添加默认 User-Agent
>> if (-not $Headers.ContainsKey('User-Agent')) {
>> $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HTTPClient/1.0")
>> }
>>
>> # 添加自定义头
>> foreach ($key in $Headers.Keys) {
>> if (-not $request.Headers.TryAddWithoutValidation($key, $Headers[$key])) {
>> if (-not $request.Content) {
>> $request.Content = New-Object System.Net.Http.StringContent("")
>> }
>> $request.Content.Headers.TryAddWithoutValidation($key, $Headers[$key])
>> }
>> }
>>
>> # 处理请求体
>> if ($Body -and @('POST','PUT','PATCH') -contains $Method) {
>> if ($Body -is [byte[]]) {
>> $request.Content = New-Object System.Net.Http.ByteArrayContent($Body)
>> }
>> elseif ($Body -is [hashtable] -or $Body -is [System.Collections.IDictionary]) {
>> $jsonBody = $Body | ConvertTo-Json -Depth 5 -Compress
>> $request.Content = New-Object System.Net.Http.StringContent(
>> $jsonBody,
>> [System.Text.Encoding]::UTF8,
>> "application/json"
>> )
>> }
>> elseif ($Body -is [string]) {
>> $request.Content = New-Object System.Net.Http.StringContent(
>> $Body,
>> [System.Text.Encoding]::UTF8
>> )
>> }
>> else {
>> throw "Unsupported body type: $($Body.GetType().Name)"
>> }
>> }
>>
>> # 发送请求
>> $response = $client.SendAsync($request).GetAwaiter().GetResult()
>>
>> # 解析响应
>> $result.StatusCode = [int]$response.StatusCode
>> $result.StatusMessage = $response.ReasonPhrase
>> $result.IsSuccess = $response.IsSuccessStatusCode
>>
>> $result.Headers = [ordered]@{}
>> foreach ($header in $response.Headers) {
>> $result.Headers[$header.Key] = $header.Value -join ", "
>> }
>>
>> foreach ($header in $response.Content.Headers) {
>> $result.Headers[$header.Key] = $header.Value -join ", "
>> }
>>
>> $result.Content = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
>> return $result
>> }
>> catch [System.Threading.Tasks.TaskCanceledException] {
>> $result.ErrorMessage = "Request timed out after $Timeout seconds"
>> $result.StatusCode = 408
>> $result.StatusMessage = "Timeout"
>> return $result
>> }
>> catch {
>> # 提供更详细的错误信息
>> $result.ErrorMessage = $_.Exception.ToString()
>> $result.StatusCode = 500
>> $result.StatusMessage = "HttpRequestError"
>> return $result
>> }
>> finally {
>> $timer.Stop()
>> $result.ElapsedMs = $timer.ElapsedMilliseconds
>>
>> # 清理资源
>> if ($response) { $response.Dispose() }
>> if ($request) { $request.Dispose() }
>> if ($client) { $client.Dispose() }
>> if ($handler) { $handler.Dispose() }
>> }
>> }
>>
PS C:\Users\Administrator> $handler.ServerCertificateCustomValidationCallback = {
>> param($sender, $cert, $chain, $sslPolicyErrors)
>> return $true
>> }
>>
在此对象上找不到属性“ServerCertificateCustomValidationCallback”。请确认该属性存在并且可设置。
所在位置 行:1 字符: 1
+ $handler.ServerCertificateCustomValidationCallback = {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
PS C:\Users\Administrator> $handler.ServerCertificateCustomValidationCallback = {
>> param($sender, $cert, $chain, $sslPolicyErrors)
>> return $true
>> }
>>
在此对象上找不到属性“ServerCertificateCustomValidationCallback”。请确认该属性存在并且可设置。
所在位置 行:1 字符: 1
+ $handler.ServerCertificateCustomValidationCallback = {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
PS C:\Users\Administrator> $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HTTPClient/1.0")
不能对 Null 值表达式调用方法。
所在位置 行:1 字符: 1
+ $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HT ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\Users\Administrator> $result.ErrorMessage = $_.Exception.ToString()
不能对 Null 值表达式调用方法。
所在位置 行:1 字符: 1
+ $result.ErrorMessage = $_.Exception.ToString()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\Users\Administrator> if ($response) { $response.Dispose() }
PS C:\Users\Administrator> # 创建模块目录
PS C:\Users\Administrator> $moduleDir = "$env:ProgramFiles\WindowsPowerShell\Modules\PSHttpClient"
PS C:\Users\Administrator> New-Item -Path $moduleDir -ItemType Directory -Force | Out-Null
PS C:\Users\Administrator>
PS C:\Users\Administrator> # 生成并保存模块文件
PS C:\Users\Administrator> $fixedModuleCode = @'
>> <上面修复后的完整函数代码>
>> '@
>> $fixedModuleCode | Out-File "$moduleDir\PSHttpClient.psm1" -Encoding UTF8 -Force
>>
PS C:\Users\Administrator> # 重新加载模块
PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue
PS C:\Users\Administrator> Import-Module PSHttpClient -Force -PassThru
< : 无法将“<”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后
再试一次。
所在位置 C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\PSHttpClient.psm1:1 字符: 1
+ <上面修复后的完整函数代码>
+ ~
+ CategoryInfo : ObjectNotFound: (<:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.3 PSHttpClient
PS C:\Users\Administrator> # 测试基本GET请求
PS C:\Users\Administrator> $response = Invoke-EnhancedCurlRequest -Uri "https://httpbin.org/get" -Method GET
PS C:\Users\Administrator>
PS C:\Users\Administrator> if ($response.IsSuccess) {
>> Write-Host "✅ 模块工作正常" -ForegroundColor Green
>> $response.Content | ConvertFrom-Json
>> } else {
>> Write-Host "❌ 模块存在问题: $($response.ErrorMessage)" -ForegroundColor Red
>> }
>>
❌ 模块存在问题: System.Management.Automation.RuntimeException: 方法调用失败,因为 [System.Net.Http.HttpMethod] 不包含名为“Parse”的方法。
在 System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
在 System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
在 System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
在 System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
PS C:\Users\Administrator> ✅ 模块工作正常
✅ : 无法将“✅”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后
再试一次。
所在位置 行:1 字符: 1
+ ✅ 模块工作正常
+ ~
+ CategoryInfo : ObjectNotFound: (✅:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Administrator>
PS C:\Users\Administrator> args : {}
args : 无法将“args”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确
,然后再试一次。
所在位置 行:1 字符: 1
+ args : {}
+ ~~~~
+ CategoryInfo : ObjectNotFound: (args:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Administrator> headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpbin.org; User-Agent=PowerShell-HTTPClient/1.0;
所在位置 行:1 字符: 31
+ headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpb ...
+ ~
哈希文本中的键后面缺少“=”运算符。
所在位置 行:1 字符: 31
+ headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpb ...
+ ~
哈希文本不完整。
所在位置 行:1 字符: 25
+ headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpb ...
+ ~~~~~~
哈希文本中不允许包含重复的键“Accept”。
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEqualsInHashLiteral
PS C:\Users\Administrator> X-Amzn-Trace-Id=Root=1-66c8f1b5-1234567890abcdef12345678}
所在位置 行:1 字符: 67
+ X-Amzn-Trace-Id=Root=1-66c8f1b5-1234567890abcdef12345678}
+ ~
表达式或语句中包含意外的标记“}”。
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
PS C:\Users\Administrator> url : https://httpbin.org/get
url : 无法将“url”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,
然后再试一次。
所在位置 行:1 字符: 1
+ url : https://httpbin.org/get
+ ~~~
+ CategoryInfo : ObjectNotFound: (url:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Administrator> # 重新加载模块
PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue
PS C:\Users\Administrator> Import-Module PSHttpClient -Force
< : 无法将“<”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后
再试一次。
所在位置 C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\PSHttpClient.psm1:1 字符: 1
+ <上面修复后的完整函数代码>
+ ~
+ CategoryInfo : ObjectNotFound: (<:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Administrator>
PS C:\Users\Administrator> # 测试用例
PS C:\Users\Administrator> $testCases = @(
>> @{Url = "https://httpbin.org/get"; Method = "GET"; ExpectedCode = 200}
>> @{Url = "https://httpbin.org/post"; Method = "POST"; Body = @{name="Test"}; ExpectedCode = 200}
>> @{Url = "https://self-signed.badssl.com/"; Method = "GET"; SkipCertificateCheck = $true; ExpectedCode = 200}
>> @{Url = "https://invalid.domain.abc/"; Method = "GET"; ExpectedCode = 0}
>> )
>>
PS C:\Users\Administrator> # 执行测试
PS C:\Users\Administrator> $results = foreach ($test in $testCases) {
>> $params = @{
>> Uri = $test.Url
>> Method = $test.Method
>> }
>>
>> if ($test.Body) { $params['Body'] = $test.Body }
>> if ($test.SkipCertificateCheck) { $params['SkipCertificateCheck'] = $true }
>>
>> $result = Invoke-EnhancedCurlRequest @params
>>
>> [PSCustomObject]@{
>> TestCase = $test.Url
>> Method = $test.Method
>> Status = if ($result.StatusCode -eq $test.ExpectedCode) { "✅ PASS" } else { "❌ FAIL" }
>> StatusCode = $result.StatusCode
>> Expected = $test.ExpectedCode
>> Success = $result.IsSuccess
>> Tech = $result.Technology
>> Error = if ($result.ErrorMessage) { $result.ErrorMessage } else { "None" }
>> Time = Get-Date -Format "HH:mm:ss"
>> }
>> }
>>
方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。
所在位置 行:114 字符: 26
+ if ($response) { $response.Dispose() }
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。
所在位置 行:114 字符: 26
+ if ($response) { $response.Dispose() }
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。
所在位置 行:114 字符: 26
+ if ($response) { $response.Dispose() }
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。
所在位置 行:114 字符: 26
+ if ($response) { $response.Dispose() }
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
PS C:\Users\Administrator> # 显示结果
PS C:\Users\Administrator> $results | Format-Table -AutoSize
TestCase Method Status StatusCode Expected Success Tech Error
-------- ------ ------ ---------- -------- ------- ---- -----
https://httpbin.org/get GET ❌ FAIL 500 200 False HttpClient System.Management.Automation.Ru...
https://httpbin.org/post POST ❌ FAIL 500 200 False HttpClient System.Management.Automation.Ru...
https://self-signed.badssl.com/ GET ❌ FAIL 500 200 False HttpClient System.Management.Automation.Ru...
https://invalid.domain.abc/ GET ❌ FAIL 500 0 False HttpClient System.Management.Automation.Ru...
PS C:\Users\Administrator>
最新发布