Hello,
I’m trying to create a PowerShell script that will run a new PowerShell Process as a different ‘Windows’ user. The following code seems to work for running the new process as the different user, but I cannot understand how to send a command to the new process. I would like to be able to spawn the new process as a different user and pass some sql commands to it.
cls
$HostName = ‘SQLInstance’
$UserName = ‘DOMAIN\DifferentUser’
$PlainPassword = ‘StrongPassword’
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
$MyUserName = $Credentials.GetNetworkCredential().UserName
$MyDomain = $Credentials.GetNetworkCredential().Domain
#$PlainPassword = $Credentials.GetNetworkCredential().Password
$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
$MyCommand = “Invoke-Sqlcmd -query ““SELECT ServerProperty(‘ComputerNamePhysicalNetBIOS’)”” -ServerInstance ““SQLInstance”” -Database ““DatabaseName”””
#$MyCommand = $env:computername
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = “powershell.exe”
$startInfo.Arguments = ($MyCommand)
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Domain = $MyDomain
$startInfo.Username = $MyUserName
$startInfo.Password = $SecurePassword
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
$standardOut
###################################
The code above is what I used and modified from the following article:
https://stackoverflow.com/questions/18540505/processstartinfo-and-process-in-powershell-authentication-error