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"
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