0

I'm trying to get some data from Azure Active Directory using C# code with reference to System.Management.Automation. I've got no errors with code execution, just null results and no output to textfile. Does anyone have this problem before or maybe I missed something? Thank you!

public void RunScriptTest()
        {
            string username = "Username";
            string password = "Password";
            List<String> listResults = new List<String>();
            PowerShell powershell = PowerShell.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            powershell.Runspace = runspace;
            powershell.AddScript("Install-Module -Name AzureAD -Force; \n");
            powershell.AddScript("Import-Module -Name AzureAD -Verbose \n");
            powershell.AddScript("$username = \"" + username + "\"; \n" +
                "$password = convertTo-securestring '" + password + "' -AsPlainText -Force; \n" +
                "$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password; \n" +
                "Connect-AzureAD - Credential $cred; \n");
            powershell.AddScript("Get-AzureADUser | Out-File -FilePath " + @"C:\TestResults\1.txt");
            Collection<PSObject> results = powershell.Invoke();
            runspace.Close();

            StringBuilder stringBuilder = new StringBuilder();
            foreach(PSObject obj in results)
            {
                listresults.Add(obj.ToString());

            }

        } 
  • you are using Out-File.. it is supposed to give you any output anyway... Also, what user are you looking up ? – Jawad Dec 11 '19 at 21:56
  • It doesn't create a new file with output, but when I execute these powershell commands in terminal, it works fine. Actually I want to get all users from Azure AD, I just want to compare with local Active Directory – user12521082 Dec 11 '19 at 23:00
  • Have you tried to use a debugger and see if there is anything in the output? Any errors or exceptions – Jawad Dec 11 '19 at 23:06
  • There is no obvious errors, I just opened an additional output and got next: System.Management.Automation.PSDataCollection`1[System.Management.Automation.ErrorRecord] – user12521082 Dec 12 '19 at 00:56

1 Answers1

0
  • Sequencing .AddScript() calls without intervening .AddStatement() calls makes only the last .AddScript() call effective - all previous calls are ignored.

  • In order to examine errors that may have occurred during execution via .Invoke(), you must access the powershell.Streams.Error stream.

Therefore, the immediate fix is to replace your powershell.AddScript(...) calls with $powershell.AddStatement().AddScript(...)

Note that your PowerShellCode appears designed not to produce any output, so there's no point in trying to populate listresults.

mklement0
  • 382,024
  • 64
  • 607
  • 775