Created
January 29, 2021 06:56
-
-
Save glennsarti/486be8ed7b46530b83a3dbaf6441b685 to your computer and use it in GitHub Desktop.
Telstra Network Trigger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#requires -Version 7.0 | |
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) | |
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { | |
Throw "This script must be run elevated!" | |
Exit 1 | |
} | |
$BT = Get-Module -name 'BurntToast' -ListAvailable -ErrorAction SilentlyContinue | |
if ($null -eq $BT) { | |
Install-Module 'BurntToast' -Scope CurrentUser | |
Write-Host "Installed BurntToast module..." | |
} else { Write-Host "Burnt Toast is already installed" } | |
$VBScriptPath = Join-Path $ENV:LOCALAPPDATA 'telstra-nic-trigger.vbs' | |
@' | |
Dim objShell | |
Dim scriptdir | |
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) | |
Set objShell = WScript.CreateObject("WScript.Shell") | |
cmd = "pwsh.exe -NoLogo -NoProfile -File """ + scriptdir + "\telstra-nic-trigger.ps1""" | |
For i = 0 To WScript.Arguments.Count - 1 | |
cmd = cmd + " """ + WScript.Arguments(i) + """" | |
Next | |
objShell.Run cmd, 0, True | |
'@ | Set-Content -Path $VBScriptPath -Encoding 'utf8' -Confirm:$False -Force | Out-Null | |
Write-Host "Installed $VBScriptPath" | |
$PS1ScriptPath = Join-Path $ENV:LOCALAPPDATA 'telstra-nic-trigger.ps1' | |
@' | |
param( | |
[String]$Guid, | |
[String]$Description, | |
[String]$Name | |
) | |
# Note - Need to use global due to script blocks in the Toast notifications later | |
$Global:TelstraNic = $null | |
$Global:UserConfigFile = $null | |
$Global:UserConfig = $null | |
if ($Description -ne 'Network') { Exit 0 } | |
# Find a NIC that's on a Telstra network | |
Import-Module DnsClient | |
$TelstraIIDs = Get-DnsClient | Where-Object { $_.ConnectionSpecificSuffix -like '*telstra.com' } | ForEach-Object { Write-Output $_.InterfaceIndex } | |
if ($null -eq $TelstraIIDs) { Exit 0 } | |
# Ensure it's an array | |
if ($TelstraIIDs.GetType().ToString() -ne 'System.Object[]') { $TelstraIIDs = @($TelstraIIDs) } | |
# Find the Network Profile that this event is applicable to | |
Import-Module NetConnection | |
$TelstraProfile = Get-NetConnectionProfile | | |
Where-Object { $TelstraIIDs -contains $_.InterfaceIndex } | | |
Where-Object { $_.Name -eq $Name } | |
if ($null -eq $TelstraProfile) { Exit 0 } | |
# Find the NIC this Network Profile is applicable to | |
Import-Module NetAdapter | |
$Global:TelstraNic = Get-NetAdapter -Physical -InterfaceIndex $TelstraProfile.InterfaceIndex | |
# We now have a NIC that is connected to the Telstra network | |
# Get user config file contents | |
$Global:UserConfigFile = Join-Path $ENV:APPDATA 'telstra-network-dectector.json' | |
$Global:UserConfig = @{} | |
try { | |
If (Test-Path -Path $Global:UserConfigFile) { | |
$TmpConfig = Get-Content -Raw -Path $Global:UserConfigFile | ConvertFrom-JSON | |
if ($null -ne $TmpConfig.yeet) { $Global:UserConfig['yeet'] = $TmpConfig.yeet } | |
if ($null -ne $TmpConfig.autodisable) { $Global:UserConfig['autodisable'] = $TmpConfig.autodisable } | |
} | |
} catch { | |
# Swallow all errors and assume bad file is bad | |
$Global:Config = @{} | |
} | |
Function Global:Disable-Nic($NicObject) { | |
Write-host "Disabling $($NicObject.Name) ..." | |
try { | |
Import-Module NetAdapter | |
Disable-NetAdapter -Name $NicObject.Name -Confirm:$false | |
} catch { | |
Write-Host "ERR $_" | |
} | |
} | |
# Check if we should disable without prompting | |
if ($UserConfig['yeet'] -eq $true) { | |
# Yeet it mode! | |
Disable-Nic -NicObject $Global:TelstraNic | |
Exit 0 | |
} | |
if ($UserConfig.autodisable -and ($UserConfig['autodisable'] -contains $Global:TelstraNic.DeviceID)) { | |
# Individual Nic | |
Disable-Nic -NicObject $Global:TelstraNic | |
Exit 0 | |
} | |
# Send a notification | |
Import-Module BurntToast | |
$ToastHeader = New-BTHeader -Id 'Telstra999' -Title 'Telstra Purple Tools' | |
# Setup the prettiness | |
$Text1 = New-BTText -Content 'Telstra Network Detector' | |
$ImagePath = 'C:\Program Files\PowerShell\7\assets\Powershell_avatar.ico' # TODO Maybe bad hardcoding...but ok for the moment? | |
$Image1 = New-BTImage -Source $ImagePath -AppLogoOverride -Crop None -AlternateText "PowerShell Logo" | |
$Audio1 = New-BTAudio -Source 'ms-winsoundevent:Notification.Default' | |
$Binding1 = New-BTBinding -Children $Text1 -AppLogoOverride $Image1 | |
$Visual1 = New-BTVisual -BindingGeneric $Binding1 | |
# Setup the selection itmes | |
$Item1 = New-BTSelectionBoxItem -Id 'Yes' -Content 'Yes' | |
$Item2 = New-BTSelectionBoxItem -Id 'Always' -Content 'Always for this desk' | |
$Item3 = New-BTSelectionBoxItem -Id 'AlwaysAlways' -Content 'Yeet all Telstra connections, all the time' | |
$InputSplat = @{ | |
Id = 'Selection001' | |
Title = 'Turn off the connection to the Telstra Network?' | |
DefaultSelectionBoxItemId = 'Yes' | |
Items = $Item1, $Item2, $Item3 | |
} | |
$BTInput = New-BTInput @InputSplat | |
$Submit = New-BTButton -Content 'Make it so' -Arguments 'SubmitButton' -ActivationType Foreground | |
$Dismiss = New-BTButton -Dismiss | |
$Actions = New-BTAction -Inputs $BTInput -Buttons $Submit, $Dismiss | |
$Content = New-BTContent -Visual $Visual1 -Audio $Audio1 -Actions $Actions -Header $ToastHeader | |
$global:BTEvent = $false | |
$ToastID = (New-Guid).ToString() | |
$sb = { | |
try { | |
# Check if they pressed SubmitButton | |
if ($Event -and $Event.SourceArgs) { | |
if ($Event.SourceArgs[1].Arguments -ne 'SubmitButton') { return } | |
} else { return } | |
Disable-Nic -NicObject $Global:TelstraNic | |
$UserInput = $Event.SourceArgs[1].UserInput | |
Switch ($UserInput.Value) { | |
'Yes' { | |
# Do Nothing | |
} | |
'Always' { | |
if ($Global:UserConfig['autodisable']) { | |
$Global:UserConfig['autodisable'] += $Global:TelstraNic.DeviceID | |
} else { | |
$Global:UserConfig['autodisable'] = @($Global:TelstraNic.DeviceID) | |
} | |
$Global:UserConfig | ConvertTo-JSON -Depth 2 | Set-Content -Path $Global:UserConfigFile -Encoding 'utf8' | |
} | |
'AlwaysAlways' { | |
$Global:UserConfig['yeet'] = $True | |
$Global:UserConfig | ConvertTo-JSON -Depth 2 | Set-Content -Path $Global:UserConfigFile -Encoding 'utf8' | |
} | |
} | |
} | |
catch { | |
Write-Host "ERR $_" | |
} | |
finally { | |
$global:BTEvent = $true | |
} | |
} | |
Submit-BTNotification -UniqueIdentifier $ToastID -Content $Content -ActivatedAction $sb -DismissedAction { $global:BTEvent = $true } -FailedAction { $global:BTEvent = $true } | |
$Timeout = 30 | |
While ((-not $global:BTEvent) -and ($Timeout -gt 0)) { Start-Sleep -Seconds 1; $Timeout-- } | |
if (-not $global:BTEvent) { Remove-BTNotification -UniqueIdentifier $ToastID } | |
'@ | Set-Content -Path $PS1ScriptPath -Encoding 'utf8' -Confirm:$False -Force | Out-Null | |
Write-Host "Installed $PS1ScriptPath" | |
$ExistingTask = Get-ScheduledTask -Taskname 'Disable Telstra Network Connection' -ErrorAction SilentlyContinue | |
if ($null -eq $ExistingTask) { | |
$XMLContent = @" | |
<?xml version=`"1.0`" encoding=`"UTF-16`"?> | |
<Task version=`"1.4`" xmlns=`"http://schemas.microsoft.com/windows/2004/02/mit/task`"> | |
<Triggers> | |
<EventTrigger> | |
<ExecutionTimeLimit>PT5M</ExecutionTimeLimit> | |
<Enabled>true</Enabled> | |
<Subscription><QueryList><Query Id=`"0`" Path=`"Microsoft-Windows-NetworkProfile/Operational`"><Select Path=`"Microsoft-Windows-NetworkProfile/Operational`">*[System[Provider[@Name='Microsoft-Windows-NetworkProfile'] and EventID=10000]]</Select></Query></QueryList></Subscription> | |
<ValueQueries> | |
<Value name=`"Description`">Event/EventData/Data[@Name=`"Description`"]</Value> | |
<Value name=`"Guid`">Event/EventData/Data[@Name=`"Guid`"]</Value> | |
<Value name=`"Name`">Event/EventData/Data[@Name=`"Name`"]</Value> | |
</ValueQueries> | |
</EventTrigger> | |
</Triggers> | |
<Principals> | |
<Principal id=`"Author`"> | |
<LogonType>InteractiveToken</LogonType> | |
<RunLevel>HighestAvailable</RunLevel> | |
</Principal> | |
</Principals> | |
<Settings> | |
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> | |
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> | |
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> | |
<AllowHardTerminate>true</AllowHardTerminate> | |
<StartWhenAvailable>false</StartWhenAvailable> | |
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> | |
<IdleSettings> | |
<StopOnIdleEnd>true</StopOnIdleEnd> | |
<RestartOnIdle>false</RestartOnIdle> | |
</IdleSettings> | |
<AllowStartOnDemand>true</AllowStartOnDemand> | |
<Enabled>true</Enabled> | |
<Hidden>true</Hidden> | |
<RunOnlyIfIdle>false</RunOnlyIfIdle> | |
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession> | |
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine> | |
<WakeToRun>false</WakeToRun> | |
<ExecutionTimeLimit>PT5M</ExecutionTimeLimit> | |
<Priority>7</Priority> | |
</Settings> | |
<Actions Context=`"Author`"> | |
<Exec> | |
<Command>wscript.exe</Command> | |
<Arguments>//Nologo //B `"$VBScriptPath`" -Guid `"`$(Guid)`" -Description `"`$(Description)`" -Name `"`$(Name)`"</Arguments> | |
</Exec> | |
</Actions> | |
</Task> | |
"@ | |
Register-ScheduledTask -Xml $XMLContent -TaskName 'Disable Telstra Network Connection' | Out-Null | |
Write-Host "Installed Scheduled Task" | |
} else { Write-Host "Scheduled Task is already installed" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment