Start-Process: Access is denied (even though i've provided credentials - powershell

I am getting the following error when trying to execute a line of code
Start-Process : This command cannot be executed due to the error:
Access is denied.
This is the code being executed
$username = "domain\username"
$passwordPlainText = "password"
$password = ConvertTo-SecureString "$passwordPlainText" -asplaintext -force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,$password
$powershellArguments = "D:\path\ps.script.ps1", "arg1", "arg2", "arg3", "arg4"
Start-Process "powershell.exe" -credential $cred -ArgumentList $powershellArguments -wait
This code works fine when executed locally, but not when called via vbs WMI
Both computers exist in the same domain and address range
The username and password supplied have admin privileges on both machines
I have tried both with and without -wait however neither works, and due to the user being privileged, I'd prefer to keep it

Q: Have you tried without the "-wait"?
Look at this link:
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/3983a1e4-a663-47df-86f6-874d1828ea61/
The parameter "-wait" suppresses the command prompt or retains the
window until the process completes. This operation may require
administrator rights.

Related

Cant use -Credential when using "Start-Process" in Powershell

I want to execute a .exe File with the Start-Process Command while using specific credentials.
However I cant get it to work for me:
$username = "<Domain\Username>"
$password = "<Password>"
$secPassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentialps = New-Object System.Management.Automation.PSCredential ($username, $secPassword)
Start-Process -FilePath "<path to exe>\Test.exe" -Credential $credentialps -NoNewWindow -ArgumentList "<Arguments>"
This outputs the following error:
Start-Process : This command cannot be run due to the error: The parameter is incorrect.
I Also tried just using $credential = Get-Credential, this gives you back an PSCredentials Object, but it gave me the same error.
What am I doing wrong? Sorry if something's missing, Iam new to Powershell :)
Edit: After removing the Credentials parameter the script runs perfectly, so there shouldnt be a problem regarding the FilePath or Argumentlist.

Start-Process powershell credentials don't work but when using cmd it does

I am trying to run a powershell script from another powershell script passing in the credentials of a different user and then using the credentials:
Start-Process powershell.exe -Credential "LON\my-user" -NoNewWindow -ArgumentList "-file C:\DevopsScripts\stuckApps.ps1"
I have this is numerous different ways all get the same error. I have tried setting the username and password before the command:
$username = "LON\my-user"
$password = "pass"
$PSS = ConvertTo-SecureString $password -AsPlainText -Force
$cred = new-object system.management.automation.PSCredential $username,$PSS
$env:USERNAME
Start-Process powershell.exe -Credential $cred -NoNewWindow -ArgumentList "-file C:\DevopsScripts\stuckApps.ps1"
But everything I try gets the error:
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
I know the username and password are correct as they have been tested on the cmd which it works fine:
C:\Users\ADM-me>runas /noprofile /user:LON\my-user"powershell.exe C:\DevopsScripts\stuckApps.ps1"
What am I doing wrong here and how could I fix this, preferably by setting the password beforehand, so this can be automated. Also this does not need to be done using Start-Process, just this is the closest thing I could find to working.
I think the problem I am having is this, in stuck apps it has this:
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server = mssql.co.uk; Database = mydata; Integrated Security = true;"
$conn.Open()
I need this to run the credentials that I am trying to pass through it or else I get this error.
`Exception calling "Open" with "0" argument(s): "Login failed. The login is from an untrusted domain and cannot be used with Windows authentication."
But I can't pass the credentials through as the only ones that work are admin ones, (which I have but then that will throw the error above). Is it possible for me to use the admin logins to access stuck apps then use the logins needed to connect on stuck apps as an AD login.
Your first attempt with -Credential "LON\my-user" can't work, but your second attempt is correct, building the object of class PSCredential, as required (see the type in Get-Help Start-Process -Parameter Credential, it is PSCredential and not String). I tried the same with some reused code here, and it works here both or CMD and PS1 calling a PS1 test script via Powershell.exe, using a local test account (sorry, no domain #home).
So even though my code ist not identical and the domain of the user is the local machine, the approach is the same compared to yours and - sorry that this does not solve your problem - I don't see that you are doing sth. wrong.
To play safe, please make sure though to test with the same Powershell version, the below scripts executed under W10 1607 (so Powershell 5.1.14393.1198), all scripts in the same directory.
testscript.ps1
write-host "Testscript is run with user: $($env:USERNAME)"
Start-Sleep 2
testrun.cmd
runas /noprofile /user:%COMPUTERNAME%\myaccount "powershell.exe -NoProfile -ExecutionPolicy ByPass -file %~dp0testscript.ps1"
testrun.ps1
$Username = "$($env:COMPUTERNAME)\myaccount"
$Password = 'mypassword'
$SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
$ScriptFile = Join-Path -Path $PSScriptRoot -ChildPath 'testscript.ps1'
$Credential = New-Object System.Management.Automation.PSCredential( $Username, $SecurePassword)
$StartOpts = #{ 'FilePath' = 'powershell.exe'
'Credential' = $Credential
'NoNewWindow' = $false
'ArgumentList' = #( '-f', $ScriptFile,
'-ExecutionPolicy', 'Bypass',
'-NoProfile'
)
}
Start-Process #StartOpts
Some remarks on testrun.ps1
Don't mind the parameters for Start-Process being passed as a hashtable, it's just better readable for me, otherwise it makes not difference
The ArgumentList is being passed as a string array here - I prefer it this way so that it is automatically taken care for double qouting parameters, e.g. when the pathname of the script directory would contain spaces
The parameter -NoNewWindow passed to Start-Process seems not to have any effect here - a new window is opened
I always recommend to add the parameters -Noprofile and -ExecutionPolicy Bypass when using Powershell.exe to launch scripts or execute commands, just to make sure it works despite of the Execution Policy set or any present user or machine profile scripts.
However, at least the parameter -NoProfile seems not to work the same when Powershell.exe is being called fom the above CMD or PS1. Called from PS1, my machine profile gets nevertheless executed, but not fom CMD... interesting! The MSDN: PowerShell.exe Command-Line Help just says about this parameter: "Does not load the Windows PowerShell profile." Funny! There are six of them, see Technet: Understanding the Six PowerShell Profiles. I use "Current User, Current Host – console" and "All Users, Current Host – console". Lesson learned, but I am not sure if it's a bug or a feature.

“Access Denied” trying to execute a command using alternate credentials as user SYSTEM

I have a script that runs as SYSTEM, if i try to start-process notepad.exe it's working fine. if i add -credentials $cred it shows Access Denied. The credentials i pass over has local admin access, so why is there Access Denied? with procmon on powershell.exe i can not identify any access denied operation, i can see that powershell access notepad.exe with success result.
any ideas?
in one forum-post I read that it's not possible to execute a command with -credentials as SYSTEM. is that so?
if so, is there any workaround?
to my background, i use a software distribution where any installation runs as SYSTEM, from there i want to execute a powershell script as different user.
i found a solution:
$secpasswd = ConvertTo-SecureString 'password' -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ('domain\user', $secpasswd)
Invoke-Command -ScriptBlock { Start-Process powershell c:\temp\mmc.ps1 -verb runas -wait} -ComputerName localhost -Credential $mycreds -Verbose
its not exactly what i want because here you need to enable psremoting first. but its like a workaround.
any idea how this is possible without invoke-command would be appreciated

win32_process create fails with Unknown failure for service account user

I have a windows service account user, using which i'm trying to create a background process using the WMI win32_proces. But fails with Unknown Failure.
(Tried this with administrator, nonadmin, domain admin, domain nonadmin users. works fine)
$process = [WMICLASS]"\\$computername\ROOT\CIMV2:win32_process"
$processinfo = $process.Create("powershell.exe -WindowStyle Hidden test.ps1")
Write-Host $processinfo.returncode
As explained in this msdn blog post: Win32_Process.Create fails if user profile is not loaded, the WMI call is hardcoded to access the users profile through the registry.
If the user profile is not already loaded in HKU, WMI tries to load it into the registry using RegLoadKey.
This fails unless the user account in question have the following privileges on the local machine:
SeRestorePrivilege
SeBackupPrivilege
So, either
Grant these privileges to the account in question
Call LoadUserProfile for the user in question prior to calling Win32_Process.Create
Or use Start-Process instead of WMI!
# Set up service account credentials
$Username = "domain\svcaccount"
$Password = "7oPs3çürEûN1c0deZ"
$Credential = New-Object pscredential -ArgumentList $Username,$(ConvertTo-SecureString $Password -AsPlainText -Force)
# Establish a session on the remote machine
$RemoteSession = New-PSSession -ComputerName $computername -Credential $Credential
# Launch the process with Start-Process -LoadUserProfile
Invoke-Command -Session $RemoteSession {
Start-Process 'powershell.exe' -LoadUserProfile:$true -Argumentlist 'test.ps1' -WindowStyle Hidden
}
# Cleanup
Remove-PSSession -Session $RemoteSession
Remove-Variable -Name Username,Password,Credential
To Mathias suggestions in below comments:
Start-Process works in background only when invoked through interactive prompt. If run from a .ps1 script, the process created through start-process exits if the .ps1 script exits.
Inside your script. You can create a New-PSsession and then pass this session to invoke-command to trigger start-process.
But again to use New-PSsession and ExitPSSession, you must have Enable-PSRemoting and other setting enabled if you are lacking permissions. http://blogs.msdn.com/b/powershell/archive/2009/11/23/you-don-t-have-to-be-an-administrator-to-run-remote-powershell-commands.aspx

Run ScriptBlock with different credentials

I have a script, that determines a userid; once I have that userid, I want to run a script block against that userid using different credentials. Is this possible? Can anyone show me examples of this?
I got it, thanks to Trevor Sullivan for pointing me in the right direction. I ended up just putting my second ps1 file into a scriptblock, and running it as a job, and passing it the arguments from the main script, like this
$job = Start-Job -scriptblock {
param ($username)
some code to run against the variable that was passed in
} -Args $target -credential $Cred
$target being the variable I want to pass to my scriptblock.
$username being the parameter that the scriptblock accepts Thanks.
I know this was answered a long time ago, but I thought I'd add another option for those looking that returns data without having to retrieve it.
We can create a helper script that creates a pscredential and then uses it to start a local PSSession to run a script or scriptblock in a different user's context. You need to get the user password from somewhere, preferably entered as a secure string or retrieved from a Key Vault, but for the example our helper script will take it as a string parameter.
Script contents:
param ([string]$username,[string]$password)
$Username = 'username#domain.com'
$Password = ConvertTo-SecureString -String $password -AsPlainText -Force
$Credential = New-Object -Type PSCredential($Username,$Password)
$Session = New-PSSession -Credential $Credential
Invoke-Command -Session $Session -FilePath C:\Path\to\some\script.ps1
You can also use -ScriptBlock instead of -FilePath if you have a simple chunk of code to run or you have converted a script to a script block.
Hope this helps somebody out!
Security context for a session is established when the session is initialized. You can't arbitrarily run commands under a different context within the session. To run under a different security context (set of credentials) you'll need to initialize a new session under those credentials and run it there.
If you look at the help for Invoke-Command, you'll note that the -Credential parameter is only valid in parameter sets that specify a remote session by computername, uri, or session. You can also use -credential with Start-Job, which will run the command in a new session on the local machine.
This code will launch PowerShell in Administrator mode using the credentials provided and then run the code in the script block. There might be others ways but this works for me.
$account= # AD account
$password = # AD user password
$passwordSecure = ConvertTo-SecureString ($password) -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ($account, $passwordSecure)
$ScriptBlock = {
whoami
start-sleep 3
}
 
# Run PowerShell as Administrator with Custom Crednetails
start-Process powershell.exe -Credential $Cred -ArgumentList "-Command Start-Process powershell.exe -Verb Runas -ArgumentList '-Command $ScriptBlock'" -Wait