Es folgt der letzte Artikel meiner kleinen Reihe zum PowerShell-Skript NetSendAll: das eigentliche Script, das die Nachricht versendet. Es nutzt die beiden vorgestellten Funktionen PingPC und ReadTextFile um die aus der Textdatei eingelesenen PCs anzupingen. Bei Erfolg wird die Nachricht gesendet bzw. der Nachrichtendienst gestartet, falls dieser nicht läuft. In letzterem Fall wird dann später erneut versucht, die Nachricht zu senden.
# Sends a message to every PC in a text file via "net send"
# ---------------------------------------------------------------------------- #
# the text file containing the PCs
$filePCsOnline = "PCs.txt";
# ---------------------------------------------------------------------------- #
# the script needs only the message as a parameter
if ($args.count -ne 1)
{
write-host ("Usage: .\" + $MyInvocation.MyCommand + " ""this is the message""") -foregroundcolor "red";
exit;
}
$message = $args[0];
# these arrays will be filled with PCs to ping/notify
$pcsOnline = ReadTextFile $filePCsOnline;
$pcsTryAgain = @();
write-host ("Sending the following message to " + $pcsOnline.length + " PCs:`n " + $message);
# find out if PCs are online and notify them resp. enable messenger if disabled
foreach ($pc in $pcsOnline)
{
if (PingPC($pc.Name))
{
$svc = gwmi win32_service -computername $pc.Name | ? { $_.name -eq "Messenger" }
if ($svc.state -eq "Running")
{
write-host ("Messenger is running. Sending message to " + $pc.Name) -foregroundcolor "green";
net send $pc.Name $message
}
else
{
write-host ("Messenger is not running on " + $pc.Name + ". Starting it...") -foregroundcolor "magenta";
[void]$svc.startservice();
$pcsTryAgain += $pc;
}
}
else
{
write-host ($pc.Name + " is offline") -foregroundcolor "red";
}
}
if ($pcsTryAgain.length -gt 0)
{
write-host ("" + $pcsTryAgain.length + " PCs with disabled Messenger will be tried again in 5 seconds");
for ($i = 1; $i -le 5; $i++)
{
write-host $i;
sleep(1);
}
foreach ($pc in $pcsTryAgain)
{
if (PingPC($pc.Name))
{
$svc = gwmi win32_service -computername $pc.Name | ? { $_.name -eq "Messenger" }
if ($svc.state -eq "Running")
{
write-host ("Messenger is running. Sending message to " + $pc.Name) -foregroundcolor "green";
net send $pc.Name $message
}
else
{
write-host ("Messenger is not running on " + $pc.Name + ".") -foregroundcolor "red";
}
}
else
{
write-host ($pc.Name + " is offline") -foregroundcolor "red";
}
}
}
Download
Das Script inkl. der beiden benötigten Funktionen gibt es hier zum Download: NetSendAll.ps1