使用远程PowerShell强制转换为C#对象
本文关键字:转换 对象 PowerShell | 更新日期: 2023-09-27 18:22:17
我正在使用C#远程连接到PowerShell控制台:
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(setUpConnection()))
{
remoteRunspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = remoteRunspace;
DateTime dateTime = GetTime(powershell); // <------ How to implement?
}
remoteRunspace.Close();
}
我想调用Get-Date PowerShell命令,并以某种方式将PSObject
强制转换为DateTime
。解决这个问题的"常用"方法是什么?
使用PSObject.BaseObject属性:
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(setUpConnection()))
{
remoteRunspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = remoteRunspace;
DateTime dateTime = (DateTime)powershell.Invoke().Single().BaseObject;
}
// No need to close runspace; you are disposing it.
}