I'm using powershell to start process as another user.
To do this I'm using "Start-Process" as below.
$creds = Get-Credential -UserName $Name -Message "Please enter authorized credentials"
Start-Process `
-Credential $creds `
"C:\MyPowerfullProcess.exe" `
-RedirectStandardOutput $logOutputPath `
-RedirectStandardError $logErrorPath `
-WorkingDirectory $workingPath `
-ArgumentList $processArg
Stop-Transcript
The problem is that the $workingPath is only accessible to the user $creds and not by the user who started the .ps1 script. And The Start-Process command trough this error : "WorkingDirectory" Invalid [..] DirectoryNotFoundException
Start-Process
CategoryInfo : InvalidOperation : (:) [Start-Process], DirectoryNotFoundException
FullyQualifiedErrorId : DirectoryNotFoundException,Microsoft.PowerShell.Commands.StartProcessCommand
Try to use the following -Verb addition to specify the run-as.
$creds = Get-Credential -UserName $Name -Message "Please enter authorized credentials"
Start-Process `
-Credential $creds `
"C:\MyPowerfullProcess.exe" `
-RedirectStandardOutput $logOutputPath `
-RedirectStandardError $logErrorPath `
-WorkingDirectory $workingPath `
-ArgumentList $processArg `
-Verb RunAsUser
Stop-Transcript
Source: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process
Related
Below is my code, I've used the same process for connecting to sftp securely. I'm getting the error at the bottom of my post. Not sure if I'm missing a step in the creation of the key and password. Thanks.
#Set the credentials
$Password = Get-Content "c:\password.txt" |
ConvertTo-SecureString -Key (Get-Content "c:\aes.key")
$Credential = New-Object System.Management.Automation.PSCredential ('serviceaccount', $Password)
# Start a new instance of Windows PowerShell using the credentials
# stored in $Credential and run the script in $scriptblock
$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
$process = Start-Process $powershellPath -Credential $Credential -NoNewWindow `
-ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile " + $scriptBlock) -PassThru
# Script to execute in the new PowerShell instance
$scriptBlock = {
Import-Module ActiveDirectory
Get-ADUser ecarlsson | Set-ADUser -Manager bbob
Read-Host
}
I tried the code above and go the password error below.
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
At\filepath \\fV3.ps1:7 char:12
+ $process = Start-Process $powershellPath -Credential $Credential -NoN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
I need to create a powershell script that launch an exe file which also has two parameters, I want to put it in a group policy, so that it starts at the power on of each computer.
I tried this command:
$Username = 'user'
$Password = 'pass'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
invoke-command -Credential $Cred -ScriptBlock {& 'C:\myfile.exe' --param1 value --param2}
It tells me
Invoke-Command : Impossibile risolvere il set di parametri utilizzando i parametri denominati specificati.
In riga:1 car:1
+ invoke-command -Credential $Cred -ScriptBlock { & 'C:\Program Files ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeCommandCommand
I also tried this:
invoke-command -Credential $Cred -ScriptBlock {Start-Process -FilePath 'C:\myfile.exe' -ArgumentList "--param1 value", "-psb4"}
but the error that appears is the same.
I am using following code for running exe from PowerShell. However, it is throwing the error mentioned in the subject.
$uid = "ABCDomina\builder"
$pwd = "password"
$Args = "-Verb RunAs -Wait -passthru"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($uid,(ConvertTo-SecureString -String $pwd -AsPlainText -Force))
Start-Process -FilePath C:\windows\system32\system32\notepad.exe -Credential ($cred) -Argumentlist $Args
Error:
Start-Process : This command cannot be run due to the error: Logon failure:
unknown user name or bad password.
At C:\CD_Clinical\Nightly\DataLabs\Untitled1.ps1:5 char:1
+ Start-Process -FilePath C:\windows\system32\system32\notepad.exe -Credential ($c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Why not use -Credential Get-Credential? it seems a bit pointless as well trying to convert an item to a secure string if you are displaying it plain text, this will mean it gives you a prompt for username and password.
But if thats the route you want to go down then this should work.
$MyCredential=New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $Uid, ($pwd | ConvertTo-SecureString -AsPlainText -Force)
Could anyone tell me, why do I get an Error if I invoke:
$log = $env:TEMP + "\File.log"
$stdErrLog = $env:TEMP + "\stderr.log"
$stdOutLog = $env:TEMP + "\stdout.log"
$argument = "Get-Childitem c:\"
Start-Process powershell.exe -Credential $credentials -WindowStyle hidden -WorkingDirectory c:\ -ArgumentList $argument -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog -wait
but there is no Error if I invoke:
Start-Process powershell.exe -Credential $credentials -WindowStyle hidden -WorkingDirectory c:\ -ArgumentList $argument -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog
But I need the "-wait" or is there any alternative?
Error:
Start-Process : Permission denied
In Zeile:1 Zeichen:1
+ Start-Process powershell.exe -Credential $cred -WorkingDirectory c:\ -ArgumentLi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-Process], Win32Exception
+ FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.StartProcessCommand
Sounds like your current user doesn't have access to see processes running as the 2nd account. Launch a PowerShell window under the other account, then run the script below as yourself to see if it's visible. If not, you may need to elevate permissions or run as admin.
Get-Process powershell | select -ExpandProperty startinfo | select -expandproperty environmentvariables | ?{$_.Name -eq USERNAME}
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'