Home > front end >  C# Powershell API msol behavior
C# Powershell API msol behavior

Time:09-16

If I run the first below code, the expected outcome occurs, results has the expected object in it. If the second example is run, results will be null and not contain any results. Is the latter set up in the correct manner, or am I missing some detail?

Works as expected

using (PowerShell ps = PowerShell.Create())
{
    ps.AddScript("connect-msolservice; Get-MsolCompanyInformation");
    Collection<PSObject> results = ps.Invoke();
    foreach (PSObject result in results)
    {
        label.Content = "Last AD Sync: "   result.Properties["LastDirSyncTime"].Value;
    }
}

Microsoft recommends chaining commands in the below example, however, results will not contain any data.

using (PowerShell ps = PowerShell.Create())
{
    ps.AddCommand("connect-msolservice");
    ps.AddCommand("Get-MsolCompanyInformation");
    Collection<PSObject> results = ps.Invoke();
    foreach (PSObject result in results)
    {
        label.Content = "Last AD Sync: "   result.Properties["LastDirSyncTime"].Value;
    }
}

CodePudding user response:

The only part missing from the second example is statement termination between the two commands - equivalent to the ; in the script:

ps.AddCommand("connect-msolservice")
  .AddStatement() // this is our `;`
  .AddCommand("Get-MsolCompanyInformation");
  • Related