win32_process create fails with Unknown failure for service account user - powershell

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

Related

PowerShell Computer StartUp-Script - Switch user-context?

Through Microsoft Group Policy I did define to run a Powershell-Script on Computer Start-Up. Also I have the requirement to run a Powershell-Script as Scheduled Task without saving credentials.
On both scenarios I have the same problem ...
I want to run a Citrix Powershell-Command (PSSnapIn) like:
Set-BrokerMachine -MachineName "domain.local\$env:COMPUTERNAME" -AdminAddress "RemoteServer.domain.local" -InMaintenanceMode $True
Manual: https://citrix.github.io/delivery-controller-sdk/Broker/Set-BrokerMachine/
Of course only users who have the permission could run those Citrix-commands. I would be able to give a domain-user the permission to run the command "Set-BrokerMachine", but in the mentioned scenarios the PowerShell-scripts run in context of the system-user.
I did simulate the system-user by PSExec:
Error running as System-User
My scripts do other things of course and I want to keep them running as System-User, but now I am looking for a clean solution to get those Citrix-commands running.
If possible, I don't want to save credentials in my scripts.
EDIT #1:
I would be able to workaround with the following code:
$Username = "MySpecialUser"
$Password = 'MyPassword'
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePassword
$Result = Invoke-Command -Session ( New-PSSession -ComputerName "RemoteServer.domain.local" -Credential $Credential ) -ScriptBlock {
Add-PSSnapin Citrix*
Set-BrokerMachine -MachineName "domain.local\$args" -InMaintenanceMode $True
} -ArgumentList $env:COMPUTERNAME -HideComputerName
Remove-PSSession -InstanceId $Result.RunspaceId
I don't like this because:
The code has to contain credentials (ofc I could encrypt it ...)
I have to create a permission-system for this special user in Citrix
I have to put the special-user into a local-group on every server, to allow the remote-administration (security-risk)
I don't like to use PSSession
...
Is there a better/cleaner solution? Any ideas?

How to create a credential of my current user?

How to create a credential of my current user in PowerShell (without prompt)?
I invoke a remote script with a service account credential (on SCCM server),
I would like to send it my current credential because this remote script needs my local credential to write on my local hard drive (during mastering).
Both computers are in same domain, but my service account is not allowed to write on my local hard drive.
Edit :
1) I can't use the $Password way because I don't know who is logged (and password)
2) I already have a PSSession. My PSSession is with a service account But my remote script need my local credential I need 2 credentials
Invoke-Command -Session $RemoteServerSession -ScriptBlock $ScriptBlock -ArgumentList $LocalWorkstationSession
Because in my remote script I do want to do
$DriveOnWorkstation = New-PSDrive -Credential $LocalWorkstationSession -Name MyDrive -Root $UNCWorkstationFolderPath -PSProvider FileSystem
show the current script.
also, you can use
PS> $s = New-PSSession -ComputerName localhost
PS> Invoke-Command -Session $s -Script { param($processId) Get-Process -Id $processId } -Args $pid
or
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential (“Login”, $Password)

“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

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

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

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.