Run powershell in C#

jwradhe

New member
Joined
Sep 23, 2021
Messages
2
Programming Experience
Beginner
Hi!
I am pretty new to this, but im trying to present when the latest winupdate was done on computer, and only found in powershell to present that, and i tried to run it in C#, but no error and no result.
I understand that im doing wrong, but what is the best way to do this?

C#:
// Get Latest Windows Update
        private void LastWinUpd()
        {
           
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            PowerShell ps = PowerShell.Create();
            ps.Runspace = runspace;

            //ps.Commands.AddScript("gwmi win32_quickfixengineering | Select-Object -expandProperty 'installedon' | sort installedon -desc | Select-Object -First 1 | Get-Date -Format 'yyyy - MM - dd K'");

            ps.AddCommand("$a = (New - Object - com 'Microsoft.Update.AutoUpdate').Results");
            ps.AddCommand("$a.LastInstallationSuccessDate | Get - Date - Format 'yyyy-MM-dd K'");

            Collection<PSObject> results = ps.Invoke();

            runspace.Close();

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                text_LastWinUpd.Text = obj.ToString();
            }
           
        }
        // END
 
Last edited by a moderator:

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
4,130
Location
Sydney, Australia
Programming Experience
10+
So what actually happens? Do you end up with a Collection<PSObject> that's empty or something else? Are you able to successfully get the information you want in PowerShell itself? If not and you want help to fix the PowerShell code then this is a PowerShell question rather than a C# question. If the C# code is correct but the PowerShell code is not then there's nothing to be done from the C# end.
 

jwradhe

New member
Joined
Sep 23, 2021
Messages
2
Programming Experience
Beginner
PPowershell part works perfect, but i dont get it in the C# code.

if i use this part instead the 2 ps.AddCommand i got result. But wrong date.
C#:
 //ps.Commands.AddScript("gwmi win32_quickfixengineering | Select-Object -expandProperty 'installedon' | sort installedon -desc | Select-Object -First 1 | Get-Date -Format 'yyyy - MM - dd K'");
 
Last edited by a moderator:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,762
Location
Chesapeake, VA
Programming Experience
10+
This is not a C# problem nor a PowerShell problem. This the problem about the difference between WMI vs the AutoUpdate object model.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
3,762
Location
Chesapeake, VA
Programming Experience
10+
Moving out of WinForms and into some other more appropriate subforum...
 
Top Bottom