Search code examples
c#powershellwmiimpersonation

Running the powershell command with a different user in C#


I have a windows application that I wrote on VS C#, I run the following powershell command when Button3 is pressed,

When I right-click on the Windows application and select run as admin (I enter a different authorized user information), the command works perfectly.

But when I run it with a normal standard user (without permission to run PowerShell) I get an error,

Can I embed the authorized username and password into the application without right-clicking on the application and running it with admin? ​

    private void button3_Click_2(object sender, EventArgs e)
    {

    
        string command = string.Concat(@"$wmi = Get-WmiObject -class Win32_OperatingSystem -computer ", txb_pc.Text.Trim(), "\n", "$LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)","\n", "[TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)","\n", "\"$($uptime.days) Gun $($uptime.hours) Saat $($uptime.minutes) Dakika\"");


        using (PowerShell powerShell = PowerShell.Create())
        {
           
            powerShell.AddScript(command);
            powerShell.AddCommand("Out-String");
            Collection<PSObject> PSOutput = powerShell.Invoke();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject pSObject in PSOutput)
                stringBuilder.AppendLine(pSObject.ToString());
           txb_islemmonitoru.Text = stringBuilder.ToString();
        }


      
    }

Solution

  • I am very happy, I solved my problem.

    With the guidance of my brother "jdweng", I researched various articles and solved my problem using the following method,

    I'm sharing it to help others, we can close the topic.

    If there is a need to pass specific credentials to Get-WmiObject in order to gather information from remote machine, here is how you can do it:

    $LAdmin = "DOMAIN\Administrator"
    $LPassword = ConvertTo-SecureString "Password!" -AsPlainText -Force
    $Credentials = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList $LAdmin, $LPassword
    
    
    Get-WmiObject -ComputerName $computername -Class Win32_VideoController -Namespace "root\cimv2" -Credential $Credentials