0

I need to remotely run powershell commands on multiple windows servers using SysInternal tools but I tried a lot but it seems not to work . Any help is highly appreciated .

Servers.csv (file content)

10.10.10.100
10.0.0.111

Code :

$List = Import-CSV -Path "C:\Users\javed\Desktop\New\servers.csv"

foreach ($entry in $List) {
if (test-Connection -Cn $($entry.Name) -quiet) {
    & C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u "$($entry.Name)\Admin" -p 'P@ssword' -accepteula  cmd /c " HostName >> C:\Users\javed\Desktop\New\Script.log"
} else {
    "$computer is not online" >> C:\Users\javed\Desktop\New\Script.log
}
}

Output :

PS C:\Users\javed> C:\Users\javed\Desktop\New\Change-NetworkRoute.ps1

PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com

psexec.exe : The handle is invalid.
At C:\Users\javed\Desktop\New\Change-NetworkRoute.ps1:26 char:9
+         & C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u "$( 
...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (The handle is invalid.:String) [], Re 
   moteException
    + FullyQualifiedErrorId : NativeCommandError

Connecting to 10.10.10.100...Couldn't access 10.10.10.100:
Connecting to 10.10.10.100...

PS C:\Users\javed> 
Javed Eqbal
  • 63
  • 1
  • 2
  • 11

1 Answers1

1

Apparently your command line isn't completely evaluated, note that PSExec shows \\$($entry.Name) in the error rather then the actual name.
The correct way to troubleshoot this is to put the first put the command is a variable, show the variable, and then execute it:

$CommandLine = "C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u ..."
Write-Host $CommandLine # Confirm that this is the command line you expect
if (test-Connection -Cn $($entry.Name) -quiet) {
    &$CommandLine
} else {

Anyhow, it is a bad idea to use an external command line as PSExec including credentials to achieve something like this. Instead, I would use WMI to retrieve the actual name of the servers. Something like this:

$SPAdmin = "$($entry.Name)\Admin"
$Password = "P@ssword" | convertto-securestring 
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $SPAdmin, $Password 
$Computer = Get-WmiObject -Class Win32_Computersystem -ComputerName $entry.Name -Credential $Credential
Write-Host $Computer.Name
iRon
  • 20,463
  • 10
  • 53
  • 79