[英]Cast to a C# object using remote PowerShell
I am connecting remotely to a PowerShell console using C#: 我正在使用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();
}
I want to call the Get-Date PowerShell command and somehow cast PSObject
to DateTime
. 我想调用Get-Date PowerShell命令,并以某种方式将
PSObject
为DateTime
。 What is "the usual" way to solve this problem? 解决此问题的“通常”方法是什么?
Use the PSObject.BaseObject property: 使用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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.