【问题标题】:Cast to a C# object using remote PowerShell使用远程 PowerShell 转换为 C# 对象
【发布时间】:2014-09-18 13:21:04
【问题描述】:

我正在使用 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。解决这个问题的“通常”方法是什么?

【问题讨论】:

标签: c# powershell casting remoting wsman


【解决方案1】:

使用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.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    相关资源
    最近更新 更多