我们在使用 C# 脚本通过 Powershell 配置连接代理时遇到问题。
当我们导入模块remotedesktopservices
时,因为之前安装并使用了会话主机角色,所以安装连接代理角色,我们必须重新启动我们的脚本才能获得正确的输出。
如果我们直接使用 Powershell,我们可以重现该行为。
这些是我们调用的命令:
PS C:\Windows\system32> import-module servermanager
PS C:\Windows\system32> import-module remotedesktopservices
PS C:\Windows\system32> add-windowsfeature rds-connection-broker
Success Restart Needed Exit Code Feature Result
------- -------------- --------- --------------
True No Success {Remotedesktop-ConnectionBroker}
PS C:\Windows\system32> ls rds:
Directory: RDS:
Name Type CurrentValue GP PermissibleValues PermissibleOperations
---- ---- ------------ -- ----------------- ---------------------
RDSConfiguration Container - Get-Item, Get-ChildItem
RemoteApp Container - Get-Item, Get-ChildItem
PS C:\Windows\system32> import-module -force remotedesktopservices
PS C:\Windows\system32> ls rds:
Directory: RDS:
Name Type CurrentValue GP PermissibleValues PermissibleOperations
---- ---- ------------ -- ----------------- ---------------------
RDSConfiguration Container - Get-Item, Get-ChildItem
RemoteApp Container - Get-Item, Get-ChildItem
重新启动 Powershell 或我们的程序后,结果(正确)如下所示:
PS C:\Windows\system32> ls rds:
Directory: RDS:
Name Type CurrentValue GP PermissibleValues PermissibleOperations
---- ---- ------------ -- ----------------- ---------------------
RDSConfiguration Container - Get-Item, Get-ChildItem
RDSFarms Container - Get-Item, Get-ChildItem
RemoteApp Container - Get-Item, Get-ChildItem
ConnectionBroker Container - Get-Item, Get-ChildItem
我们需要这个输出而不需要重新启动我们的程序。是否有可能在 C# 中获得全新的 Powershell?“删除模块”和“导入模块”没有帮助。
这是我们获取 Powershell 运行空间的 C# 代码:
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ThrowOnRunspaceOpenError = true;
iss.ImportPSModule(initialRoles);
RemoteHost.powerShellRunspace = RunspaceFactory.CreateRunspace(iss);
RemoteHost.powerShellRunspace.Open();
即使我们以相同的方式创建一个新的 powershell 运行空间,似乎旧的 Powershell 已加载