Not able to run exe from powershell for a system user - powershell

I am trying to run an exe from powershell script on windows-7 64 bit machine. In this script I want to run exe as another user. It works when user invoking script is an actual user. But in my case, this powershell script will be executed from system user account and for system user script does not work. Here in a simple code I am using to open notepad. This code fails for system user.
$username = 'MyDomain\MyUser'
$password = 'mypswd'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process -Credential $cred "notepad.exe"
I have set execution policy to unrestricted. When I run this script for system user, then I get error as
Start-Process : This command cannot be executed due to the error: Access is den
ied.
At D:\temp\trythis.ps1:4 char:14
+ Start-Process <<<< -Credential $cred "notepad.exe"
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
Is there any way in which I can run this script for system user?

The most likely problem here is a permissions one (The only way I could reproduce your issue was by setting a Deny entry for the account).
I would suggest the following to confirm the permissions are correct. Instructions are for Windows XP, SP3 - adjust for your version!
Right-click on "notepad.exe" and click Properties
Click the Security tab
Click the Advanced button
Click the Effective Permissions tab
Click the Select... button
Enter the account you want to check and confirm that the account has appropriate read and execute permissions.

Related

How to use Powershell to grant Windows application or executable to use your network profile?

Powershell newbie here. I am learning Powershell (yes, I have been ignoring it all these years) as I have never needed this one particular need of mine. I have looked at PS tutorial sites and, of course, StackOverflow for any tips. Seems like my need is unique.
Short story, how do you execute an application (for example, notepad.exe) on a local machine to open a network shared file but the local machine has a generic logged-on user but the network share requires a privileged user (like mine) to open the file. I want the app/executable to inherit my credentials but not set the local machine itself. I want to run a local app/executable as if I logged on to the local machine with my credentials.
I have read PS can do this exact thing so I have been experimenting with Powershell command line:
start-process "[SOME APP].exe" -FilePath "\DIRECTORY\PATH\WHERE\APP\IS\LOCATED]" -Credential (Get-Credential -Credential "DOMAIN\USERID")
I get an error prompt from the Powershell command line:
start-process : This command cannot be run due to the error: The
system cannot find the file specified. At line:1 char:1
+ start-process "[SOME APP].exe" -FilePath "[\DIRECTORY\PATH\WHERE\APP\IS\LOCATED] ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
I plan on using this Powershell script in my LabVIEW executable to assign the VI (virtual instrument) executable my own network login privilege to transfer files to/fro or modify a text file that resides in the network share.
Thanks for your help guys!
You could do something like the following. All you need to do is change the $app variable to the executable you want and save the script as a PS1 file. Someone can run it by right-clicking and selecting Run with PowerShell or opening a PowerShell console and typing in path\scriptname.ps1.
$App = "c:\windows\system32\notepad.exe"
$Credentials = Get-Credential
$WorkingDir = Split-Path $app
$Exe = Split-Path $app -Leaf
Start-Process -FilePath $Exe -WorkingDirectory $WorkingDir -credential $Credentials

Access denied while running Windows Update using Powershell's Invoke-Command

I've been trying to setup a Powershell module that would remotely call Windows/Microsoft update on a server using Invoke-Command, then process the updates, and send everything back to the calling server so it can send an email report.
My issue comes when I try and call the downloader: Powershell seems to be requesting Elevated rights on the remote computer.
Here is a snippet of what I'm trying to run and fail:
Invoke-Command -ComputerName $Server -Credential $Credentials -ScriptBlock {
$UpdateSession = New-Object -ComObject "Microsoft.Update.Session"
Write-Progress -Activity "Updating" -Status "Checking for new updates"
$Criteria = "IsInstalled=0 and Type='Software'"
$Updates = $UpdateSession.CreateUpdateSearcher().Search($Criteria).updates
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $Updates
}
I know the issue isn't with remoting, as the first 4 commands work fine.
The $Credentials variable points to pre-defined credentials, which are Local Admin on the remote server.
When the script gets to the 5th line, $Downloader = $UpdateSession.CreateUpdateDownloader(), I get this error from Powershell:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : SERVER.sidlee.inc
What could be causing this exactly ?
Thanks in advance for the help!
As i just hit the same wall, and Google isn't of much help either, here is what i could dig up.
For the record, i am pretty much doing the same thing (using custom PS code to check remote systems for Windows Updates) but using WinRM over Python instead of Invoke-Command and also got stuck on Microsoft.Update.Searcher.Search() throwing a E_ACCESSDENIED error.
The UnauthorizedAccessException is indeed not related to Powershell but the underlying API.
I suspect Microsoft started cutting off impersonation in remote session in some recent update (Powershell v5?) as this was (and still is) working just fine on older Windows versions (e.g. Server 2012 with Powershell v3 or 2012 R2 with v4)
To get around this you will need to authenticate (on the remote server) prior to executing your stuff with a PSCredential object.
So Remote Auth -> Local Auth -> Run stuff for example using Start-Process -Credential ...
e.g.
$pass = ConvertTo-SecureString "PA$$W0RD" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential "User", $pass
Start-Process -Credential $creds powershell -ArgumentList "-Command & { ... whatever you want to do ... }"
Keep in mind that this poses a security risk as your password will be parsed in clear text, so don't do this over an
unencrypted channel!

Run BAT file as a Local User Account

I pulled this from another question, but I cannot seem to make this work.
I need to run this .bat file as a local admin account. I want users to be able to run and install this without having local admin rights.
I'm not sure what's wrong though.
$username = 'localadmin'
$password = 'passwordforlocaladmin'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process -Filepath "p:\kaceInstaller\kaceinstall3.bat" -Credential $credential
The error I'm getting back is:
Start-Process : This command cannot be executed due to the error: The directory
name is invalid.
At P:\kaceInstaller\misc\kaceSetup.ps1:7 char:14
+ Start-Process <<<< cmd -Credential $credential
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommandy
If you want to allow users to run something as a local administrator account without effectively giving them the password to the local admin account, I would suggest to create a scheduled task running as a local admin. Users can manually trigger that task, which will then be executed under the local admin account. Creating the task withoug saving the credentials should work, but even if you have to save the credentials they won't be accessible to your users.
For access to network shares you may need to connect/disconnect the share with explicit credentials from within the script that the scheduled task runs, though, because the local account usually doesn't have permission to access the network drives mapped by your domain user.
net use X: \\server\share\kaceInstaller password /user:DOMAIN\user
call X:\kaceinstall3.bat
net use X: /d
Make DOMAIN\user a dedicated account that has access only to \\server\share and nothing else to minimize risk.
Note that you must make sure that the script run by the task is not writable by regular users, otherwise they will be able to run arbitrary commands with admin privileges by simply modifying the script.

How to avoid the crendetial dialog box while conecting to different system using powershell?

I am making connection to the diferent system using powershell. I want this process to be automated in a way that once user hits the powershell script he gets connected to different system without entering username and password details into the dialog box. So, currently my.PS1 script as follows:
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts CP0001256
Restart-Service WinRM
Test-WsMan CP0001256
$credential = Import-CliXml -Path "D:\$Env:USERNAME_pass.xml"
Invoke-Command -ComputerName CP0001256-ScriptBlock { Get-ChildItem D:\ }-credential $credential
Before running my.PS1 i have executed follwing script:
$credential = Get-Credential
$credential | Export-CliXml -Path "D:\$Env:USERNAME_pass.xml"
So, when i execute my.PS1 i got error as:
Invoke-Command : Cannot process argument transformation on parameter 'Credential'. username
At my.PS1:7 char 86
+ Invoke-Command -ComputerName CP0001256-ScriptBlock { Get-ChildItem D:\ } -credential <<<< $credential
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindin..mationException
+ FullyQualifiedErrorID : ParameterArgumentTransformationError,Microsoft.Powershell.Commands.InvokeCommand
So, tell me what i am doing wrong and how can i avoid getting the credential dialog box pop up appearing.
This is a question of how to store credentials in a script. Keep in mind that this always carries some risk. You can of course store them in plain text. Then anyone with access to the script has those credentials.
Another thing you can do is take advantage of the [PSCredential] object, and store the password encrypted. Consider running this code (outside of that script):
$credential = Get-Credential # dialog pops up here, enter server creds
$credential | Export-CliXml -Path "C:\Script\$Env:USERNAME_Credential.xml"
Now in your script, you can do this:
$credential = Import-CliXml -Path "C:\Script\$Env:USERNAME_Credential.xml"
Invoke-Command -ComputerName CP0001256-ScriptBlock { Get-ChildItem D:\ }-credential $credential
The password is encrypted within that XML file, and it's encrypted with a key that is specific to the user who ran the first set of commands, so only that user will be able to effectively run the script if you do this.
This is also why I use the USERNAME environment variable as part of the file name. You can have multiple employees run the first code snippet to generate a separate encrypted file for each of them. Then your script will work successfully when any of them run it.
It also works if you have an account used for a scheduled task for example; run the snippet as that user once, then the scheduled task will work.

remove-computer cmdlet access denied

I am trying create a script to remove a computer from a domain using remove-computer -unjoincredentials domain\admin -passthru However, I consistently receive an error stating that
remove-computer : Failed to unjoin computer 'web140127105714' from domain 'domain.com' with the following error
message: Access is denied.
At line:1 char:1
+ remove-computer -UnjoinDomainCredential domain\admin -PassThru
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (web140127105714:String) [Remove-Computer], InvalidOperationException
+ FullyQualifiedErrorId : FailToUnjoinDomain,Microsoft.PowerShell.Commands.RemoveComputerCommand
The account I am using is a domain administrator with full access. I have confirmed that the account can manually unjoin from the domian.
Some operations on the console require you to be on an elevated PowerShell session. You can start your PowerShell session as Admin by right clicking on it and choosing 'Run as Administrator'. Then run the remove-computer cmdlet in that console session. Default title of the Administrator PowerShell console is 'Administrator : Windows PowerShell'. You can identify the window that way
Sounds like the OP found his answer, so here is a powershell self elevating example for future readers. Add to the top of your scripts and it will re-launch itself elevated so we don't have to right click and 'Run As Administrator'.
$WID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$WIP=new-object System.Security.Principal.WindowsPrincipal($WID);
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator;
If ($WIP.IsInRole($adminRole)){
}else {
$newProcess = new-object System.Diagnostics.ProcessStartInfo 'PowerShell';
$newProcess.Arguments = $myInvocation.MyCommand.Definition
$newProcess.Verb = 'runas'
[System.Diagnostics.Process]::Start($newProcess);Write-Host 'Prompting for Elevation'
exit
}
#####################
# Add Scripts Below #
#####################
Write-Host 'ElevatedCodeRunsHere';
Write-Host 'Press any key to continue...'
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
Powershell start-process script calls a second script - how to make one script only
There is no such parameter as -unjoincredentials
http://technet.microsoft.com/en-us/library/hh849816.aspx