Start a process as a different user in a script


I have a script that installs several programs. I’m using SCCM to let the users run it if they want to. So the script runs as a system user with administrator privileges, which works fine.

But at the end of the script, I have to start a process that has to be run as the logged on user on the machine. Is there a way to start this process as the logged on user?

You have to identify the logged in user first and the trigger the script as that user. But you would require credentials of that user and hence it wont be working for end user accounts. There can be multiple logon sessions as well in a system. Picking up the right user will difficult. And if you wan’t to execute the script with interactive session, then thats not possible with PowerShell.

Better to put the start process as a logon script , so it will execute interactively with user context and be sure to clean it up or use the Run reg key so that clean up is not required. But for both approaches a fresh logon from the user will be require.

I am not sure there is an option to switch the users in between in the same session, but you can use the Start-Process CmdLet with -Credential parameter everytime you trigger a command


$Credential = [System.Management.Automation.PSCredential]::new($UserName,$PassWord)
Start-Process -FilePath ‘<FileName>’ -ArgumentList ‘<Args>’ -Credential $Credential


Username nad Password, you need to manage them from your vaults or some secure way.

Thank you.

You can try to call another powershell script from within your current script and wait for it to complete ( probably with a flag file)

Here is a similar part of the script I wrote sometime back. The important ones are the Invoke command and the script block.

$list_UsersExtCloud = Invoke-Command -session (Get-Pssession) -scriptblock {Get-Mailbox -ResultSize Unlimited | select-object -property alias,HiddenFromAddressListsEnabled,RecipientTypeDetails,displayname } | Where { $_.RecipientTypeDetails -like “*UserMailbox” -and $_.HiddenFromAddressListsEnabled -eq $False -and $_.DisplayName -like “*:*” -and $_.DisplayName -like “*(*”}| select alias,displayname

Thank you guys! I will try to figure out something.