0

I am connecting remotely to a PowerShell console using 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();
}

I want to call the Get-Date PowerShell command and somehow cast PSObject to DateTime. What is "the usual" way to solve this problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Egor Okhterov
  • 478
  • 2
  • 9
  • 34
  • http://msdn.microsoft.com/en-us/library/system.management.automation.powershell%28v=vs.85%29.aspx – Jesse Sep 18 '14 at 13:36

1 Answers1

1

Use the PSObject.BaseObject property:

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.
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RX_DID_RX
  • 4,113
  • 4
  • 17
  • 27