Don't Do This: PSExec'ing a Batch Script Containing a PowerShell Script

This is just broken, but  broken times call for broken measures.  I'm stuck on PSH V1 for reasons best left unmentioned (or maybe it's unmentionable reasons.)  To run remote commands, I don't have remoting at my disposal - I'm stuck with SysInternal's PSExec.exe.

As shown in Lee Holmes' blog,  you have to perform some hackosity to run a script remotely:

\\path\to\psexec.exe \\computerName cmd /c "echo . | powershell \\path\to\script.ps1"

This means you can't use PSExec.exe's -c option to copy the file over, so you have to manually copy the script over.

Here's my 'solution' (to use the term exceptionally loosely):


echo @"
@echo off && copy /y %~f0 %~f0.ps1 >NUL 2>&1
echo . | powershell -nologo -noprofile %~f0.ps1 %*
del /f /q %0.ps1 >NUL 2>&1 && exit /b 0
"@ | out-null;
$args = [Environment]::GetCommandLineArgs();
$scriptName = $args[3];
$args = $args[4..($args.Count - 1)];

"rest of script goes here"
$scriptname
$args


Yeah.  Hack-n-slash scripting.

Comments

  • Anonymous
    June 22, 2011
    Oh, and there's a PSH V2 way that's much cleaner from http://poshcode.org/2447 :: <# copy %0 %0.ps1 PowerShell.exe -ExecutionPolicy Unrestricted -NoProfile -Command "$ErrorActionPreference = 'SilentlyContinue'; . %0.ps1; Remove-Item %0.ps1" exit :: #> $ErrorActionPreference = 'Continue'

Your PowerShell script goes below here.

I've put a couple of lines as an example ...

ls | sort length -desc | select -first 5 | ft ps | sort ws -desc | select -first 10 | ft

  • Anonymous
    July 13, 2015
    Yep!! It worked!! I'm ridiculously greatful. Goal: My goal was to deploy my ps via sccm. I kept getting errors. Solution: Exactly what you stated... Place the following above the ps and change to cmd...and deploy cmd :: <# copy %0 %0.ps1 PowerShell.exe -ExecutionPolicy Unrestricted -NoProfile -Command "$ErrorActionPreference = 'SilentlyContinue'; . %0.ps1; Remove-Item %0.ps1" exit :: #> $ErrorActionPreference = 'Continue'