Use Powershell to run Psexec command Use Powershell to run Psexec command powershell powershell

Use Powershell to run Psexec command


Ok, let's take it from the top then.

$computers = gc "C:\scripts\computers.txt"

That loads the contents of the "computers.txt" file into the variable $computers. Simple enough, no issues there.

Next we have a ForEach loop. It splits up the contents of $computers and processes each line (presumably the name of a computer) as $computer against all the code within the curly braces.

foreach ($computer in $computers) {

That loop starts up with a standard If-Then statement. If (condition) then {do stuff}. In this case it is testing to see if the $computer is available on the network. If it is, then it attempts to run PSExec on it. If it isn't online it runs the Else clause, we'll get to that in a second.

if (test-Connection -Cn $computer -quiet) {

Then it changes directory. Kind of pointless, but ok, whatever. You could have just called it explicitly, such as C:\PSTools\PSExec.exe <arguments> and saved a line, but there's really no harm done.

cd C:\pstools

Then you are calling PSExec, though there's a little syntax error here. It should be $computer and not %computer. Also, it should just have the command you want to execute, not cmd and the command on a second line. You may have better results if you use the Call operator (&) to make powershell realize that it's trying to execute something and not run a cmdlet or function or what not.

& psexec \\$computer C:\Folder\install.bat

After that is the Else clause that says if the computer isn't online to write the string "$computer is not online" followed by closing braces for the Else clause and the ForEach loop.

} else {    "$computer is not online"}}

Edit: Ok, your finished script should look something like this (enclosed target in quotes in case there are spaces in the path):

$computers = gc "C:\scripts\computers.txt"foreach ($computer in $computers) {    if (test-Connection -Cn $computer -quiet) {        & C:\pstools\psexec.exe \\$computer "C:\folder\install.bat"    } else {        "$computer is not online"    }}


I realize this question is from 2014, and this answer will not directly address the question the user asked. But for people who come across this question these days, I want to throw out there that you don't need* to use PSExec if you're using PowerShell. Since you're already in PowerShell, just use Invoke-Command.

Syntax would be

Invoke-Command -ComputerName $Computer -ScriptBlock { C:\Folder\install.bat }

It's really that easy.

*Requires PowerShell remoting to be enabled on the target server.


Give this a try. You had a % where you wanted a $. Also the cmd.exe call is unnecessary.

    $computers = gc "C:\scripts\computers.txt"foreach ($computer in $computers) {if (test-Connection -Cn $computer -quiet) {    cd C:\pstools    psexec \\$computer "C:\Folder\install.bat"} else {    "$computer is not online"}}