Skip to content

Instantly share code, notes, and snippets.

@p0w3rsh3ll
Last active January 25, 2021 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p0w3rsh3ll/5ef0e49444704b045312c703cfea7d39 to your computer and use it in GitHub Desktop.
Save p0w3rsh3ll/5ef0e49444704b045312c703cfea7d39 to your computer and use it in GitHub Desktop.
#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