Scripts/Invoke-WOLWakeComputer.ps1
Function Invoke-WOLWakeComputer { <# .SYNOPSIS Send a magic packet to a computer .DESCRIPTION Send a magic packet to a computer using its host name (if saved on the database) or MAC address .PARAMETER ComputerName Name of the computer to wake up .PARAMETER MACAddress MAC address of the computer to wake up .PARAMETER Port The port to use to send the magic packet (optional) .EXAMPLE Invoke-WOLWakeComputer -ComputerName LabPC2064 .EXAMPLE Invoke-WOLWakeComputer -ComputerName LabPC2064 -Port 9 .EXAMPLE Invoke-WOLWakeComputer -MACAddress 00:01:02:AA:BB:CC .EXAMPLE Invoke-WOLWakeComputer -ComputerName LabPC2064 -MACAddress 00:01:02:AA:BB:CC .NOTES A combination of computer names and MAC addresses can be used, the magic packet will be sent individually .LINK N/A #> [CmdletBinding ()] Param( [Parameter(Mandatory = $False, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True, HelpMessage = 'Enter computer name' ) ] [String[]]$ComputerName, [Parameter(Mandatory = $False, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True, HelpMessage = 'Enter MAC address' ) ] [String[]]$MACAddress, [Parameter(Mandatory = $False, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True, HelpMessage = 'Enter port' ) ] [ValidateSet(0, 7, 9, 2114)] [Int]$Port = 2114 ) BEGIN { Function Send-MagicPacket { Param ( [String]$Host, [String]$HostMAC ) $Host = $Host.toUpper() $HostMAC = $HostMAC.toUpper() If ($HostMAC -notmatch '^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$') { [PsCustomObject]@{ 'Computer' = $Host 'MACAddress' = $HostMAC 'Status' = 'MAC address not formatted properly' } } Else { $UDPClient = New-Object System.Net.Sockets.UdpClient $MACEntry = $HostMAC.Split('-:') | ForEach {[Byte]"0x$_"} $Packet = [Byte[]](, 255 * 6) + ($MACEntry * 16) $UDPClient.Connect(([System.Net.IPAddress]::Broadcast), $Port) [Void]$UDPClient.Send($Packet, $Packet.Length) [PsCustomObject]@{ 'Computer' = $Host 'MACAddress' = $HostMAC 'Status' = 'Magic packet sent' } $UDPClient.Close() $UDPClient.Dispose() } } } PROCESS { ForEach ($Computer In $ComputerName) { $Path = $MyInvocation.MyCommand.Module.ModuleBase + '\System.Data.SQLite.dll' Add-Type -Path $Path $DBConnect = New-Object -TypeName System.Data.SQLite.SQLiteConnection $DBConnect.ConnectionString = "Data Source = $env:ALLUSERSPROFILE\PSWakeOnLAN\WOLDatabase.db3" $DBConnect.Open() $SQL = $DBConnect.CreateCommand() $SQL.CommandText = "SELECT * FROM Computers WHERE Computer = ""$Computer""" $Adapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $SQL $Data = New-Object System.Data.DataSet $Records = $Adapter.Fill($Data) If ($Records -eq 0) { [PsCustomObject]@{ 'Computer' = $Computer 'MACAddress' = '' 'Status' = 'Not in database' } } Else { Send-MagicPacket -Host $Computer -HostMAC $Data.Tables.Rows.MAC } $SQL.Dispose() $DBConnect.Close() } ForEach ($MAC In $MACAddress) { Send-MagicPacket -Host $MAC -HostMAC $MAC } } END {} } |