Powershell start process with runas and credentials - powershell

I'm trying to run a process with a hardcoded user and pwd however i seem to only be able to specify either the credential or runas, but never both:
$username = "[redacted]"
$password = "[redacted]"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
# Self-elevate the script if required
# From: https://blog.expta.com/2017/03/how-to-self-elevate-powershell-script.html
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
$CommandLine = "-noexit -noprofile -File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process Powershell -Verb Runas -ArgumentList $CommandLine # work, but no credential
# Start-Process PowerShell -Cred $credentials -Verb Runas -ArgumentList $CommandLine # both credential and runas, doesnt work.
Exit
}
}
How can i run Start-Process with both credentials and runas?

Related

Powershell - Within Powershell ISE run multiple line script in Powershell

I have a script that runs in Powershell ISE but there is a part of that script that has to run in regular Powershell. The script that needs to run in Powershell has multiple lines.
When I try running the script like this:
<#
Some code runs up here
#>
$script = {
$PW = "Password1";
$PW = $PW | ConvertTo-SecureString -AsPlainText -Force;
Add-SQLAssessmentTask -ManagementGroup "SOME_ID_NUMBER" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose;
}
$command = $script.ToString()
#Start-Process powershell -argumentlist $command
Start-Process powershell -argumentlist $script
I get the follow error:
When I run the script like this:
<#
Some code runs up here
#>
$arguments = "$PW = ""Password1""","$PW = $PW | ConvertTo-SecureString -AsPlainText -Force","Add-SQLAssessmentTask -ManagementGroup ""SOME_ID_NUMBER"" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose"
Start-Process powershell -argumentlist $arguments
I get this error:
If I run each line in regular Powershell, one at a time, it works fine.
Any suggestions?
$Arguments is supposed to be a script block separated by semi-colons if you want to run multiple commands.
$arguments = {"$PW = ""Password1""";"$PW = $PW | ConvertTo-SecureString -AsPlainText -Force";"Add-SQLAssessmentTask -ManagementGroup ""SOME_ID_NUMBER"" -SQLServerName $env:computername -WorkingDirectory C:\Temp\SQL -ScheduledTaskUsername domain\user -ScheduledTaskPassword $PW -Verbose" }
Start-Process powershell -argumentlist $arguments

How to launch an other ps1 within a ps1 with an other accompt (and admin rights)?

I've got a bug on some of my users computers and I need my users to launch a .ps1 from their computer to fix the problem so i can access to their computer when they need it through NetSupport.
Problem is that they don't have administrator rights on their computer.
So this is what I did already :
Encrypt an admin password in a .txt (this one will be launch by me with administrative rights)
Function RandomKey {
$RKey = #()
For ($i=1; $i -le 16; $i++) {
[Byte]$RByte = Get-Random -Minimum 0 -Maximum 256
$RKey += $RByte
}
$RKey
}
$Key = RandomKey
$key |Out-File "$path\Key.txt"
Read-Host "Enter one admin Password" -assecurestring | ConvertFrom-SecureString -key $Key | Out-file "$path\EncKey.txt"
This part seems to work fine.
Now, come the working "client" part :
$PassKey = get-content "$Path\Key.txt"
$Password = get-content "$Path\EncKey.txt" | Convertto-SecureString -Key $PassKey
$User = Read-Host "Enter the ID given by your administrator"
$credentials = New-Object System.Management.Automation.Pscredential `
-Argumentlist $User,$Password
And the not working one (I tried a lot of things here some exemple) :
1 : When I set the local administrator (.\administrator) a new powershell Windows start with administrator rights but doesn't do what the file.ps1 is supposed to do, and if I set domain\adminaccount it just start a new posershell windows but without admin rights.
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process powershell -ArgumentList "-file "\\serveur\path\file.ps1" "}'
2 : When I set the local administrator (.\administrator) a new powershell Windows start with administrator rights but only half of the script (file.ps1) works, and if I set domain\adminaccount : same as above.
Invoke-Item (Start-Process powershell.exe -Credential $credentials ((Split-Path $MyInvocation.InvocationName) + "\\serveur\path\file.ps1" ))
3 and so on
Start-Process powershell -ArgumentList '-executionpolicy, bypass, -file "\\serveur\path\file.ps1", -Credential $credentials, -verb RunAs'
Start-Process -filepath "\\serveur\path\file.ps1" -Credential $credentials -ArgumentList '-noprofile -noexit -command -verb runas}'
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process powershell -ArgumentList "-file "\\serveur\path\file.ps1" "}'
But nothing works as expected...
If you guys have an idea it'll be wonderfull !!
--------------------- EDIT ----------------
I did a mistake in my file.ps1, so
Invoke-Item (Start-Process powershell.exe -Credential $credentials ((Split-Path $MyInvocation.InvocationName) + "\\serveur\path\file.ps1" ))
This work fine with local admin (.\administrator), the script does start with admin rights and works as expected.
BUT... it doesn't work with domaine admin (domain\admin) : the script does start, but without admin rights...
Can you try using this script ?
I was able to call this as below and get an elevated session.
Invoke-Elevated -FilePath \\server\share\file.ps1
If someone interested by the solution I found to make it work with local administrator account here it is :
Couldn't make it work with the file.ps1 I wanted to execute on a UNC path.
So I had to copy it 1st on the local computer executing the script.
$path="[...]\temp"
$source= "[...]file.ps1"
$destination = "c:\users\$env:USERNAME\documents"
if (!(Test-Path "$destination\Netlogon_Firewall.ps1")){Copy-Item -Path $source -Destination $destination}
Then I import my credentials :
$PassKey = get-content "$Path\Key.txt"
$Password = get-content "$Path\EncKey.txt" | Convertto-SecureString -Key $PassKey
$User = Read-Host "Enter the ID given by your administrator"
$credentials = New-Object System.Management.Automation.Pscredential `
-Argumentlist $User,$Password
And finaly i can start the file.ps1 script with administrator rights :
Start-Process -Credential $Credentials "$PSHOME\powershell.exe" -WorkingDirectory "C:\Users\$env:USERNAME" -ArgumentList "-ExecutionPolicy Bypass & '$destination\file.ps1'"

PowerShell Start-Process with other user credential and wait

I am starting a process with PowerShell using another user with elevated rights.
$username = "username"
$password = "password"
$startWithElevatedRights = "notepad"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ‘, $startWithElevatedRights, ‘ -Wait -verb runas}'
I know it's bad style to write user credentials to code, but it is used within full automated procedures, so this is necessary.
My problem is, that I cannot wait until the process (last code line) finished. The inner process waits as expected.
I tried the parameter -Wait, * | Wait-Process, * | Out-Null, with return Value (which is always null)
Nothing works.
Is there any solution waiting until the process has exited?
If there is any solution for PowerShell 2.0 it would be the best for my use case.
You can get Process object from Start-Process using PassThru parameter and then wait for it to exit.
$username = "username"
$password = "password"
$startWithElevatedRights = "notepad"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ', $startWithElevatedRights, ' -Wait -verb runas}'
$ps.WaitForExit()

start-process with elevated credentials and password on file

I want to make a script for my users. It will let us install applications while there are not admins.
pw= get-content \\xxx\xxxx\xxx\xxx\pass.txt | convertto-securestring
$pp= new-object -typename System.Management.Automation.PSCredential -argumentlist "xx\admin",$pw
The file is created and is crypted.
$script = "\\xxxx\xxx\xxx\xxx\Install_chrome.ps1"
Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process $script -verb runas}' -RedirectStandardOutput c:\stdout.txt -RedirectStandardError c:\stderr.txt
Here's my error:
Start -Process : Unable to validate the argument on parameter "FilePath". The argument is null or empty. Specify an argument that is not null or empty and try again.

Powershell - Start-Process to launch hello world is not working

I am trying to figure out how to run powershell script with elevated credentials, and was told the best way to do this was with Start-Process
And this website, http://social.technet.microsoft.com/Forums/windowsserver/en-US/132e170f-e3e8-4178-9454-e37bfccd39ea/startprocess-verb-runas-credential is also good reference
But I am still having trouble.
I created one script for testing purposes, hello.ps1
write-host Hello World
That runs well by itself
Then, I created another script to invoke Hello World with elevated credentials
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\script\hello.ps1"
Start-Process powershell -Credential $credentials -verb runas -ArgumentList "-file $script"
And I get error:
At C:\script\my_script.ps1:6 char:14
+ Start-Process <<<< powershell -Credential $credentials -verb runas -ArgumentList "-file $script"
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
EDIT
#Adi Inbar
I updated the code as follows
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
Start-Process powershell -Credential $credentials -ArgumentList "-file $script"
But now a cmd windows pops up and the output is blank, instead of the expected "Hello World"
EDIT
And I read that you must include -FilePath if you include -Credential, but code is still not working :-(
It just pops-up the cmd window and no output is written in powershell_ise.exe GUI
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
Start-Process -FilePath C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Credential $credentials -ArgumentList "-file $script"
-Verb and -Credential are in different parameter sets. They cannot be used together. -Verb runas doesn't run the specified process as a different user (not to be confused with the runas command), it uses UAC to run the process with elevated privileges in the current user's context, like right-clicking and selecting "Run as administrator".
Just get rid of -Credential $credentials, and run the script while logged in with an account that has local admin privileges.
Well, I was able to answer parts of my question, because I still have a bigger question that I will post separately
'noexit' in -ArgumentList keeps the cmd window persistent, but at least it outputs the value, so at least I know the program is working
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Username",$password
$script = "C:\Script\hello.ps1"
start-process powershell -Credential $credentials -ArgumentList '-noexit','-File', 'C:\script\hello.ps1'