Powershell running as a another user with elevated privileges

后端 未结 2 636
-上瘾入骨i
-上瘾入骨i 2021-01-24 04:36

I have two scripts located in C:\\setup: script.ps1 and script1.ps1.

I want to be able to run the script1.ps1 from withing script.ps1 as another user and with elevated p

相关标签:
2条回答
  • 2021-01-24 05:21

    Since you're concerned about the new session window closing, I'm guessing you want command line output.

    Start-Process is working as intended. It will run the script passed in through -ArgumentList and exit the session. This means it will not hold to display command line output - the session will terminate immediately after the process completes.

    If you want a persistent session, use New-PSSession. Otherwise, you could export the data you're gathering to a file.

    0 讨论(0)
  • 2021-01-24 05:22

    It looks like you might need to adjust your parameters for powershell.exe. Instead of using -ArgumentList, which I don't think is valid, you should use the -File parameter. Also, you will want to use the -ExecutionPolicy Bypass parameter to ensure that the script execution policy is not interfering.

    Finally, I would recommend removing the single quotes from around the script path, as the Windows command interpreter does not understand single quotes to surround parameters.

    Give this a try:

    $ArgumentList = '-Command Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-ExecutionPolicy Bypass -File \"{0}\"" -Verb Runas' -f $sPath;
    Start-Process $PSHOME\powershell.exe `
        -Credential $sac `
        -ArgumentList $ArgumentList -Wait 
    

    Update

    It seems that some quoting rules were at play here as well, since we are embedding one command inside of another. I wrote and tested a fully function script on PowerShell v4.0.

    Here are the contents:

    # Create test directory and script file
    [void](New-Item -Path c:\test -ItemType Directory -Force);
    Set-Content -Path c:\test\test1.ps1 -Value 'Add-Content -Path $PSScriptRoot\blah.txt -Value (Get-Date);';
    
    # Get credential and define script path
    $Credential = Get-Credential;
    $ScriptPath = 'c:\test\test1.ps1';
    
    # Define the command line arguments
    $ArgumentList = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $ScriptPath;
    
    Start-Process -FilePath powershell.exe `
        -Credential $Credential `
        -ArgumentList $ArgumentList -Wait -NoNewWindow;
    

    I can confirm that I get a UAC prompt, and the target script successfully executes.

    0 讨论(0)
提交回复
热议问题