Problem with my script, dont execute

Copper Contributor

Hello to everyone
I have a script that is not working for me and I do not understand why ?, my script tries to run a ping to selected machines as long as the computer is in a valid network to perform the ping and finally gives me a report in a file, in If a ping fails with a machine, I will display an alert window to take actions, but I really do not understand what happens with the script if you can guide me please, thank you very much.

 

+++ Powershell script++++

Add-Type -AssemblyName PresentationCore,PresentationFramework

$names = Get-content "C:\Servers.txt"
$subname=" "
$chequea="no"
$dia = Get-date
$ButtonType = [System.Windows.MessageBoxButton]::OK
$MessageIcon = [System.Windows.MessageBoxImage]::Error
$MessageTitle = "Falla de Alcance por Ping"

#$ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select -ExpandProperty IPV4Address
$ipV4 = (Get-NetAdapter -Physical | where status -eq 'up' | Get-NetIPAddress).IPv4Address 
Write-Host $ipV4.IPAddressToString
#Write-Verbose $ipV4.IPAddressToString

if ($ipV4.GetAddressBytes()[0] -eq "192" -and $ipV4.GetAddressBytes()[1] -eq "168" -and $ipV4.GetAddressBytes()[2] -eq "5" ){
$chequea="si"
}

if ($ipV4.GetAddressBytes()[0] -eq "192" -and $ipV4.GetAddressBytes()[1] -eq "168" -and $ipV4.GetAddressBytes()[2] -eq "6" ){
$chequea="si"
}

if ($ipV4.GetAddressBytes()[0] -eq "10" -and $ipV4.GetAddressBytes()[1] -eq "212" -and $ipV4.GetAddressBytes()[2] -eq "134" ){
$chequea="si"
}

if($chequea -eq "si"){

$Output+="$dia : "
foreach ($name in $names){

 if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
   $Output+= "$name ====>> UP || "
   Write-Host "$name ====>> UP "
   #Write-Verbose "$name ====>> UP "
 }
 else{
    
   $Output+= "$name ====>> DOWN || "
   Write-Host "$name ====>> DOWN "
   #Write-Verbose "$name ====>> DOWN "

   if ($name -eq "8.8.8.8"){
    $subname="DNS Google"
}

if ($name -eq "www.google.com"){
    $subname="Dominio Google"
}

if ($name -eq "192.168.5.1"){
    $subname="Firewall"
}

if ($name -eq "192.168.5.2"){
    $subname="Server 10"
}

if ($name -eq "192.168.5.30"){
    $subname="Server 8"
}

if ($name -eq "192.168.5.29"){
    $subname="Server 9"
}

if ($name -eq "192.168.5.52"){
    $subname="Server 7"
}

if ($name -eq "192.168.6.16"){
    $subname="Server 1"
}

if ($name -eq "192.168.5.94"){
    $subname="Server 2"
}

if ($name -eq "192.168.5.102"){
    $subname="Server 3"
}

if ($name -eq "192.168.5.43"){
    $subname="Server 4"
}

if ($name -eq "192.168.5.124"){
    $subname="Server 5"
}

if ($name -eq "192.168.6.250"){
    $subname="Impresora Wifi"
}

if ($name -eq "192.168.5.250"){
    $subname="Impresora Xerox "
}
   $MessageBody = "Conexion Perdida con el IP: $name$subname"
   $oReturn=[System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)
 }
}
$Output | Out-file "C:\PingResult.txt" -Append
}

 

23 Replies

@Nervill_mcbo  are you getting an error? Or what is not working?

Not working Erick!

@Nervill_mcbo So, you mean no output at all? No error, no results, right? I'm going to try to run it in my system and brb. 

 

Regards

when I set the variable wanting to get the IP value of the active network, it stopped working completely

@Nervill_mcbo I've modified your script to fix the errors that it was throwing for the GetAddressBytes() and the way the array of adapters were listed. 
It is working on my system, so please let me know how it goes now. 

Add-Type -AssemblyName PresentationCore,PresentationFramework

$names = Get-content "C:\Servers.txt"
$subname=" "
$chequea="no"
$dia = Get-date
$ButtonType = [System.Windows.MessageBoxButton]::OK
$MessageIcon = [System.Windows.MessageBoxImage]::Error
$MessageTitle = "Falla de Alcance por Ping"

#$ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select -ExpandProperty IPV4Address
$ipsV4 = $(Get-NetAdapter -Physical | where status -eq 'up' | Get-NetIPAddress | where{$_.AddressFamily -eq 'IPv4'}).IPAddress 

#Write-Verbose $ipV4.IPAddressToString
Foreach($ipV4_tmp in $ipsV4) #added due that multiple Adapter could be up
 {
  $ipV4 = $null
  [System.Net.IPAddress]$ipV4 = $ipV4_tmp
  Write-Host $ipV4.IPAddressToString

  If($ipV4_tmp)
   {
    if ($ipV4.GetAddressBytes()[0] -eq "192" -and $ipV4.GetAddressBytes()[1] -eq "168" -and $ipV4.GetAddressBytes()[2] -eq "5" ){
    $chequea="si"
    }
    
    if ($ipV4.GetAddressBytes()[0] -eq "192" -and $ipV4.GetAddressBytes()[1] -eq "168" -and $ipV4.GetAddressBytes()[2] -eq "6" ){
    $chequea="si"
    }
    
    if ($ipV4.GetAddressBytes()[0] -eq "10" -and $ipV4.GetAddressBytes()[1] -eq "212" -and $ipV4.GetAddressBytes()[2] -eq "134" ){
    $chequea="si"
    }
   }
  Else
   {
    Write-Host "Adapter IP item was empty"
   }
 } 

if($chequea -eq "si"){

$Output+="$dia : "
foreach ($name in $names){

 if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
   $Output+= "$name ====>> UP || "
   Write-Host "$name ====>> UP "
   #Write-Verbose "$name ====>> UP "
 }
 else{
    
   $Output+= "$name ====>> DOWN || "
   Write-Host "$name ====>> DOWN "
   #Write-Verbose "$name ====>> DOWN "

   if ($name -eq "8.8.8.8"){
    $subname="DNS Google"
}
   
   if ($name -eq "www.google.com"){
    $subname="Dominio Google"
}
   
   if ($name -eq "192.168.5.1"){
    $subname="Firewall"
}
   
   if ($name -eq "192.168.5.2"){
    $subname="Server 10"
}
   
   if ($name -eq "192.168.5.30"){
    $subname="Server 8"
}
   
   if ($name -eq "192.168.5.29"){
    $subname="Server 9"
}
   
   if ($name -eq "192.168.5.52"){
    $subname="Server 7"
}
   
   if ($name -eq "192.168.6.16"){
    $subname="Server 1"
}
   
   if ($name -eq "192.168.5.94"){
    $subname="Server 2"
}
   
   if ($name -eq "192.168.5.102"){
    $subname="Server 3"
}
   
   if ($name -eq "192.168.5.43"){
    $subname="Server 4"
}
   
   if ($name -eq "192.168.5.124"){
    $subname="Server 5"
}
   
   if ($name -eq "192.168.6.250"){
    $subname="Impresora Wifi"
}
   
   if ($name -eq "192.168.5.250"){
    $subname="Impresora Xerox "
}
   $MessageBody = "Conexion Perdida con el IP: $name, $subname"
   $oReturn=[System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)
 }
  }#foreach
   $Output | Out-file "C:\PingResult.txt" -Append
  }#If

 
 

 

@Erick A. Moreno R.
It works perfect! I only have one doubt I try to have this script running on the scheduled tasks and it doesn't run, is it not the reason?
 

Hi @Erick

I have a doubt! because the ip of my vpn does not recognize me when I connect, what would the script lack so that when it finds that range of ip it will perform the operation?

this is my ifconfig:


Configuración IP de Windows


Adaptador de Ethernet Ethernet 2:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de Ethernet Ethernet 3:

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::60e9:c265:2745:5140%18
Dirección IPv4. . . . . . . . . . . . . . : 10.212.134.200
Máscara de subred . . . . . . . . . . . . : 255.255.255.255
Puerta de enlace predeterminada . . . . . :

Adaptador de Ethernet Ethernet:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de LAN inalámbrica Conexión de área local* 1:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de LAN inalámbrica Conexión de área local* 10:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de Ethernet VMware Network Adapter VMnet1:

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::1008:6a5e:fda9:67c3%7
Dirección IPv4. . . . . . . . . . . . . . : 192.168.20.1
Máscara de subred . . . . . . . . . . . . : 255.255.255.0
Puerta de enlace predeterminada . . . . . :

Adaptador de Ethernet VMware Network Adapter VMnet8:

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::1931:2147:e0f8:dca7%19
Dirección IPv4. . . . . . . . . . . . . . : 192.168.111.1
Máscara de subred . . . . . . . . . . . . : 255.255.255.0
Puerta de enlace predeterminada . . . . . :

Adaptador de LAN inalámbrica Wi-Fi:

Sufijo DNS específico para la conexión. . : fibertel.com.ar
Dirección IPv4. . . . . . . . . . . . . . : 192.168.0.135
Máscara de subred . . . . . . . . . . . . : 255.255.255.0
Puerta de enlace predeterminada . . . . . : 192.168.0.1

Adaptador de Ethernet Conexión de red Bluetooth:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de Ethernet vEthernet (Default Switch):

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::817e:7ad:5feb:3f15%26
Dirección IPv4. . . . . . . . . . . . . . : 192.168.209.177
Máscara de subred . . . . . . . . . . . . : 255.255.255.240
Puerta de enlace predeterminada . . . . . :
PS C:\Users\LabsXD-1\Documents\DevOps\checkpingPowershell> ipconfig

Configuración IP de Windows


Adaptador de Ethernet Ethernet 2:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de Ethernet Ethernet 3:

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::60e9:c265:2745:5140%18
Dirección IPv4. . . . . . . . . . . . . . : 10.212.134.200
Máscara de subred . . . . . . . . . . . . : 255.255.255.255
Puerta de enlace predeterminada . . . . . :

Adaptador de Ethernet Ethernet:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de LAN inalámbrica Conexión de área local* 1:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de LAN inalámbrica Conexión de área local* 10:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de Ethernet VMware Network Adapter VMnet1:

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::1008:6a5e:fda9:67c3%7
Dirección IPv4. . . . . . . . . . . . . . : 192.168.20.1
Máscara de subred . . . . . . . . . . . . : 255.255.255.0
Puerta de enlace predeterminada . . . . . :

Adaptador de Ethernet VMware Network Adapter VMnet8:

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::1931:2147:e0f8:dca7%19
Dirección IPv4. . . . . . . . . . . . . . : 192.168.111.1
Máscara de subred . . . . . . . . . . . . : 255.255.255.0
Puerta de enlace predeterminada . . . . . :

Adaptador de LAN inalámbrica Wi-Fi:

Sufijo DNS específico para la conexión. . : fibertel.com.ar
Dirección IPv4. . . . . . . . . . . . . . : 192.168.0.135
Máscara de subred . . . . . . . . . . . . : 255.255.255.0
Puerta de enlace predeterminada . . . . . : 192.168.0.1

Adaptador de Ethernet Conexión de red Bluetooth:

Estado de los medios. . . . . . . . . . . : medios desconectados
Sufijo DNS específico para la conexión. . :

Adaptador de Ethernet vEthernet (Default Switch):

Sufijo DNS específico para la conexión. . :
Vínculo: dirección IPv6 local. . . : fe80::817e:7ad:5feb:3f15%26
Dirección IPv4. . . . . . . . . . . . . . : 192.168.209.177
Máscara de subred . . . . . . . . . . . . : 255.255.255.240
Puerta de enlace predeterminada . . . . . :

Regards.

@Nervill_mcbo 

What is the status when you run it through the task scheduler?

If I have to guess I would say it could be permissions issue as you are trying to write directly to C: other than that it depends on the environment. 

 

Regards

I change the path to this C: \ Users \ LabsXD-1 \ Documents \ checkpingPowershell
the error in the scheduled task is 0x41303 and it stays in running state and never runs and never ends

@Nervill_mcbo could you try to run it, with the argument -NonInteractive in the task scheduler? and see what is the result. 

 

Regards

Erick

It remains the same as the following program: Powershell argument: -NoneInteractive C: \ Users \ LabsXD-1 \ Documents \ checkpingPowershell \ CheckPing.ps1

@Nervill_mcbo It is weird, I have created a task to test it and its working fine, even without the additional argument. I'm attaching my settings in the tasks in case we have something different that could be messing with yours, probably playing with the time when the task first runs can help to clear that error.

For your question about the VPN, If I understood your question correctly you can use the task scheduler option to run it only when a specific connection is available and there you can select the one that corresponds to your VPN. 


Hello, what I am trying to do with the script is to check which of the NICs is in an up state and also contains one of the 3 network segments configured to run so that when detecting some of the IPSs the script is executed

@Nervill_mcbo Understand. Were you able to run it in the task scheduler? 

 

Regards

Copy your images and configure it, even though I think that the execution does not happen as I expect, when I check the result in the task it is always different from 0x0

@Nervill_mcbo After testing on a different machine I found something that may help. 
Please use the arguments -noninteractive -file "Pathtoscript.ps1" don't forget the quotes for your path as you can see in the attached ss. Also, I have removed the popup window as it was preventing the task from completing.  

 

#Start-Transcript -Path "C:\transcriptPing.txt" -Force

#Add-Type -AssemblyName PresentationCore,PresentationFramework

$names        = Get-content "C:\Servers.txt" #@('192.168.50.1','192.168.50.2','8.8.8.8')#
$subname      = $null
$chequea      = "no"
$dia          = Get-date
#$ButtonType   = [System.Windows.MessageBoxButton]::OK
#$MessageIcon  = [System.Windows.MessageBoxImage]::Error
#$MessageTitle = "Falla de Alcance por Ping"

$ipsV4 = $(Get-NetAdapter -Physical | where status -eq 'up' | Get-NetIPAddress | where{$_.AddressFamily -eq 'IPv4'}).IPAddress 

Foreach($ipV4_tmp in $ipsV4) #added due that multiple Adapter could be up
 {
  $ipV4 = $null
  [System.Net.IPAddress]$ipV4 = $ipV4_tmp
  Write-Host "Local Adapter ip" $ipV4.IPAddressToString -ForegroundColor Cyan

  If($ipV4_tmp)
   {
    if ($ipV4.GetAddressBytes()[0] -eq "192" -and $ipV4.GetAddressBytes()[1]  -eq "168" -and $ipV4.GetAddressBytes()[2] -eq "5" ){
    $chequea="si"
    }
    
    if ($ipV4.GetAddressBytes()[0] -eq "192" -and $ipV4.GetAddressBytes()[1] -eq "168" -and $ipV4.GetAddressBytes()[2] -eq "6" ){
    $chequea="si"
    }
    
    if ($ipV4.GetAddressBytes()[0] -eq "10" -and $ipV4.GetAddressBytes()[1] -eq "212" -and $ipV4.GetAddressBytes()[2] -eq "134" ){
    $chequea="si"
    }
   }
  Else
   {
    Write-Host "Adapter IP item was empty"
   }
 } 

if($chequea -eq "si")
 {
  $Output += "$dia : "
  foreach ($name in $names)
   {
    if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue)
     {
    $Output+= "$name ====>> UP || "
    Write-Host "$name ====>> UP "
   }
    else
     {
    $Output+= "$name ====>> DOWN || "
    Write-Host "$name ====>> DOWN "
    #region Conditions
   if($name -eq "8.8.8.8")
    {
     $subname="DNS Google"
    }
   if($name -eq "www.google.com")
    {
     $subname = "Dominio Google"
    }
   if($name -eq "192.168.5.1")
    {
     $subname="Firewall"
    }
   if($name -eq "192.168.5.2")
    {
     $subname="Server 10"
    }
   if($name -eq "192.168.5.30")
    {
     $subname="Server 8"
    }
   if($name -eq "192.168.5.29")
    {
     $subname="Server 9"
    }
   if($name -eq "192.168.5.52")
    {
     $subname="Server 7"
    }
   if($name -eq "192.168.6.16")
    {
     $subname="Server 1"
    }
   if($name -eq "192.168.5.94")
    {
     $subname="Server 2"
    }
   if($name -eq "192.168.5.102")
    {
     $subname="Server 3" 
    }
   if($name -eq "192.168.5.43")
    {
     $subname="Server 4"
    }
   if($name -eq "192.168.5.124")
    {
     $subname="Server 5"
    }
   if($name -eq "192.168.6.250")
    {
    $subname="Impresora Wifi"
    }
   if($name -eq "192.168.5.250")
    {
     $subname="Impresora Xerox "
    }
   #endregion
    #$MessageBody = "Conexion Perdida con el IP: $name, $subname"
    #$oReturn=[System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)
    }#If
   }#foreach
   $Output | Out-file "C:\PingResult.txt" -Append
 }#If

  #Stop-Transcript

 
 
Ok, but what solution could be applied to return an alert identifying me the IP and name of the service dropped in this case? since popus cause a problem with the task.

@Erick A. Moreno R. 

 

I'm throwing this error with the code you send me

 

Get-content : No se encuentra la ruta de acceso 'C:\Servers.txt' porque no existe.
En C:\Users\LabsXD-1\Documents\DevOps\checkpingPowershell\CheckPing.ps1: 5 Carácter: 17
+ $names = Get-content "C:\Servers.txt" #@('192.168.50.1','192.1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Servers.txt:String) [Get-Content], ItemNot
FoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Local Adapter ip 192.168.6.32
Out-file : Acceso denegado a la ruta de acceso 'C:\PingResult.txt'.
En C:\Users\LabsXD-1\Documents\DevOps\checkpingPowershell\CheckPing.ps1: 117 Carácter: 14
+ $Output | Out-file "C:\PingResult.txt" -Append
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

@Nervill_mcbo For the error: You have to update the location of the server's file as it is looking for C:\servers.txt

The alternatives; Save a file containing all the IPs that did not respond or send an email notifying about it at the end. 

I can help you with that later, just confirm that after modifying the server's file location the script is able to complete using the task scheduler after that we can add functionality to the script as needed.