collection filling with nulls on second run

Gazza t 1 Reputation point
2023-03-24T11:16:11.6466667+00:00

I have the following method that runs a powershell command to get the ad user list and fill a collection

<

private void fillADUsers()
        {
            
            AdUsers = new Collection<PSObject>();
            AdUsers = PSCommandToRun("Get-ADUser -filter * -properties LastLogon, whenCreated, Enabled, LockedOut");
        }

After running this it fills a listview with the details. This works fine on the first run but when i run it again the LastLogon and whenCreated are giving me a null reference exception

why would the second run of the method give me nulls when it gives me the correct details the first time and how can i avoid this?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,121 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,683 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Osjaetor 480 Reputation points
    2023-06-05T20:03:54.1866667+00:00

    Hi ,

    The best thing to do in these cases is to clear the PowerShell session state before running the command, this way we make sure we always get the latest information from Active Directory. Here are some changes to your script for you to try and see if it solves your problem:

    private void fillADUsers()
    {
        AdUsers = new Collection<PSObject>();
        
        using (PowerShell powershell = PowerShell.Create())
        {
            powershell.AddScript("Clear-Variable -Scope Global");
            powershell.AddScript("Clear-Variable -Scope Local");
            powershell.AddScript("Clear-Variable -Scope Script");
            
            powershell.AddScript("Get-ADUser -Filter * -Properties LastLogon, whenCreated, Enabled, LockedOut");
            
            try
            {
                AdUsers = powershell.Invoke();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
        }
    }
    

    Regards,

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.