Added CustomAction and Detection

Added functionality for custom actions and detection so you can have the toast display if a script returns a $true  It can then build and run a custom protocol.

The main goal here is to be able to create flexibility to toast for any custom action.  And if desired, build a custom action protocol for that execution.

## Config XML Changes
* CustomActions element area.  This includes the DetectionScript, Action, and optional ExecutionScript
** If the ExecutionScript is enabled, a new protocol with the Action Name is created.  Note that you have to set the Action element to match the named custom action here if you want to use it.
## New Variables
* CustomActionsEnabled - Enables/Disables the custom action
* CustomDetection - The destection script.
* CustomAction - The XML that contains the action name and Script.
* CustomActionName - The name of the custom action.
## Functions
* Write-FullCustomAction - Writes the action script to the requested directory for the protocol to reference.
* Write-FullCustomProtocol - Writes the protocol information into the registry so the action can be called from there.
## New Check
* Additional Check for conflicts with custom actions being enabled.
## Misc
* Code for determining  the results of custom actions, if enabled.
* Custom action Toast display section.
* modified default toast to not display when custom actions are enabled.
This commit is contained in:
Paul Wetter 2020-10-17 01:15:25 -05:00
parent 8253af7675
commit 94625157ca
3 changed files with 286 additions and 33 deletions

View file

@ -1081,6 +1081,89 @@ exit 0
}
}
function Write-FullCustomAction {
[CmdletBinding()]
param (
[Parameter()]
[string]
$ActionName,
[Parameter()]
[string]
$ScriptDirectory,
[Parameter()]
[string]
$ExecutionScript
)
# Create CMD File
try {
$CMDFileName = $ActionName + '.cmd'
$CMDFilePath = $ScriptDirectory + '\' + $CMDFileName
Write-Log -Level Info -Message "Creating CMD File [$CMDFilePath]"
New-item -Path $ScriptDirectory -Name $CMDFileName -Force -ErrorAction Stop -OutVariable PathInfo | Out-Null
$GetCustomScriptPath = $PathInfo.FullName
Write-Log -Level Info -Message "File created. Writing content for CMD File [$CMDFilePath]"
[String]$Script = "powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File `"$ScriptDirectory\$ActionName.ps1`""
if (-NOT[string]::IsNullOrEmpty($Script)) {
Out-File -FilePath $GetCustomScriptPath -InputObject $Script -Encoding ASCII -Force -ErrorAction Stop
}
Write-Log -Level Info -Message "CMD File [$CMDFilePath] created and content written successfully!"
}
catch {
Write-Log -Level Error "Failed to create or write content to custom CMD script [$CMDFilePath] for action [$ActionName]. Action button will not work."
$ErrorMessage = $_.Exception.Message
Write-Log -Level Error -Message "Error message: $ErrorMessage"
}
#Create PS1 File
try {
$PS1FileName = $ActionName + '.ps1'
$PS1FilePath = $ScriptDirectory + '\' + $PS1FileName
Write-Log -Level Info -Message "Creating PS1 File [$PS1FilePath]"
New-item -Path $ScriptDirectory -Name $PS1FileName -Force -ErrorAction Stop -OutVariable PathInfo | Out-Null
$GetCustomScriptPath = $PathInfo.FullName
Write-Log -Level Info -Message "File created. Writing content for PS1 File [$PS1FilePath]"
[String]$Script = @"
$ExecutionScript
"@
if (-NOT[string]::IsNullOrEmpty($Script)) {
Out-File -FilePath $GetCustomScriptPath -InputObject $Script -Encoding ASCII -Force
}
Write-Log -Level Info -Message "PS1 File [$PS1FilePath] created and content written successfully!"
}
catch {
Write-Log -Level Error "Failed to create or write content to custom PS1 script [$PS1FilePath] for action [$ActionName]. Action button will not work."
$ErrorMessage = $_.Exception.Message
Write-Log -Level Error -Message "Error message: $ErrorMessage"
}
}
function Write-FullCustomProtocol {
[CmdletBinding()]
param (
[Parameter()]
[string]
$ActionName,
[Parameter()]
[string]
$ScriptDirectory
)
# Build out registry for custom action for running packages and task sequences via the action button
try {
Write-Log -Level Info -Message "Creating protocol in current user [HKCU:\Software\Classes\$($ActionName)] for action [$ActionName]"
New-Item "HKCU:\Software\Classes\$($ActionName)\shell\open\command" -Force -ErrorAction Stop | Out-Null
New-ItemProperty -LiteralPath "HKCU:\Software\Classes\$($ActionName)" -Name 'URL Protocol' -Value '' -PropertyType String -Force -ErrorAction Stop | Out-Null
New-ItemProperty -LiteralPath "HKCU:\Software\Classes\$($ActionName)" -Name '(default)' -Value "URL:$($ActionName) Protocol" -PropertyType String -Force -ErrorAction Stop | Out-Null
$RegCommandValue = $ScriptDirectory + '\' + "$($ActionName).cmd"
New-ItemProperty -LiteralPath "HKCU:\Software\Classes\$($ActionName)\shell\open\command" -Name '(default)' -Value $RegCommandValue -PropertyType String -Force -ErrorAction Stop | Out-Null
}
catch {
Write-Log -Level Error -Message "Failed to create the $ActionName custom protocol in HKCU\Software\Classes. Action button might not work"
$ErrorMessage = $_.Exception.Message
Write-Log -Level Error -Message "Error message: $ErrorMessage"
}
}
######### GENERAL VARIABLES #########
# Global variables
# Setting global script version
@ -1220,6 +1303,7 @@ if(-NOT[string]::IsNullOrEmpty($Xml)) {
$PendingRebootUptime = $Xml.Configuration.Feature | Where-Object {$_.Name -like 'PendingRebootUptime'} | Select-Object -ExpandProperty 'Enabled'
$PendingRebootCheck = $Xml.Configuration.Feature | Where-Object {$_.Name -like 'PendingRebootCheck'} | Select-Object -ExpandProperty 'Enabled'
$ADPasswordExpiration = $Xml.Configuration.Feature | Where-Object {$_.Name -like 'ADPasswordExpiration'} | Select-Object -ExpandProperty 'Enabled'
$CustomActionsEnabled = $Xml.Configuration.CustomActions.Enabled
# Load Toast Notification options
$PendingRebootUptimeTextEnabled = $Xml.Configuration.Option | Where-Object {$_.Name -like 'PendingRebootUptimeText'} | Select-Object -ExpandProperty 'Enabled'
$MaxUptimeDays = $Xml.Configuration.Option | Where-Object {$_.Name -like 'MaxUptimeDays'} | Select-Object -ExpandProperty 'Value'
@ -1261,6 +1345,10 @@ if(-NOT[string]::IsNullOrEmpty($Xml)) {
$Action = $Xml.Configuration.Option | Where-Object {$_.Name -like 'Action'} | Select-Object -ExpandProperty 'Value'
$GreetGivenName = $Xml.Configuration.Text | Where-Object {$_.Option -like 'GreetGivenName'} | Select-Object -ExpandProperty 'Enabled'
$MultiLanguageSupport = $Xml.Configuration.Text | Where-Object {$_.Option -like 'MultiLanguageSupport'} | Select-Object -ExpandProperty 'Enabled'
# Load Custom Action Details
$CustomDetection = $Xml.Configuration.CustomActions.DetectionScript
$CustomAction = $Xml.Configuration.CustomActions.Action
$CustomActionName = $Xml.Configuration.CustomActions.Action.Name
# Load Toast Notification buttons
$ActionButtonEnabled = $Xml.Configuration.Option | Where-Object {$_.Name -like 'ActionButton'} | Select-Object -ExpandProperty 'Enabled'
$DismissButtonEnabled = $Xml.Configuration.Option | Where-Object {$_.Name -like 'DismissButton'} | Select-Object -ExpandProperty 'Enabled'
@ -1490,6 +1578,13 @@ if (($Action -eq "ToastReboot:") -AND ($RunApplicationIDEnabled -eq "True")) {
Write-Log -Level Error -Message "This seems like an unintended configuration"
Exit 1
}
# New checks for Custom Actions
if (($CustomActionsEnabled -eq "True") -AND (($UpgradeOS -eq "True") -or ($PendingRebootUptime -eq "True") -or ($PendingRebootCheck -eq "True") -or ($ADPasswordExpiration -eq "True"))){
Write-Log -Level Error -Message "Error. Conflicting selection in the $Config file"
Write-Log -Level Error -Message "Error. You can't have CustomActionsEnabled set to True and other features set to True at the same time"
Write-Log -Level Error -Message "You should only enable one of the features or CustomActions"
Exit 1
}
# Downloading images into user's temp folder if images are hosted online
if (($LogoImageFileName.StartsWith("https://")) -OR ($LogoImageFileName.StartsWith("http://"))) {
@ -1613,6 +1708,35 @@ if ($PendingRebootUptime -eq "True") {
Write-Log -Message "PendingRebootUptime set to True. Checking for device uptime. Current uptime is: $Uptime days"
}
# Determin the results of custom actions, if enabled.
If ($CustomActionsEnabled -eq "True"){
# convert the string to a scriptblock
$DetectionScript = [Scriptblock]::Create($CustomDetection)
write-log -Message "Running custom detection script..."
Try {
#Run the script block. It should return a boolean true or false.
$CustomDetectionResult = Invoke-Command -ScriptBlock $DetectionScript
Write-Log -Message "Custom detection script seemed to execute successfully and returned [$CustomDetectionResult]"
}
Catch {
Write-Log -Level Error -Message "Custom detection script seemed to execute unsuccessfully and returned [$CustomDetectionResult]"
Write-Log -Level Warn -Message "Setting Result to false because of failure."
$CustomDetectionResult = $False
}
If($CustomDetectionResult -eq $true) {
IF ($CustomAction.ExecutionScript.Enabled -eq "True"){
Write-Log -Message "Custom Action Execution Script set to 'True'. Creating protocol and action script"
Write-FullCustomProtocol -ActionName $CustomActionName -ScriptDirectory $global:CustomScriptsPath
Write-FullCustomAction -ActionName $CustomActionName -ScriptDirectory $global:CustomScriptsPath -ExecutionScript $CustomAction.ExecutionScript.'#text'
} else {
Write-Log -Message "Custom Action Execution Script NOT set to 'True'. Skipping creating protocol and action script"
}
}
}
# Check for required entries in registry for when using Software Center as application for the toast
if ($SCAppStatus -eq "True") {
if (Get-Service -Name ccmexec -ErrorAction SilentlyContinue) {
@ -1978,14 +2102,24 @@ if (($ADPasswordExpiration -eq "True") -AND ($ADPasswordExpirationResult -eq $Tr
else {
Write-Log -Level Warn -Message "Conditions for displaying toast notification for ADPasswordExpiration are not fulfilled"
}
# Toast Used for Custom Action
if (($CustomActionsEnabled -eq "True") -AND ($CustomDetectionResult -eq $True)) {
Write-Log -Message "Toast notification is used in regards to CustomActionsEnabled. CustomDetection returned [$CustomDetectionResult]"
Display-ToastNotification
# Stopping script. No need to accidently run further toasts
break
}
else {
Write-Log -Level Warn -Message "Conditions for displaying toast notification for CustomActionsEnabled are not fulfilled. CustomDetection returned [$CustomDetectionResult]"
}
# Toast not used for either OS upgrade or Pending reboot OR ADPasswordExpiration. Run this if all features are set to false in config.xml
if (($UpgradeOS -ne "True") -AND ($PendingRebootCheck -ne "True") -AND ($PendingRebootUptime -ne "True") -AND ($ADPasswordExpiration -ne "True")) {
if (($UpgradeOS -ne "True") -AND ($PendingRebootCheck -ne "True") -AND ($PendingRebootUptime -ne "True") -AND ($ADPasswordExpiration -ne "True") -AND ($CustomActionsEnabled -ne "True")) {
Write-Log -Message "Toast notification is not used in regards to OS upgrade OR Pending Reboots OR ADPasswordExpiration. Displaying default toast"
Display-ToastNotification
# Stopping script. No need to accidently run further toasts
break
}
else {
Write-Log -Level Warn -Message "Conditions for displaying default toast notification are not fulfilled"
Write-Log -Level Warn -Message "Conditions for displaying default toast notification are not fulfilled. Either One of the other scenarios match or, CustomActionsEnabled is set to true."
}

109
config-toast-custom.xml Normal file
View file

@ -0,0 +1,109 @@
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Feature Name="Toast" Enabled="True" /> <!-- Enables or disables the entire toast notification -->
<Feature Name="UpgradeOS" Enabled="False" /> <!-- Specifies if the toast is used for OS upgrades. If set to True, the targetOS build is taking into account -->
<Feature Name="PendingRebootUptime" Enabled="False" /> <!-- Enables the toast for reminding users of restarting their device if it exceeds the uptime defined in MaxUptimeDays -->
<Feature Name="PendingRebootCheck" Enabled="False" /> <!-- Enables the toast for reminding users of pending reboots found in registry/WMI. Might not suit ConfigMgr all too well, as if a pending reboot is found, further deployments won't run -->
<Feature Name="ADPasswordExpiration" Enabled="False" /> <!-- Enables the toast for reminding users of expiring Active Directory passwords -->
<Option Name="TargetOS" Build="19041" /> <!-- The actual build number of the targeted OS. 19041 = 2004 | 18363 = 1909 | 18362 = 1903 | 17763 = 1809. This option has no effect if OSUpgrade is set to False -->
<Option Name="MaxUptimeDays" Value="-6" /> <!-- When using the toast for checking for pending reboots. A reboot is considered pending if computer uptime exceeds the value set here -->
<Option Name="PendingRebootUptimeText" Enabled="False" /> <!-- Adds an additional group to the toast with text about the uptime of the computer -->
<Option Name="PendingRebootCheckText" Enabled="False" /> <!-- Adds an additional group to the toast with text -->
<Option Name="ADPasswordExpirationText" Enabled="False" /> <!-- Adds an additional group to the toast with text -->
<Option Name="ADPasswordExpirationDays" Value="90" /> <!-- How many days in advance shall the toast start reminding the users -->
<Option Name="RunPackageID" Enabled="False" Value="KR100907" /> <!-- Will enable the toast to run any ConfigMgr PackageID through a custom protocol -->
<Option Name="RunApplicationID" Enabled="False" Value="ScopeId_A9117680-D054-482B-BC97-532E6CBD0E6B/Application_fd55f35c-4e34-4490-a3ec-ee0b79233ec6" /> <!-- Will enable the toast to run any ConfigMgr ApplicationID through a custom protocol -->
<Option Name="RunUpdateID" Enabled="False" Value="4561600" /> <!-- Will enable the toast to run any ConfigMgr Update ID through a custom protocol. Configure the value to the relevant KB-article ID -->
<Option Name="RunUpdateTitle" Enabled="False" Value="" /> <!-- Will enable the toast to run any ConfigMgr Update Name through a custom protocol -->
<Option Name="Deadline" Enabled="True" Value="12-31-2020 16:00" /> <!-- Adds an additional group to the toast with text about the deadline of the OSUpgrade -->
<Option Name="DynamicDeadline" Enabled="False" Value="KR1008C8" /> <!-- Adds an additional group to the toast with text about the deadline of the OSUpgrade. This will retrieve the deadline of the IPU from WMI -->
<Option Name="CreateScriptsAndProtocols" Enabled="True" /> <!-- Automatically create the needed custom scripts and protocols. This removes the need to do scripts and protocols outside of the script -->
<Option Name="UseSoftwareCenterApp" Enabled="False" /> <!-- The app in Windows doing the actual notification - can't be both SoftwareCenter and Powershell -->
<Option Name="UsePowershellApp" Enabled="True" /> <!-- The app in Windows doing the actual notification - can't be both SoftwareCenter and Powershell -->
<Option Name="CustomAudio" Enabled="False" /> <!-- Enable or disable a custom speak scenario, where the text will be read out aloud -->
<Option Name="LogoImageName" Value="ToastLogoImageDefault.jpg" /> <!-- File name of the image shown as logo in the toast notoification -->
<Option Name="HeroImageName" Value="ToastHeroImageDefault.jpg" /> <!-- File name of the image shown in the top of the toast notification -->
<Option Name="ActionButton" Enabled="True" /> <!-- Enables or disables the action button. -->
<Option Name="ActionButton2" Enabled="False" /> <!-- Enables or disables the action button. -->
<Option Name="DismissButton" Enabled="True" /> <!-- Enables or disables the dismiss button. -->
<Option Name="SnoozeButton" Enabled="False" /> <!-- Enabling this option will always enable action button and dismiss button -->
<Option Name="Scenario" Type="reminder" /> <!-- Possible values are: reminder | short | long -->
<Option Name="Action" Value="LaunchAppRepair:" /> <!-- Action taken when using the Action button. Can be any protocol in Windows -->
<Option Name="Action2" Value="ToastReboot:" /> <!-- Action taken when using the Action button. Can be any protocol in Windows -->
<CustomActions Enabled="true">
<DetectionScript>
$PathExists = Test-Path 'C:\Windows\System32' -ErrorAction Ignore
If ($PathExists){
$True
} else {
$False
}
</DetectionScript><!--This script should always return a boolean True or False to properly evaluate-->
<Action Name="LaunchAppRepair">
<ExecutionScript Enabled="True">
$App = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe"
[xml]$Toast = @"
&lt;toast scenario="Reminder"&gt;
&lt;visual&gt;
&lt;binding template="ToastGeneric"&gt;
&lt;text placement="attribution"&gt;The Servicedesk&lt;/text&gt;
&lt;text&gt;Doing the Needful...&lt;/text&gt;
&lt;group&gt;
&lt;subgroup&gt;
&lt;text hint-style="body" hint-wrap="true"&gt;Thanks for clicking to do the needful. This was a lot of fun.&lt;/text&gt;
&lt;/subgroup&gt;
&lt;/group&gt;
&lt;group&gt;
&lt;subgroup&gt;
&lt;text hint-style="base" hint-wrap="true"&gt;Just another paragragh on doing the needful.&lt;/text&gt;
&lt;/subgroup&gt;
&lt;/group&gt;
&lt;group&gt;
&lt;subgroup&gt;
&lt;text hint-style="body" hint-wrap="true"&gt;I've really got nothing else. Just wanting to babble on a little more.&lt;/text&gt;
&lt;/subgroup&gt;
&lt;/group&gt;
&lt;/binding&gt;
&lt;/visual&gt;
&lt;actions&gt;
&lt;action activationType="system" arguments="dismiss" content="Thanks!" /&gt;
&lt;/actions&gt;
&lt;/toast&gt;
"@
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] &gt; $nul
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] &gt; $nul
# Load the notification into the required format
$ToastXml = New-Object -TypeName Windows.Data.Xml.Dom.XmlDocument
$ToastXml.LoadXml($Toast.OuterXml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($App).Show($ToastXml)
</ExecutionScript>
</Action>
</CustomActions>
<Text Option="GreetGivenName" Enabled="True" /> <!-- Displays the toast with a personal greeting using the users given name retrieved from AD. Will try retrieval from WMI of no local AD -->
<Text Option="MultiLanguageSupport" Enabled="False" /> <!-- Enable support for multiple languages. If set to True, the toast notification will look for the users language culture within the config file -->
<en-US> <!-- Default fallback language. This language will be used if MultiLanguageSupport is set to False or if no matching language is found -->
<Text Name="PendingRebootUptimeText">Your computer is required to restart due to having exceeded the maximum allowed uptime.</Text> <!-- Text used if the PendingRebootUptimeText Option is enabled -->
<Text Name="PendingRebootCheckText">Reason: Pending reboots was found in registry or WMI.</Text> <!-- Text used if the PendingRebootUptimeText Option is enabled -->
<Text Name="ADPasswordExpirationText">Your password will expire on: </Text> <!-- Text used if the ADPasswordExpirationText Option is enabled -->
<Text Name="CustomAudioTextToSpeech">Hey you - wake up. Your computer needs to restart. Do it now.</Text> <!-- Text to speech used if the CustomAudioTextToSpeech Option is enabled -->
<Text Name="ActionButton">Do it!</Text> <!-- Text on the ActionButton if enabled -->
<Text Name="DismissButton">Later</Text> <!-- Text on the DismissButton if enabled -->
<Text Name="SnoozeButton">Snooze</Text> <!-- Text on the SnoozeButton if enabled -->
<Text Name="AttributionText">www.imab.dk</Text>
<Text Name="HeaderText">Helpdesk kindly reminds you...</Text>
<Text Name="TitleText">Computer requires the needful!</Text>
<Text Name="BodyText1">The directory C:\Windows\System32 exists. So, looks like your computer is ready to do the needful.</Text>
<Text Name="BodyText2">To proceed with doing the needful, click the "Do it!" link below. It will be amazing.</Text>
<Text Name="SnoozeText">Click snooze to be reminded again in:</Text>
<Text Name="DeadlineText">Your deadline is:</Text>
<Text Name="GreetMorningText">Good morning</Text>
<Text Name="GreetAfternoonText">Good afternoon</Text>
<Text Name="GreetEveningText">Good evening</Text>
<Text Name="MinutesText">Minutes</Text>
<Text Name="HourText">Hour</Text>
<Text Name="HoursText">Hours</Text>
<Text Name="ComputerUptimeText">Computer uptime:</Text>
<Text Name="ComputerUptimeDaysText">days</Text>
</en-US>
</Configuration>

View file

@ -23,11 +23,21 @@
<Option Name="CustomAudio" Enabled="False" /> <!-- Enable or disable a custom speak scenario, where the text will be read out aloud -->
<Option Name="LogoImageName" Value="ToastLogoImageDefault.jpg" /> <!-- File name of the image shown as logo in the toast notoification -->
<Option Name="HeroImageName" Value="ToastHeroImageDefault.jpg" /> <!-- File name of the image shown in the top of the toast notification -->
<Option Name="ActionButton" Enabled="True" /> <!-- Enables or disables the action button. -->
<Option Name="ActionButton" Enabled="False" /> <!-- Enables or disables the action button. -->
<Option Name="DismissButton" Enabled="True" /> <!-- Enables or disables the dismiss button. -->
<Option Name="SnoozeButton" Enabled="False" /> <!-- Enabling this option will always enable action button and dismiss button -->
<Option Name="Scenario" Type="reminder" /> <!-- Possible values are: reminder | short | long -->
<Option Name="Scenario" Type="long" /> <!-- Possible values are: reminder | short | long -->
<Option Name="Action" Value="ToastReboot:" /> <!-- Action taken when using the Action button. Can be any protocol in Windows -->
<CustomActions Enabled="True">
<Action Name="LaunchAppRepair">
<DetectionScript>
Test-Path 'C:\Windows\System32' -ErrorAction Ignore
</DetectionScript>
<!--This script should always return a boolean True or False to properly evaluate-->
<ExecutionScript>
</ExecutionScript>
</Action>
</CustomActions>
<Text Option="GreetGivenName" Enabled="True" /> <!-- Displays the toast with a personal greeting using the users given name retrieved from AD. Will try retrieval from WMI of no local AD -->
<Text Option="MultiLanguageSupport" Enabled="False" /> <!-- Enable support for multiple languages. If set to True, the toast notification will look for the users language culture within the config file -->
<en-US> <!-- Default fallback language. This language will be used if MultiLanguageSupport is set to False or if no matching language is found -->