Powershell running as a another user with elevated privileges - powershell

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 privileges but I cannot make it work. The new powershell window opens but closes immediately ...
here is the script:
$cspath = $MyInvocation.MyCommand.Path
$sfolder = Split-Path $cspath
$spath = Join-Path $sfolder "\Script1.ps1"
$sa = "domain\user"
$sap = "userpassword"
$sasp = ConvertTo-SecureString -String $sap -AsPlainText -Force
$sac = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sa, $sasp
Start-Process $PSHOME\powershell.exe `
-Credential $sac `
-ArgumentList "-Command Start-Process $PSHOME\powershell.exe -ArgumentList `"'$spath'`" -Verb Runas" -Wait
Any help will be appreciated ...

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.

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.

Related

Powershell remote execution of Oracle installer Silent from unc

Meanwhile I've read and tried so many options and none of them worked for me.
I need to run a command on a remote machine that will install an application.
The setup.exe is an Oracle installer and is able to accept silent parameters.
"\\SVR1\Share\remote application Install\install\Setup.exe" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx
When I paste this command in a cmd it works as expected
When I put this in a ps1 script and run it, it works too:
cmd /c "\\SVR1\Share\remote application Install\install\Setup.exe" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx
However trying to run this 1 line script from a remote computer, it fails with: [Start-Process], InvalidOperationException
$svr="mach1"
$cmdFile="install.ps1"
$RemDir = "\\${svr}\C$\All_files\Scripts\"
$fn = "${RemDir}\${cmdFile}"
$password = ConvertTo-SecureString "${pazwd}" -AsPlainText -Force
# can't change the remote dir without spaces
"cmd /c `"\\SVR1\Share\remote application Install\install\Setup.exe`" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx " | Out-File -FilePath $fn
$cred = New-Object System.Management.Automation.PSCredential($user,$password)
$sb = { Start-Process -FilePath "${LocalDir}\${cmdFile}" }
Invoke-Command -ComputerName $svr -Credential $cred -ScriptBlock $sb
Suggestions? what Am I doing wrong here?

Powershell-Command to download a file with admin rights

I try do download a file via a powershell command. The command I use is simple:
Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'
I can run the command in PS succesfully. But now I want to run it with elevated rights. So I gooogled and found this solution:
There it says the command should be:
Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {get-process}"
So I tried adjusting it for my use case:
Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"
But all is does is open a new PS-Window and closing it right after. Where is my mistake?
You can change to this
Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"
Note the window will close after the execution completes. If you would like to see the output/errors (such as what would be shown in your non working example) just add another command to pause.
Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer -Source 'https://download.com/file.zip' -Destination 'E:\test\file.zip';pause}"
& is used to invoke a command. It's useful for executing strings or scriptblocks. It runs in a child runspace.
& 'Get-Host'
& 'Write-Host' Hello -Fore Green
& {Write-Host Goodbye -Fore Cyan}
; is used to separate different commands on the same line.
& {$name = 'Doug';Write-Host Hello $name}
You can also use a period to invoke a scriptblock in the current runspace. In the previous command the $name variable would be empty in the callers scope where the following command would leave the variable defined.
& {$name = 'Doug';Write-Host Hello $name}
$name # empty as it all happens in the child scope
vs
. {$name = 'Doug';Write-Host Hello $name}
$name # populated because it's brought into the caller's scope

Opening multiple powershell scripts same time for user

I am developing a SQL health check using powershell. So it checks the statuses of databases and outputs text to console whether anything needs attention. i have the first ps1 to load the various checks but i need them to start loading the below ps1's in parralel. I need to work this on powershell v2. Do i need to use start-job for each line
Here is my code
$Output = #()
$BackupHistory = #()
$script = $myInvocation.MyCommand.Definition
$scriptPath = Split-Path -parent $script
Start-Process -FilePath powershell.exe -ArgumentList "-noexit","$scriptpath\SQLHealthVLF.ps1 $Env" -Wait -WindowStyle Maximized
Start-Process -FilePath powershell.exe -ArgumentList "-noexit","$scriptpath\SQLHealthBackup.ps1 $Env" -Wait -WindowStyle Maximized
Start-Process -FilePath powershell.exe -ArgumentList "-noexit","$scriptpath\SQLHealthIOAlerts.ps1 $Env" -Wait -WindowStyle Maximized
Start-Process -FilePath powershell.exe -ArgumentList "-noexit","$scriptpath\SQLDisksUsage.ps1 $Env" -Wait -WindowStyle Maximized
What currently happens is one loads, then i need to close it and then the next one loads. This doesn't give the script consistency.

Can't start PowerShell script file with credentials of other user

I have a GUI that has been created with PowerShell Studio and exported as a PS1-file. I'm now trying to launch this GUI by calling it with another user's credentials.
When I run the code it doesn't even give an error message. PowerShell pops-up and closes again in seconds and nothing is launched. Follwoing this thread, I think I followed the correct syntax.
$Script = 'S:\Prod\Script center\GUI Script.ps1'
$Credentials = Get-Credential
$powershellArguments = "-file '$Script'", "-noexit", "-verb runas"
Start-Process powershell -Credential $Credentials -ArgumentList $powershellArguments
These ones doesn't work either:
Start-Process powershell -Credential $Credentials -ArgumentList "-noprofile -command &{Start-Process powershell -verb runas -File 'S:\Prod\Script center\GUI Script.ps1'}"
Start-Process powershell -Credential $Credentials -ArgumentList "-noprofile -command &{Start-Process $script -verb runas}"
And this one is asking me the credentials, although they are already saved in the variable $Credentials. However, the powershell console launched is not launched as the user in the Credentials :(
$cmd = 'powershell.exe'
$arguments = "-NoExit", "-NoProfile", "-WindowStyle Maximized", '-NoLogo', "Credential $Credentials", "File '$script'"
Start-Process $cmd -ArgumentList $arguments -Verb runAs
I'm sure it's not related to the GUI script, because this works perfectly fine:
& 'S:\Prod\Script center\GUI Script.ps1'
Any help is greatly appreciated.
Maybe your error is only on argument single quotes $powershellArguments = "-file '$Script'"; double quotes should be used.
Start-Process -FilePath "powershell" -Credential $cred -ArgumentList #("-file 'cred.ps1'") # doesn't work
Start-Process -FilePath "powershell" -Credential $cred -ArgumentList #("-file ""cred.ps1""") # works

run another program with credentials

what I'm trying to do is add a user to the local admin group then launch a program with those credentials. I have the first part working:
$env:COMPUTERNAME
$srvgroup = [ADSI]("WinNT://"+$env:COMPUTERNAME+"/Administrators, Group")
$srvgroup.name
$srvgroup.add("WinNT://userID,user")
$srvgroup.Invoke("Members") | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
The second part is what I can't seem to get working correctly.
Start-Process runas.exe -Credential DOMAIN\user -ArgumentList '-noprofile -command & "C:\Program Files (x86)\Misc\SecureClient" -verb runas}'
I don't get an error message but the program does not start. I should get a popup window for the application but nothing happens when I try it this way.
Any ideas?
DOMAIN\user is not a full credential. You need to do something like this:
$passwd = ConvertTo-SecureString "opensesame" -Force -AsPlainText
$cred = new-object pscredential 'Domain\user',$passwd
Start-Process -Credential $cred ...
I ended up doing it like, don't really like it but it works:
start-process "cmd.exe" "/c D:\Scripts\client_connect.cmd"
that .cmd file is:
C:\Windows\System32\runas.exe /savecred /user:domain\username"C:\Program Files (x86)\xxx\xxx\sclient.cmd"