Poweshell under the security context of another user (RunAs)

Recently i needed to run some powershell scripts under multiple security context’s – the main reason for this was my client’s strict delegation model.

We ended up with multiple service account with rights only to the needed systems (Its not such a bad thing!)

The result was this powershell script to change security context

$SPAccountName = “<username>”;
$AccountPassword = “<password>”;
$AccountPasswordAsSecureString = $AccountPassword | ConvertTo-SecureString -Force -AsPlainText
$credential = New-Object System.Management.Automation.PsCredential(“$env:userdomain\$SPAccountName”,$AccountPasswordAsSecureString)
$SvcAccSession = New-PSSession -Credential $credential;
Invoke-Command -Session $SvcAccSession -Script { Import-Module ActiveDirectory }
Invoke-Command -Session $SvcAccSession -Script { Get-AdGroupMember “Some-group”}

In the above example we just get the member of some application group – but really, you can do whatever you like.

If you need it to query a specific server you can use -Computername <servername> right after New-PSSession.

This method also came in rather handy when running service-side powershell execution invoked by a webservice.. but more on that later

 

Feel free to comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.