I'm working on a generic/common PS script that I can use to execute other scripts remotely on multiple machines. Using psexec for this. I know there are other ways to do it but psexec seems to be the most reliable in my scenario.
Here is an excerpt of what I initially tried:
SWITCH ($ScriptExt) {
'.bat' {$ShellCmd = 'CMD /C'}
'.cmd' {$ShellCmd = 'CMD /C'}
'.ps1' {$ShellCmd = 'powershell -ExecutionPolicy Unrestricted -File'}
[...]
}
}
Get-Content $PcList | ForEach-Object {
& "$PSScriptRoot\..\psexec.exe" \\$_.$Domain -u $Domain\$AdminUser -p $AdminPassword -h -i $ShellCmd $ScriptPath $ScriptArgs ## Does NOT work...
[...]
}
This does not work: psexec errors out every time telling me it can't run the program on the remote PC even though the path it provides looks correct.
Also tried to add some quotes within the ForEach:
& "$PSScriptRoot\..\psexec.exe" "\\$_.$Domain -u $Domain\$AdminUser -p $AdminPassword -h -i $ShellCmd $ScriptPath $ScriptArgs" ## Does NOT work...
...and various other iterations to try to get this to work.
After doing more troubleshooting, I found that it was the $ShellCmd variable that was causing the issue. If I hard-code that portion in the ForEach, like so:
& "$PSScriptRoot\..\psexec.exe" \\$_.$Domain -u $Domain\$AdminUser -p $AdminPassword -h -i powershell -ExecutionPolicy Unrestricted -File $ScriptPath $ScriptArgs
...it works but it's a hack.
Anyone know what I might be doing wrong with syntax? Comparing my working and non-working examples, there is very little difference except I'm trying to use the $ShellCmd variable in one.