Skip to content

Instantly share code, notes, and snippets.

@p0w3rsh3ll

p0w3rsh3ll/Start-UserNotification.ps1 Secret

Last active Jan 25, 2021
Embed
What would you like to do?
#Requires -RunAsAdministrator
Function Start-UserNotification {
<#
.SYNOPSIS
Start a script in the user context
.DESCRIPTION
Start a script in the user context using scheduled tasks
.PARAMETER UserName
String that represents the targeted user name
.PARAMETER FilePath
String that represents the path to the script to be executed
.PARAMETER Prefix
String that is being used to prefix the task name
.EXAMPLE
Start-UserNotification -UserName LocalUserName -FilePath C:\notif.ps1
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType('System.Boolean')]
Param(
[Parameter(Mandatory)]
[string]$UserName,
[Parameter(Mandatory)]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[string]$FilePath,
[Parameter()]
[string]$Prefix='__'
)
Begin {
$errHT = @{ ErrorAction = 'Stop' }
$cmd = '& {0}' -f [Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($FilePath)
$aHT = @{
Execute = 'C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe'
Argument = '-NoProfile -WindowStyle Hidden -Exec Bypass -Command "{0}"' -f "$($cmd)"
}
}
Process {
}
End {
# Notify user using a Scheduled task
try {
$taskName = '{0}-Notify' -f [regex]::Escape($Prefix)
Get-ScheduledTask -TaskPath '\' @errHT | Where-Object { $_.TaskName -match "^$($taskName)_" } | ForEach-Object {
if ($pscmdlet.ShouldProcess("$($_.TaskName)", 'Remove previous task')) {
$null = $_ | Stop-ScheduledTask -Verbose @errHT
$null = $_ | Unregister-ScheduledTask -Verbose -Confirm:$false @errHT
Write-Verbose -Message "Successfully remove task $($_.TaskName)"
}
}
} catch {
Write-Warning -Message "Failed to stop and unregister because $($_.Exception.Message)"
}
try {
$HT = @{
TaskName = '{0}_{1}' -f "$($taskName)","$($UserName)"
User = '{0}' -f "$($UserName)"
Force = [switch]::Present
Action = (New-ScheduledTaskAction @aHT @errHT)
Settings = (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Compatibility 'Win8' @errHT)
}
if ($pscmdlet.ShouldProcess("$($HT['TaskName'])", 'Create and run task')) {
$null = Register-ScheduledTask @HT @errHT | Start-ScheduledTask @errHT
Write-Verbose -Message "Successfully created and ran task $($HT['TaskName'])"
$true
}
} catch {
Write-Warning -Message "Failed to register and run notification task because $($_.Exception.Message)"
$false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment