Приведение к объекту C# с использованием удаленного PowerShell

Я подключаюсь удаленно к консоли PowerShell с помощью C#:

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, Каков "обычный" способ решения этой проблемы?

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.
}
Другие вопросы по тегам