Powershell : Executing a batch file on remote machines


Do you have a batch file which you want to run on multiple remote machines? The below powershell script can simplify this task. I have used this script to remotely repair SCCM client on multiple machines by executing batch files.

The steps are quite simple
  • Copy the below code to powershell script file.
  • Provide list of machines in computers.txt file in same folder where you kept the script.
  • Copy your batch file ‘MyFile.bat’  in same folder.
  • Run the script.

    Code:

#Get current path
$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$Inputfile = $directorypath + "\computers.txt"
$BatchFile = "c:\windows\temp\MyFile.bat"
$source = $directorypath + "\Myfile.bat"
 Get-Content $inputfile | ForEach-Object {
    $computer = $_
    $TargetPath = "\\$computer\admin$\temp\"
    Write-Host  "==============================="
     #Copy source
    if (Test-Path -Path $targetPath)
      {
       Copy-Item -Path $source $targetPath -force
      #Run batch file
       Write-Host "$computer : Executing batch file $batchfile"
       ([WMICLASS]"\\$computer\ROOT\CIMV2:win32_process").Create("cmd.exe `/c $BatchFile")
      }
    else
      {
       Write-host "$computer : Unable to connect"
      }
}
 Write-Host "Finished execution.Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")




Comments

Popular posts from this blog

SCCM Software Distribution Troubleshooting

Powershell - List AD Organizational Unit and GPOs linked to them

Troubleshooting System Center Endpoint Protection (SCEP) Client