用PowerShell探索System.RuntimeType类型

本文通过PowerShell展示了如何深入探索.NET Framework中System.RuntimeType类的内部细节,并利用这些信息揭示了System.String类的构造函数。

PowerShell绝对是学习.Net Framework的好工具, 这句话是PowerShell团队中某人说的, 实际确实如此, 我们可以通过Get-Member来窥探.Net中很多神秘的元素. 要学习.Net Framework, 我想很多人会拜读Jeffrey Richter所编写的<<Applied Microsoft .NET Framework Programming>>一书.

.Net Framework中的类在加载到应用域(Application Domain)时, 转化为System.RuntimeType的一个实例, System.RuntimeType是一个非公开的类, 你无法在MSDN上找到详细信息, PowerShell提供了简单途径来窥探System.RuntimeType中的成员. 在Jeffrey Richter书中也介绍过System.RuntimeType的内容, 我们下面以System.String为例, 用PowerShell进行详细介绍:

PS C:/> [System.String].GetType().FullName
System.RuntimeType

我们看到了神秘System.RuntimeType类的实例, 我们可以用Get-Member看看这个类上都有哪些成员:

PS C:/> [System.String] | Get-Member | Sort-Object MemberType, Name
   TypeName: System.RuntimeType

Name                           MemberType Definition
----                           ---------- ----------
Assembly                       Property   System.Reflection.Assembly Assembly {get;}
AssemblyQualifiedName          Property   System.String AssemblyQualifiedName {get;}
Attributes                     Property   System.Reflection.TypeAttributes Attributes {get;}
BaseType                       Property   System.Type BaseType {get;}
ContainsGenericParameters      Property   System.Boolean ContainsGenericParameters {get;}
DeclaringMethod                Property   System.Reflection.MethodBase DeclaringMethod {get;}
DeclaringType                  Property   System.Type DeclaringType {get;}
FullName                       Property   System.String FullName {get;}
GenericParameterAttributes     Property   System.Reflection.GenericParameterAttributes GenericParameterAttributes {g...
GenericParameterPosition       Property   System.Int32 GenericParameterPosition {get;}
GUID                           Property   System.Guid GUID {get;}
HasElementType                 Property   System.Boolean HasElementType {get;}
IsAbstract                     Property   System.Boolean IsAbstract {get;}
IsAnsiClass                    Property   System.Boolean IsAnsiClass {get;}
IsArray                        Property   System.Boolean IsArray {get;}
IsAutoClass                    Property   System.Boolean IsAutoClass {get;}
IsAutoLayout                   Property   System.Boolean IsAutoLayout {get;}
IsByRef                        Property   System.Boolean IsByRef {get;}
IsClass                        Property   System.Boolean IsClass {get;}
IsCOMObject                    Property   System.Boolean IsCOMObject {get;}
IsContextful                   Property   System.Boolean IsContextful {get;}
IsEnum                         Property   System.Boolean IsEnum {get;}
IsExplicitLayout               Property   System.Boolean IsExplicitLayout {get;}
IsGenericParameter             Property   System.Boolean IsGenericParameter {get;}
IsGenericType                  Property   System.Boolean IsGenericType {get;}
IsGenericTypeDefinition        Property   System.Boolean IsGenericTypeDefinition {get;}
IsImport                       Property   System.Boolean IsImport {get;}
IsInterface                    Property   System.Boolean IsInterface {get;}
IsLayoutSequential             Property   System.Boolean IsLayoutSequential {get;}
IsMarshalByRef                 Property   System.Boolean IsMarshalByRef {get;}
IsNested                       Property   System.Boolean IsNested {get;}
IsNestedAssembly               Property   System.Boolean IsNestedAssembly {get;}
IsNestedFamANDAssem            Property   System.Boolean IsNestedFamANDAssem {get;}
IsNestedFamily                 Property   System.Boolean IsNestedFamily {get;}
IsNestedFamORAssem             Property   System.Boolean IsNestedFamORAssem {get;}
IsNestedPrivate                Property   System.Boolean IsNestedPrivate {get;}
IsNestedPublic                 Property   System.Boolean IsNestedPublic {get;}
IsNotPublic                    Property   System.Boolean IsNotPublic {get;}
IsPointer                      Property   System.Boolean IsPointer {get;}
IsPrimitive                    Property   System.Boolean IsPrimitive {get;}
IsPublic                       Property   System.Boolean IsPublic {get;}
IsSealed                       Property   System.Boolean IsSealed {get;}
IsSerializable                 Property   System.Boolean IsSerializable {get;}
IsSpecialName                  Property   System.Boolean IsSpecialName {get;}
IsUnicodeClass                 Property   System.Boolean IsUnicodeClass {get;}
IsValueType                    Property   System.Boolean IsValueType {get;}
IsVisible                      Property   System.Boolean IsVisible {get;}
MemberType                     Property   System.Reflection.MemberTypes MemberType {get;}
MetadataToken                  Property   System.Int32 MetadataToken {get;}
Module                         Property   System.Reflection.Module Module {get;}
Name                           Property   System.String Name {get;}
Namespace                      Property   System.String Namespace {get;}
ReflectedType                  Property   System.Type ReflectedType {get;}
StructLayoutAttribute          Property   System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute...
TypeHandle                     Property   System.RuntimeTypeHandle TypeHandle {get;}
TypeInitializer                Property   System.Reflection.ConstructorInfo TypeInitializer {get;}
UnderlyingSystemType           Property   System.Type UnderlyingSystemType {get;}
Clone                          Method     System.Object Clone()
Equals                         Method     System.Boolean Equals(Object obj), System.Boolean Equals(Type o)
FindInterfaces                 Method     System.Type[] FindInterfaces(TypeFilter filter, Object filterCriteria)
FindMembers                    Method     System.Reflection.MemberInfo[] FindMembers(MemberTypes memberType, Binding...
GetArrayRank                   Method     System.Int32 GetArrayRank()
GetConstructor                 Method     System.Reflection.ConstructorInfo GetConstructor(BindingFlags bindingAttr,...
GetConstructors                Method     System.Reflection.ConstructorInfo[] GetConstructors(BindingFlags bindingAt...
GetCustomAttributes            Method     System.Object[] GetCustomAttributes(Boolean inherit), System.Object[] GetC...
GetDefaultMembers              Method     System.Reflection.MemberInfo[] GetDefaultMembers()
GetElementType                 Method     System.Type GetElementType()
GetEvent                       Method     System.Reflection.EventInfo GetEvent(String name, BindingFlags bindingAttr...
GetEvents                      Method     System.Reflection.EventInfo[] GetEvents(BindingFlags bindingAttr), System....
GetField                       Method     System.Reflection.FieldInfo GetField(String name, BindingFlags bindingAttr...
GetFields                      Method     System.Reflection.FieldInfo[] GetFields(BindingFlags bindingAttr), System....
GetGenericArguments            Method     System.Type[] GetGenericArguments()
GetGenericParameterConstraints Method     System.Type[] GetGenericParameterConstraints()
GetGenericTypeDefinition       Method     System.Type GetGenericTypeDefinition()
GetHashCode                    Method     System.Int32 GetHashCode()
GetInterface                   Method     System.Type GetInterface(String fullname, Boolean ignoreCase), System.Type...
GetInterfaceMap                Method     System.Reflection.InterfaceMapping GetInterfaceMap(Type ifaceType)
GetInterfaces                  Method     System.Type[] GetInterfaces()
GetMember                      Method     System.Reflection.MemberInfo[] GetMember(String name, MemberTypes type, Bi...
GetMembers                     Method     System.Reflection.MemberInfo[] GetMembers(BindingFlags bindingAttr), Syste...
GetMethod                      Method     System.Reflection.MethodInfo GetMethod(String name, BindingFlags bindingAt...
GetMethods                     Method     System.Reflection.MethodInfo[] GetMethods(BindingFlags bindingAttr), Syste...
GetNestedType                  Method     System.Type GetNestedType(String fullname, BindingFlags bindingAttr), Syst...
GetNestedTypes                 Method     System.Type[] GetNestedTypes(BindingFlags bindingAttr), System.Type[] GetN...
GetObjectData                  Method     System.Void GetObjectData(SerializationInfo info, StreamingContext context)
GetProperties                  Method     System.Reflection.PropertyInfo[] GetProperties(BindingFlags bindingAttr), ...
GetProperty                    Method     System.Reflection.PropertyInfo GetProperty(String name, BindingFlags bindi...
GetType                        Method     System.Type GetType(), System.Type GetType()
InvokeMember                   Method     System.Object InvokeMember(String name, BindingFlags bindingFlags, Binder ...
IsAssignableFrom               Method     System.Boolean IsAssignableFrom(Type c)
IsDefined                      Method     System.Boolean IsDefined(Type attributeType, Boolean inherit)
IsInstanceOfType               Method     System.Boolean IsInstanceOfType(Object o)
IsSubclassOf                   Method     System.Boolean IsSubclassOf(Type type)
MakeArrayType                  Method     System.Type MakeArrayType(), System.Type MakeArrayType(Int32 rank)
MakeByRefType                  Method     System.Type MakeByRefType()
MakeGenericType                Method     System.Type MakeGenericType(Type[] instantiation)
MakePointerType                Method     System.Type MakePointerType()
ToString                       Method     System.String ToString()

我们可以通过System.RuntimeType上的GetContructors方法知道System.String上的构造函数:

PS C:/> [System.String].GetConstructors() | %{ $_.ToString() }
Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, System.Text.Encoding)
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char[])
Void .ctor(Char, Int32)

下面是MSDN上关于System.String类构造器的定义:

  NameDescription
String(Char*)Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.
String(array<Char>[]()[])Initializes a new instance of the String class to the value indicated by an array of Unicode characters.
String(SByte*)Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.
String(Char, Int32)Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.
String(Char*, Int32, Int32)Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.
String(array<Char>[]()[], Int32, Int32)Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.
String(SByte*, Int32, Int32)Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting character position within that array, and a length.
String(SByte*, Int32, Int32, Encoding)Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting character position within that array, a length, and an Encoding object.

是不是很方便呢??

点击vs扩展功能时出现这样的提示是怎么回事构造此帧的内容时遇到了异常。 此信息也记录在“C:\Users\baiyi\AppData\Roaming\Microsoft\VisualStudio\17.0_8ba2cb44\ActivityLog.xml”中。 异常详细信息: System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> System.Runtime.InteropServices.COMException: 找不到元素。 (异常来自 HRESULT:0x80070490) 在 Microsoft.VisualStudio.Setup.Configuration.ISetupConfiguration2.GetInstanceForCurrentProcess() 在 Microsoft.VisualStudio.ExtensionManager.Utilities.GetCurrentVsInstance() 在 System.Lazy`1.CreateValue() 在 System.Lazy`1.LazyInitValue() 在 Microsoft.VisualStudio.ExtensionManager.UI.InstalledExtensionViewModel..ctor(IInstalledExtension extension, Boolean canToggleEnabled, String reasonCannotEnable, CancellationToken cancellationToken) 在 Microsoft.VisualStudio.ExtensionManager.UI.ExtensionProviderUtilities.<>c__DisplayClass0_0.<InitializeInstalledExtensions>b__1(IInstalledExtension extension) 在 System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() 在 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) 在 System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) 在 Microsoft.VisualStudio.ExtensionManager.UI.ExtensionProviderUtilities.InitializeInstalledExtensions(ExtensionManagerService extensionManagerService, CancellationToken cancellationToken, IReadOnlyList`1 commandSet) 在 Microsoft.VisualStudio.ExtensionManager.UI.InstalledExtensionsProvider.SynchronousRefreshWork() 在 Microsoft.VisualStudio.ExtensionManager.UI.TaskSynchronizationHelper.ScheduleWorkAsync(CancellationToken cancellationToken) 在 Microsoft.VisualStudio.ExtensionManager.UI.InstalledExtensionsProvider.RefreshExtensionList() 在 Microsoft.VisualStudio.ExtensionManager.UI.InstalledExtensionsProvider..ctor(ExtensionProviderArguments args, List`1 commandSet) 在 Microsoft.VisualStudio.ExtensionManager.UI.ExtensionManagerDataContext..ctor(ExtensionManagerToolWindowCreationContext context, StatusReportingManager statusReportingManager, Action OnClearExtensions) 在 Microsoft.VisualStudio.ExtensionManager.UI.ExtensionManagerToolWindowControl..ctor(ExtensionManagerToolWindowCreationContext context, StatusReportingManager statusReportingManager) 在 Microsoft.VisualStudio.ExtensionManager.UI.ExtensionManagerToolWindow..ctor(ExtensionManagerToolWindowCreationContext context) --- 内部异常堆栈跟踪的结尾 --- 在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) 在 System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 在 System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) 在 System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) 在 System.Activator.CreateInstance(Type type, Object[] args) 在 Microsoft.VisualStudio.Shell.Package.InstantiateToolWindow(Type toolWindowType, Object context) 在 Microsoft.VisualStudio.Shell.Package.<>c__DisplayClass74_0.<CreateToolWindow>g__CreateToolWindowWorker|1() 在 Microsoft.VisualStudio.Shell.Package.CreateToolWindow(Type toolWindowType, Int32 id, UInt32 flags, Object context, Guid persistenceGuid) 在 Microsoft.VisualStudio.Shell.Package.CreateToolWindow(Type toolWindowType, Int32 id, Object context) 在 Microsoft.VisualStudio.Shell.AsyncPackage.<CompleteToolWindowCreationAsync>d__24.MoveNext()
10-26
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" >> >> $handler = $null >> $client = $null >> $request = $null >> $response = $null >> >> try { >> # 创建 HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> >> # 修复证书验证 - 兼容所有 .NET 版本 >> if ($SkipCertificateCheck) { >> # 方法1: 使用反射设置回调(兼容旧版 .NET) >> $handlerType = $handler.GetType() >> $prop = $handlerType.GetProperty("ServerCertificateCustomValidationCallback") >> >> if ($null -ne $prop) { >> $callback = { >> param($sender, $cert, $chain, $sslPolicyErrors) >> return $true >> } >> $prop.SetValue($handler, $callback) >> } >> # 方法2: 使用全局设置(备用方案) >> else { >> $originalCallback = [System.Net.ServicePointManager]::ServerCertificateValidationCallback >> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { >> param($sender, $cert, $chain, $sslPolicyErrors) >> return $true >> } >> } >> } >> >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> >> # 创建 HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> >> # 创建请求方法对象 >> $httpMethod = [System.Net.Http.HttpMethod]::new($Method) >> if (-not $httpMethod) { >> $httpMethod = New-Object System.Net.Http.HttpMethod($Method) >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage($httpMethod, $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 [System.Net.Http.HttpRequestException] { >> # 处理特定HTTP请求异常 >> $ex = $_.Exception >> $result.ErrorMessage = $ex.ToString() >> >> if ($ex.InnerException -is [System.Net.Sockets.SocketException]) { >> $result.StatusCode = 0 >> $result.StatusMessage = "DNSResolutionFailed" >> } >> else { >> $result.StatusCode = 500 >> $result.StatusMessage = "HttpRequestError" >> } >> >> return $result >> } >> catch { >> # 通用错误处理 >> $result.ErrorMessage = $_.Exception.ToString() >> $result.StatusCode = 500 >> $result.StatusMessage = "InternalError" >> return $result >> } >> finally { >> $timer.Stop() >> $result.ElapsedMs = $timer.ElapsedMilliseconds >> >> # 安全清理资源 >> if ($response -is [IDisposable]) { $response.Dispose() } >> if ($request -is [IDisposable]) { $request.Dispose() } >> if ($client -is [IDisposable]) { $client.Dispose() } >> if ($handler -is [IDisposable]) { $handler.Dispose() } >> >> # 恢复全局证书验证设置 >> if ($SkipCertificateCheck -and $null -ne $originalCallback) { >> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $originalCallback >> } >> } >> } >> PS C:\Users\Administrator> # 使用反射设置回调(兼容旧版 .NET) PS C:\Users\Administrator> $handlerType = $handler.GetType() 不能对 Null 值表达式调用方法。 所在位置 行:1 字符: 1 + $handlerType = $handler.GetType() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull PS C:\Users\Administrator> $prop = $handlerType.GetProperty("ServerCertificateCustomValidationCallback") 不能对 Null 值表达式调用方法。 所在位置 行:1 字符: 1 + $prop = $handlerType.GetProperty("ServerCertificateCustomValidationCa ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull PS C:\Users\Administrator> if ($null -ne $prop) { >> $callback = { param($sender, $cert, $chain, $sslPolicyErrors) return $true } >> $prop.SetValue($handler, $callback) >> } >> # 备用方案:全局设置 >> else { >> $originalCallback = [System.Net.ServicePointManager]::ServerCertificateValidationCallback >> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { >> param($sender, $cert, $chain, $sslPolicyErrors) return $true >> } >> } >> PS C:\Users\Administrator> catch [System.Net.Http.HttpRequestException] { >> $ex = $_.Exception >> if ($ex.InnerException -is [System.Net.Sockets.SocketException]) { >> $result.StatusCode = 0 >> $result.StatusMessage = "DNSResolutionFailed" >> } >> } >> catch : 无法将“catch”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正 确,然后再试一次。 所在位置 行:1 字符: 1 + catch [System.Net.Http.HttpRequestException] { + ~~~~~ + CategoryInfo : ObjectNotFound: (catch:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> finally { >> # 恢复全局证书验证设置 >> if ($SkipCertificateCheck -and $null -ne $originalCallback) { >> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $originalCallback >> } >> } >> finally : 无法将“finally”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路 径正确,然后再试一次。 所在位置 行:1 字符: 1 + finally { + ~~~~~~~ + CategoryInfo : ObjectNotFound: (finally:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 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 = @' >> # 将上面修复后的完整函数代码复制到这里 >> '@ >> PS C:\Users\Administrator> $fixedModuleCode | Out-File "$moduleDir\PSHttpClient.psm1" -Encoding UTF8 -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 重新加载模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module PSHttpClient -Force -PassThru ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 1.3 PSHttpClient PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试自签名证书网站 PS C:\Users\Administrator> $result = Invoke-EnhancedCurlRequest -Uri "https://self-signed.badssl.com/" -SkipCertificateCheck PS C:\Users\Administrator> PS C:\Users\Administrator> if ($result.IsSuccess) { >> Write-Host "✅ 自签名证书网站访问成功" -ForegroundColor Green >> } else { >> Write-Host "❌ 自签名证书网站访问失败: $($result.ErrorMessage)" -ForegroundColor Red >> } >> ❌ 自签名证书网站访问失败: System.Management.Automation.MethodInvocationException: 使用“2”个参数调用“SetValue”时发生异常:“类型System.Management.Automation.ScriptBlock”的对象无法转换为类型System.Func`5[System.Net.Http.HttpRequestMessage,System.Security.Cryptography.X509Certificates.X509Certificate2,System.Security.Cryptography.X509Certificates.X509Chain,System.Net.Security.SslPolicyErrors,System.Boolean]”。” ---> System.ArgumentException: 类型System.Management.Automation.ScriptBlock”的对象无法转换为类型System.Func`5[System.Net.Http.HttpRequestMessage,System.Security.Cryptography.X509Certificates.X509Certificate2,System.Security.Cryptography.X509Certificates.X509Chain,System.Net.Security.SslPolicyErrors,System.Boolean]”。 在 System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast) 在 System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) 在 System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 在 System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index) 在 CallSite.Target(Closure , CallSite , Object , Object , Object ) --- 内部异常堆栈跟踪的结尾 --- 在 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> # 测试无效域名 PS C:\Users\Administrator> $result = Invoke-EnhancedCurlRequest -Uri "https://invalid.domain.abc/" PS C:\Users\Administrator> PS C:\Users\Administrator> if ($result.StatusCode -eq 0) { >> Write-Host "✅ DNS错误处理成功" -ForegroundColor Green >> } else { >> Write-Host "❌ DNS错误处理失败: $($result.StatusCode)" -ForegroundColor Red >> } >> ❌ DNS错误处理失败: 500 PS C:\Users\Administrator>
08-17
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值