Run New PowerShell Process As A Different User

  • 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

  • $UserName = 'DOMAIN\DifferentUser'
    $PlainPassword = 'StrongPassword'

    The snippet of code above is from the code you posted.  I'm no ninja at PowerShell but that code seems to imply that the user name and password will exist in clear text, which is a serious violation of all that is holy when it comes to security.

    If what I've stated is correct, my recommendation would be to learn how to correctly use Active Directory for such things.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Thanks for the reply, Jeff.  This is just a simulation where I'm using a dummy account on a test server and was tired of typing the pwd.  I can't imagine anyone actually thinking that this would be the right thing to do. 

    Having said that, do you have any suggestions or help on the actual topic?

    Thanks,
    Mark

  • Coozie - Tuesday, January 15, 2019 11:19 AM

    Thanks for the reply, Jeff.  This is just a simulation where I'm using a dummy account on a test server and was tired of typing the pwd.  I can't imagine anyone actually thinking that this would be the right thing to do. 

    Having said that, do you have any suggestions or help on the actual topic?

    Thanks,
    Mark

    You said you wanted to spawn the process as a different user and then hardcoded it with no explanation.  With that, I thought you were actually going to do such a thing.  And, no... I can't imagine anyone actually doing such a thing and, yet, they do.

    As for the actual topic, yes... I have an idea... why are you trying to get information about the computer using T-SQL.  Why not just make a WMIC call?  Also, why write something like this?  Why not just buy an existing product the would not only identify such things but also provide you with the ability to monitor the servers for other things?  Of course, you'll also take some exception to those questions because your post hasn't provided anyone with enough information to actually know what the end game here is and so I'm just guessing based on what I see in the code.

    .

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • not sure if this helps.
    Fore security reasons, i never log in as my elevated account, but as a regular account,and spawn applications with the privileged account as needed. via a simple cmd/bat file:
    the advantage is i have saved my credentials the first time it runs, and just have to update when it's time to change password

    for example, to start the PowerShell IDE, i have a *.cmd file with one of the various commands below in it, as examples:
    Explorer++.cmd:
    runas /savecred /user:mydomain\super.admin.lowell "C:\_Apps\Explorer++\Explorer++.exe"
    PowerShell.cmd
    runas /savecred /user:mydomain\super.admin.lowell "%windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe"

    Bids2008.cmd
    runas /savecred /user:mydomain\super.admin.lowell  "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Coozie - Tuesday, January 15, 2019 11:19 AM

    Thanks for the reply, Jeff.  This is just a simulation where I'm using a dummy account on a test server and was tired of typing the pwd.  I can't imagine anyone actually thinking that this would be the right thing to do. 

    Having said that, do you have any suggestions or help on the actual topic?

    Thanks,
    Mark

    I haven't had time to test this yet but I think you need to do this a little differently that using start process.  Gather the credentials etc and then do New-PSSession and then invoke-sqlcmd.

    Sue

  • Summary:
    I'm trying to automate a process. 
    In the process I create sql credentials and a windows account.
    At a point in the process I have to execute code as that windows account.  For example: create asymmetric key.
    Then after that windows user creates the asymmetric key I have to complete some additional tasks to complete the automation.

    So in a nutshell:
    Execute code as me.
    Execute code as a different Windows user.
    Execute code as me.
    Done.

  • Coozie - Wednesday, January 16, 2019 6:44 AM

    At a point in the process I have to execute code as that windows account.  For example: create asymmetric key.
    Then after that windows user creates the asymmetric key... 

    Are you impersonating the Windows user only for T-SQL actions, like creating the key?
    If the reason you are impersonating the Windows user is only for actions on a SQL instance and your personal account on that instance has the rights, you can do this all in T-SQL and avoid the Credential object work.

    Create the user in AD with PowerShell first, then log into the SQL Server as yourself and use EXECUTE AS LOGIN to impersonate the new account and fire commands as that login.

    Once you have created the Windows user with PowerShell, you can log into SQL as yourself (or the automation account executing your script can log in as itself), and then execute a T-SQL batch to do the impersonation as it is doing the work inside SQL:

    -- the account must exist in AD before beginning
    -- add the Windows user to the SQL instance (membership in a Windows AD Group that has been granted access is not enough in this case)
    CREATE LOGIN [DOMAIN\DifferentUser] FROM WINDOWS;
    -- <set Login permissions and role membership here> --

    -- Once Login is ready, impersonate it and run commands as that login
    EXECUTE AS LOGIN 'DOMAIN\DifferentUser';
    -- all commands below here are executed as if you logged in as DOMAIN\DifferentUser
    CREATE ASYMMETRIC KEY MyKey....<etc.>
    -- <other commands go here as needed> --

    -- once you're finished doing 'DifferentUser' stuff, go back to being yourself
    REVERT;
    -- <do stuff as your login> --

    Eddie Wuerch
    MCM: SQL

  • Coozie - Wednesday, January 16, 2019 6:44 AM

    Summary:
    I'm trying to automate a process. 
    In the process I create sql credentials and a windows account.
    At a point in the process I have to execute code as that windows account.  For example: create asymmetric key.
    Then after that windows user creates the asymmetric key I have to complete some additional tasks to complete the automation.

    So in a nutshell:
    Execute code as me.
    Execute code as a different Windows user.
    Execute code as me.
    Done.

    This is beyond what I know for PoSH and I apologize for not being able to help here now that I know what you're trying to do.  It does seem that Eddie may have it for you, though.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Thanks to all for the replies.

    Thanks Eddie,
    I've tried to use Execute As Login.
    I'm able to start the Execute As Logon, however, I'm not sure if it's some limitation or policy with the cryptographic provider or what, but when I execute the code to create the asymmetric key as that login, I get the following error Msg:

    Msg 33048, Level 16, State 1, Line 12  Cannot use cryptographic provider under non-primary security context.

    So as you probably know, the Asymmetric key has to be created by the login that is mapped to the credential that is tied to the cryptographic provider.  The only other way I could think to automate it was to use PowerShell and spawn a new process for the part to create the asymmetric key.

Viewing 10 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic. Login to reply