如何向RunspacePool的InitialSessionState中添加自定义类
在RunspacePool中通过InitialSessionState添加PowerShell类定义
你可以通过SessionStateScriptEntry将PowerShell类定义注入到RunspacePool的初始会话状态中,因为PowerShell类属于脚本级别的类型定义,无法像函数那样通过SessionStateFunctionEntry直接添加。以下是具体实现步骤:
实现代码
# 创建默认初始会话状态 $initialSessionState = [InitialSessionState]::CreateDefault() # 定义要注入的PowerShell类脚本 $classDefinition = @" class MyCustomClass { [string]$Name [int]$Age [string] GetInfo() { return "Name: `$(`$this.Name), Age: `$(`$this.Age)" } } "@ # 创建SessionStateScriptEntry对象,注入类定义脚本 $classScriptEntry = New-Object System.Management.Automation.Runspaces.SessionStateScriptEntry -ArgumentList $classDefinition $initialSessionState.Scripts.Add($classScriptEntry) # 保留你之前添加函数的逻辑(可选) $definition = Get-Content Function:\Icmp-Ping -ErrorAction Stop $functionEntry = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList 'Icmp-Ping', $definition $initialSessionState.Commands.Add($functionEntry) # 创建并使用RunspacePool $runspacePool = [RunspaceFactory]::CreateRunspacePool(1, 5, $initialSessionState, $Host) $runspacePool.Open() # 测试类是否可用 $powershell = [PowerShell]::Create().AddScript({ $obj = [MyCustomClass]::new() $obj.Name = "TestUser" $obj.Age = 30 $obj.GetInfo() }) $powershell.RunspacePool = $runspacePool $result = $powershell.Invoke() $result # 清理资源 $powershell.Dispose() $runspacePool.Close() $runspacePool.Dispose()
关键说明
- PowerShell类是在脚本执行上下文里定义的类型,不属于"命令"范畴,因此无法通过
InitialSessionState.Commands集合添加,必须通过Scripts集合注入定义脚本,让Runspace在初始化时执行这段脚本完成类的定义。 - 如果你要添加的是**.NET类**(而非PowerShell自定义类),可以通过
SessionStateAssemblyEntry将编译好的程序集添加到InitialSessionState.Assemblies集合中,或者在注入的脚本里使用Add-Type编译.NET类。
内容的提问来源于stack exchange,提问作者Dom
相关产品推荐
相关产品推荐

