Run remote process by powershell - powershell

I have the following line of code to create object to access to a remote server before I associate it with user name, password and process:
$process = [WMIClass]"\\remoteServer\ROOT\cimv2:Win32_Process"
I tried this on two PCs, one is OK without any errors, but another one I am going to run has an exception:
Cannot convert value "\\remoteServer\ROOT\cimv2:Win32_Process" to type "System.Manage
ment.ManagementClass". Error: "Access is denied. (Exception from HRESULT: 0x800
70005 (E_ACCESSDENIED))"
The remoteServer is the same one. Not sure what I have to set on local PC or remote PC to make this work? On both client PCs, the user names are all member of Administrators.

Have you considered looking into PowerShell remoting? If your running PowerShell 2.0 I'd recommend that you take a look at it. Once you have set up remoting you'll be able to execute commands on the remote server using the Invoke-Command:
Invoke-Command -ComputerName {serverName} –ScriptBlock { commands }
The ScriptBlock can contain any powershell commands so you will be able to start processes on the remote machine with this mechanism. To enable remoting you'll need to use the Enable-PSRemoting cmdlet and you can get details of this at http://blogs.msdn.com/powershell/archive/2009/04/30/enable-psremoting.aspx and http://technet.microsoft.com/en-us/library/dd819498.aspx

Is there some reason you don't want to use psexec?
http://technet.microsoft.com/en-us/sysinternals/bb545027.aspx

I know this is an old post, but what I think you need to do is run the following command on the remote machine:
"Get-ExecutionPolicy"
it sounds like its set to "Restricted" which means it will not run any "Invoke-Commands" commands, or remote scripts.
You can change it to 1 of 7 options:
Unrestricted____(least secure but if you need to troubleshoot set this option)
RemoteSigned__(will only all scripts with a signature, this a so so option)
AllSigned______(Best option if youu need to run remote scripts, but all will beed signed)
Restricted_____(I believe this option is set by default in windows 7 nad WS2k8)
Default
Bypass
Undefined

Related

Triggering a remote powershell script to run independently

I've created a script which calls 'dfsutil', and is available for all the members in my team. Some members don't have RSAT (dfsutil) installed locally, so I'd like to 'trigger' a .ps1 script independently of the source PC (PC1) to be run on a server (Server1) which has 'dfsutil' installed.
It's easy enough to trigger a remote PowerShell script from the source 'PC1' by dot-sourcing it from 'myscript.ps1':
. \\Server1\scripts\dfsscript.ps1
As we already know, the above will fail as PowerShell is looking for 'dfsutil' locally on PC1, rather than on the server 'Server1'.
'dfsscript.ps1' has been written so it can be run independently, without need to return the values to PC1.
I can't seem to find any documentation which shows how to initialise a remote script which only uses the values and conditions of the OS it was triggered on.
Any thoughts?
Dot-sourcing is about the scope of a PowerShell session, but doesn't include the computing environment, so what you are doing won't get the script on Server1 to run from Server2, but still act like it is on Server1 with access to all of Server1's installed apps, etc.
What you need to do is use PowerShell remoting to actually run the script on the remote server (i.e. trigger from Server2, but execute on Server1). For example:
Invoke-Command -ComputerName Server1 -FilePath <path>\script.ps1

Starting Service on remote server failed

I encounter strange behavior when trying to remotely start a service.
on Server A i'm running this line (it's part of bigger script named RunRemoteService.ps1):
Invoke-Command -ComputerName $B_comp -ScriptBlock {Powershell.exe -File "run_service.ps1"} -Credential $cred
And the script run_service.ps1 contains the following line (it's also part of bigger script):
$my_service_name.Start()
Now here's the strange thing, If I run RunRemoteService.ps1 when I have an open remote connection (mstsc) to server B then the script works perfectly and the required service on B is really starting.
However, if I run RunRemoteService.ps1 when there is no mstsc connection with server B then the script failed (service doesn't start).
Why is this happening and how can it be resolved?
EDIT: I explored this issue a bit more and found out that this occurs only when trying to run my specific service.
that means that my service must run from a session of already logged on user (that is why it's working if I mstsc to the server before).
So I guess my new question is - is there a way I can login to remote machine from powershell?
Thanks.
If you cannot use Credential delegation as suggested by #EBGreen. Try using psexec.exe for calling the script instead of PowerShell remoting.
psexec \\server "cmd /c powershell.exe -f c:\script.ps1"
Get psexec from sysinternals.com
Ok, so my question had evolved and modified on the fly so this solution is to the latest issue I had which is - I couldn't remotely start my service if no user is logged on to remote machine.
The solution is a workaround:
I configured auto-login (using sysinternals auto-login tool) on remote server.
I used Restart-Computer cmdlet at the beginning of the test.
Now after the restart is complete and ps-session is restored, user is logged in automatically to server and I can remotely start my service.
Thanks.

Run specific commands in PowerShell under different credentials?

I am trying to run a specific command line function in my PowerShell script. The catch is the command needs elevated permissions to be able to execute.
Here is a condensed example:
# PowerShell code...
query session /server:"SERVERNAME" #NEEDS ELEVATED PERMISSIONS
# More PowerShell code
The query command needs to be run under elevated permissions.
I have tried the following:
Invoke-Command -ScriptBlock {
query session /server:"SERVERNAME"
} -Credential get-credential
But this doesn't work because the -ComputerName parameter needs to be present when using a -Credential parameter. I want to be able to run this without using a remote server.
I know I can get around it by having the users start up PowerShell under their elevated account credentials, but I'd rather just prompt for credentials while the script runs and just run that single command under their administrator account credentials. Everything else the script does is fine under normal credentials.
There are some add-ins for PowerShell, but I actually found the simplest way was to:
Sysinternals in regular command line
With the PSexec process, you can pass IP address, usermame, and password
Fiddle with it to a point you're happy
Create a batch file to then run from PowerShell if that is the desired deploy to environment
When creating the method, have it consume parameters if you want the call out to be dynamic and consume different usernames/passwords/IP addresses to log into
If the exec will always run on "computerA" using "loginA" and "pwA" then there is obviously no need to parameterize
*Sysinternals cannot be used to outright hack a terminal. The user of a remote exec must first have the same Sysinternals tools installed to the system that is to accept remote executables, that tool must be opened once and given GUI-based approval to allow run on said system must be physically addressed.
Note: Any remote PSexec's using credentials will execute with the same level of permissions that the provided username/password is granted on that system.
Here is the link: (PsExec v2.2). Although I recommend going a level or two up and downloading the entire toolbox.

Execute remote quiet MSI installs from Powershell

I am trying to use the Invoke-Command powershell cmdlet to install a MSI installer. From within powershell on the local machine and from the proper directory, the following works:
./setup /quiet
The following does not seem to work:
$script =
{
param($path)
cd "$path"
& ./setup /quiet
return pwd
}
return Invoke-Command -ComputerName $product.IPs -ScriptBlock $script -Args $sourcePath
For test purposes I am working on the local machine passing in "." for the -ComputerName argument. The paths have been verified correct before passing in to Invoke-Command, and errors generated on different versions of this code indicate the paths are correct. I have also tried with and without the "& " on the remote call to setup. Other Invoke-Command calls are working, so I doubt it is a permissions issue. I have verified that the return from the pwd call is the expected directory.
How do I get the install to work?
What error (if any) are you receiving? Unfortunately, you must run the shell as admin on your local machine to be able to connect to your local machine with invoke-command or any WINRM based command that requires administrative privilege (this is not a requirement when connecting remotely).
When connecting to loopback, I believe it is unable (for some security reason) to enumerate groups and determine if you are in an admin enabled AD or local group, which is how it auto elevates when invoking on a remote machine. The only solution may be to have a conditional which checks for localhost and if so, don't use the -ComputerName parameter.
This GitHub Issue covers it
You might try using Start-Process in your script block:
cd $path
start-process setup.exe -arg "/quiet"
Not sure if you will want or need to wait. Look at help for Start-Process.
I have had weird issues when trying to remotely execute a script on a local machine. In other words, remote powershell to the local machine. It comes back with an error that seems to say that PowerShell remoting is not enabled on the machine, but it was. I can run the script remotely from another machine to the target, but when using remoting to the same box, the issue crops up.
Verify that the WinRM service is running.
Verify powershell remoting has been enabled as in Enable-PSRemoting -force.
Verify your powershell execution policy is loose enough as in Set-ExecutionPolicy Unrestricted, for example. If the policy was set to RemoteSigned, this might be the problem.
You might also want to verify the user you are running the script as (locally, but using remoting) has privileges to "log on as a service" or as a batch job. Just guessing there, if the above list doesn't solve anything.

Access denied exception when trying to execute an exe on remote machine

I am trying to execute an exe on machine B from machine A. I have logged on to machine A as userx and trying to run the exe on machine B as usery.
usery is system admin on machine A as well as B.
i tried using PsExec to execute an exe as well as invoke-command to execute a script in both the case am getting access denied exception in spite on passing credential of usery in both case
invoke-command -computername "machineB" -scriptBlock { c:\psscript.ps1 } -credential $useryCred
psExec \\machineB c:\exec.exe -u usery -p ypass
what am i doing wrong ?
Update:
simple scripts gets executed with out any hassle but this script is trying to create a process on remote machine under the userY's credential !
is it something related to mapping of incoming request to different user say guest ?
regards,
jeez
are there 3 machine's involved? it sounds like you are remoting from A to B and the script on B is remoting to C - is that right?
How are you supplying the credentials (for userY)?
I wonder if it's double hop related... if it is and your on windows 2008 you can try using CredSSP.
Here's some links to help explain it better than I would:
http://www.ravichaganti.com/blog/?p=1230
http://blogs.msdn.com/b/powershell/archive/2008/06/05/credssp-for-second-hop-remoting-part-i-domain-account.aspx
http://blogs.msdn.com/b/clustering/archive/2009/06/25/9803001.aspx
and Get-Help credssp displays the commands that you'll need.
HTH,
Matt