First post so please don't hurt me. I've searched around but can't seem to find a way to do what I want. I've made a script that copies a folder I have to numerous computers at \$computer\c$. In these folders is a batch file that runs an .exe. What I want to do is have Powershell pull from the same computers.txt that I used to copy the folder and then use psexec to run the batch file. I could do this all manually but scripting it seems to be a problem, here's what I thought would work but apparently not.
$computers = gc "C:\scripts\computers.txt"
foreach ($computer in $computers) {
if (test-Connection -Cn $computer -quiet) {
cd C:\pstools
psexec \\%computer cmd
C:\Folder\install.bat"
} else {
"$computer is not online"
}
}
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"
}
}