Run PowerShell-Script from C# Application

后端 未结 3 1949
既然无缘
既然无缘 2020-12-05 08:18

I\'m trying to execute a PowerShell script from a c# application. The script has to be executed under a special usercontext.

I\'ve tried different scenarios some are

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 08:35

    Several PowerShell cmddlets take a PSCredential object to run using a particular user account. May have a look at this article - http://letitknow.wordpress.com/2011/06/20/run-powershell-script-using-another-account/

    Here's how you can create the Credential object containing the username and password you want to use:

    $username = 'domain\user'
    $password = 'something'
    $cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
    

    Once you have the password ready for use in a credential object, you can do a number of things, such as call Start-Process to launch PowerShell.exe, specifying the credential in the -Credential parameter, or Invoke-Command to invoke a "remote" command locally, specifying the credential in the -Credential parameter, or you could call Start-Job to do the work as a background job, passing the credentials you want into the -Credential parameter.

    See here , here & in msdn for more information

提交回复
热议问题