Skip to content

Instantly share code, notes, and snippets.

@MrWyss-MSFT
Created October 12, 2023 08:17
Show Gist options
  • Select an option

  • Save MrWyss-MSFT/502061059c37797d99b4fb6f19fc44f9 to your computer and use it in GitHub Desktop.

Select an option

Save MrWyss-MSFT/502061059c37797d99b4fb6f19fc44f9 to your computer and use it in GitHub Desktop.
Check-IntuneEndpointsSchedTask.ps1
#Requires -RunAsAdministrator
$scheduledTaskScript = @'
$PSDefaultParameterValues = @{
"Write-Log:Path" = $env:ALLUSERSPROFILE + "\Microsoft\IntuneManagementExtension\Logs\Log-Network-$(Get-Date -Format yyyy-M-dd).log"
"Write-Log:Component" = "Log-Network"
"Write-Log:Type" = "Info"
"Write-Log:ConsoleOutput" = $True
}
#endregion
Function Write-Log {
<#
.SYNOPSIS
Writes CMTrace log file, customized version of https://janikvonrotz.ch/2017/10/26/powershell-logging-in-cmtrace-format/
#>
[CmdletBinding()]
Param(
[parameter(Mandatory = $true)]
[String]$Path,
[parameter(Mandatory = $true, ValueFromPipeline)]
[String]$Message,
[parameter(Mandatory = $true)]
[String]$Component,
[Parameter(Mandatory = $true)]
[ValidateSet("Info", "Warning", "Error")]
[String]$Type,
[Parameter(Mandatory = $false)]
[Switch]$ConsoleOutput
)
switch ($Type) {
"Info" { [int]$Type = 1 }
"Warning" { [int]$Type = 2 }
"Error" { [int]$Type = 3 }
}
if ($ConsoleOutput.IsPresent) {
switch ($Type) {
1 { $ForgroundColor = "White" }
2 { $ForgroundColor = "Yellow" }
3 { $ForgroundColor = "Red" }
}
$OutPut = "{0} : {1}" -f $(Get-Date -Format "MM-d-yyyy HH:mm:ss.ffffff"), $Message
write-host $OutPut -ForegroundColor $ForgroundColor
}
# Create a log entry
$Content = "<![LOG[$Message]LOG]!>" + `
"<time=`"$(Get-Date -Format "HH:mm:ss.ffffff")`" " + `
"date=`"$(Get-Date -Format "M-d-yyyy")`" " + `
"component=`"$Component`" " + `
"context=`"$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)`" " + `
"type=`"$Type`" " + `
"thread=`"$([Threading.Thread]::CurrentThread.ManagedThreadId)`" " + `
"file=`"`">"
# Write the line to the log file
$Content | Out-File -FilePath $Path -Append -Encoding UTF8
}
function Test-Port () {
param (
$hostname = "",
$port = 443,
$timeout = 100
)
$requestCallback = $state = $null
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect($hostname, $port, $requestCallback, $state)
Start-Sleep -milli $timeOut
if ($client.Connected) { $open = $true } else { $open = $false }
$client.Close()
[pscustomobject]@{hostname = $hostname; port = $port; open = $open }
}
$IntuneEndpointUrls = (invoke-restmethod -Uri ("https://endpoints.office.com/endpoints/WorldWide?ServiceAreas=MEM`&`clientrequestid=" + ([GUID]::NewGuid()).Guid)) | ? { $_.ServiceArea -eq "MEM" } | select -unique -ExpandProperty urls
$IntuneEndpointIpsNoAsterix = $IntuneEndpointUrls -notmatch '^\*'
Do {
$IntuneEndpointIpsNoAsterix | ForEach-Object {
Try {
$PingResult = Test-Port -hostname $_ -port 443 -timeout 100
if ($PingResult.Open) {
$Type = "Info"
} else {
$Type = "Warning"
}
Write-Log -Message "Ping $_ Port: $($PingResult.Port) Open: $($PingResult.Open)" -Type $Type -ConsoleOutput
} Catch {
Write-Log -Message "Ping $_ Port: 443 Something went wrong" -Type "Error" -ConsoleOutput
Continue
}
Start-Sleep -Milliseconds 100
}
Write-Log -Message "Wait for a Second" -ConsoleOutput
Start-Sleep -Seconds 1
} Until ($False)
'@
#endregion
$scheduledTaskScriptPath = "$env:CommonProgramW6432\Log-Network.ps1"
$scheduledTaskScript | out-file $scheduledTaskScriptPath -Encoding UTF8
$PSDefaultParameterValues = @{
"Install-ScheduledTask:TimeToLiveInHours" = 1
"Install-ScheduledTask:Author" = "MrWyss-MSFT"
"Install-ScheduledTask:TaskName" = "Log-Network"
#"Install-ScheduledTask:RepetitionInterval" = (New-TimeSpan -Minutes 1)
"Install-ScheduledTask:ScriptPath" = $scheduledTaskScriptPath
}
Function Install-ScheduledTask {
<#
.SYNOPSIS
Creates a scheduled task that run a online Powershell Script ($uri) on StartUp,
Which expires after given hours ($TimeToLiveInHours)
Optional an Author ($Author) can be specified for the Task
#>
[CmdletBinding()]
param (
[Parameter(Mandatory, HelpMessage = 'Path to the PoSH Script to be run')]
[string]
$ScriptPath,
[Parameter(Mandatory, HelpMessage = 'Specifies how long the task exists')]
[int]
$TimeToLiveInHours,
[Parameter(HelpMessage = 'Author of the Scheduled Task')]
[String]
$Author,
[Parameter(HelpMessage = 'Scheduled Task Name')]
[String]
$TaskName,
[Parameter(HelpMessage = 'Repetition Duration, for how long')]
[TimeSpan]
$RepetitionDuration = ((New-TimeSpan -Hours $TimeToLiveInHours) - (New-TimeSpan -Minutes 2)),
[Parameter(HelpMessage = 'Repetition Interval')]
[TimeSpan]
$RepetitionInterval,
[Parameter(HelpMessage = 'Start task at startup')]
[switch]
$AtStartup
)
#$OnlineScript = 'Invoke-Expression $($(Invoke-WebRequest -UseBasicParsing -Uri "' + $Uri + '").Content)'
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File ""$ScriptPath"""
$Trigger = New-ScheduledTaskTrigger -Once -At ((Get-Date).AddSeconds(10))
$User = "NT AUTHORITY\SYSTEM"
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -User $User -Action $Action -RunLevel Highest -Force | out-null
#region modify task
#get task
$TargetTask = Get-ScheduledTask -TaskName $TaskName
#tweaks
$TargetTask.Author = $Author
$TargetTask.Triggers[0].StartBoundary = [DateTime]::Now.ToString("yyyy-MM-dd'T'HH:mm:ss")
$TargetTask.Triggers[0].EndBoundary = [DateTime]::Now.AddHours($TimeToLiveInHours).ToString("yyyy-MM-dd'T'HH:mm:ss")
$TargetTask.Settings.AllowHardTerminate = $True
$TargetTask.Settings.DeleteExpiredTaskAfter = 'PT0S'
$TargetTask.Settings.ExecutionTimeLimit = 'PT1H'
$TargetTask.Settings.volatile = $False
$TargetTask.Settings.DisallowStartIfOnBatteries = $False
# Save tweaks
$TargetTask | Set-ScheduledTask | Out-Null
#endregion
}
Install-ScheduledTask
Start-ScheduledTask -TaskName $PSDefaultParameterValues.'Install-ScheduledTask:TaskName'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment