Howto use psexec via powershell invoke-command on a remote computer? (invalid handle)
04:32 19 May 2014

I have written a powershell script which creates a powershell script or a batch script depending on the remote host on which this script should be started remotely (either via powershell invoke-command or psexec).

The script creates either a powershell or a batch script, because not all hosts on which these created scripts should be run support WinRM (Windows Remote Management).

The created scripts include some psexec lines which executes a command on another remote host. The created batch script works as expected, but from the created powershell script i get the following errors from the psexec calls.

NotSpecified: (:String) [], RemoteException
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : 

PsExec v2.1 - Execute processes remotely
Copyright (C) 2001-2013 Mark Russinovich
Sysinternals - www.sysinternals.com
The handle is invalid.
Access is denied.
Connecting to 10.XXX.XXX.127...Couldn't access 10.XXX.XXX.127:
Starting PSEXESVC service on 10.XXX.XXX.127...Could not start PSEXESVC service on 10.XXX.XXX.127:
Connecting to 10.XXX.XXX.127...Starting PSEXESVC service on 10.XXX.XXX.127...

Here is a small overview of what is done:

  1. Powershell script on deployment host creates the rollout script (ps1 or batch) depending on the destination host
  2. Powershell script on deployment host starts the created rollout script on the destination host
    • Powershell will be started via Invoke-Command -ComputerName -FilePath -Authentication default
    • Batch will be started via & psexec.exe \\ -n 60 -accepteula -c -f
  3. Created rollout script on the destination host executes a psexec command to start a service on a third host (this fails only if the rollout script is powershell)

This is the psexec command which fails if executed via a remotely started powershell script.

& psexec.exe \\ -n 60 -accepteula -u -p net stop

The same command psexec.exe \\ -n 60 -accepteula -u -p net stop executed via a remotely started batch script works without problems.

Update #1

Also if i connect to the destination host with rdp and start a powershell shell and paste the command it works without issues. The problem only occurs if started remotely.

I already tried the following variants of starting psexec, all without luck!

  1. & psexec.exe \\ -n 60 -accepteula -s -u -p net stop
  2. Start-Process cmd.exe -Credential "\" -WorkingDirectory $env:systemdrive -ArgumentList "/C psexec.exe \\ -n 60 -accepteula -u -p net stop "
  3. Start-Process powershell.exe -WorkingDirectory $env:systemdrive -Verb Runas -ArgumentList "cmd.exe /C psexec.exe \\ -n 60 -accepteula -u -p net stop "
windows batch-file powershell psexec