Subscriber.psm1
$script:ModuleRoot = $PSScriptRoot $script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\Subscriber.psd1").ModuleVersion # Detect whether at some level dotsourcing was enforced $script:doDotSource = Get-PSFConfigValue -FullName Subscriber.Import.DoDotSource -Fallback $false if ($Subscriber_dotsourcemodule) { $script:doDotSource = $true } <# Note on Resolve-Path: All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator. This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS. Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist. This is important when testing for paths. #> # Detect whether at some level loading individual module files, rather than the compiled module was enforced $importIndividualFiles = Get-PSFConfigValue -FullName Subscriber.Import.IndividualFiles -Fallback $false if ($Subscriber_importIndividualFiles) { $importIndividualFiles = $true } if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true } if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true } function Import-ModuleFile { <# .SYNOPSIS Loads files into the module on module import. .DESCRIPTION This helper function is used during module initialization. It should always be dotsourced itself, in order to proper function. This provides a central location to react to files being imported, if later desired .PARAMETER Path The path to the file to load .EXAMPLE PS C:\> . Import-ModuleFile -File $function.FullName Imports the file stored in $function according to import policy #> [CmdletBinding()] Param ( [string] $Path ) $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath if ($doDotSource) { . $resolvedPath } else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) } } #region Load individual files if ($importIndividualFiles) { # Execute Preimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) { . Import-ModuleFile -Path $path } # Import all internal functions foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Import all public functions foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Execute Postimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) { . Import-ModuleFile -Path $path } # End it here, do not load compiled code below return } #endregion Load individual files #region Load compiled code <# This file loads the strings documents from the respective language folders. This allows localizing messages and errors. Load psd1 language files for each language you wish to support. Partial translations are acceptable - when missing a current language message, it will fallback to English or another available language. #> Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'Subscriber' -Language 'en-US' function Get-EventSubscription { <# .SYNOPSIS Returns information on installed event subscriptions. .DESCRIPTION Returns information on installed event subscriptions. .PARAMETER SubscriptionName Name of the subscription to filter by. Defaults to '*'. .PARAMETER ComputerName Name of the computers against which to operate. Defaults to localhost. .PARAMETER Credential Credentials to use when connecting to computers. .EXAMPLE PS C:\> Get-EventSubscription List all event subscriptions installed on the local computer. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")] [CmdletBinding()] param ( [string] $SubscriptionName = '*', [Parameter(ValueFromPipeline = $true)] [PSFComputer[]] $ComputerName = $env:COMPUTERNAME, [PSCredential] $Credential ) process { Invoke-PSFCommand -ComputerName $ComputerName -Credential $Credential -ArgumentList $SubscriptionName -ScriptBlock { param ( $SubscriptionName ) try { $tasks = Get-ScheduledTask -TaskPath '\PowerShell_EventSubscriptions\' -ErrorAction Stop } catch { return } $scriptFolder = "$env:ProgramFiles\WindowsPowerShell\EventSubscriptions\subscriptions" foreach ($task in $tasks) { if ($task.TaskName -notlike $SubscriptionName) { continue } $taskInfo = $task | Get-ScheduledTaskInfo $code = $null if (Test-Path -Path "$scriptFolder\$($task.TaskName).ps1") { $code = Get-Content -Path "$scriptFolder\$($task.TaskName).ps1" -Raw } try { $queryObjects = ([xml]$task.Triggers.Subscription).QueryList.Query.Select } catch { } $queries = foreach ($query in $queryObjects) { $source, $eventID = $query.'#text' -replace "^.+@Name='([^']+)'] and EventID=(\d+).+$", '$1þ$2' -split 'þ' $object = [pscustomobject]@{ Path = $query.Path Filter = $query.'#text' Source = $source EventID = $eventID -as [int] } Add-Member -InputObject $object -MemberType ScriptMethod -Name ToString -Value { if ($this.EventID) { '{0}: {1} > {2}' -f $this.Path, $this.Source, $this.EventID } else { '{0}: {1}' -f $this.Path, $this.Filter } } -Force -PassThru } [pscustomobject]@{ PSTypeName = 'Subscriber.Task' ComputerName = $env:COMPUTERNAME Subscription = $task.TaskName LastRun = $taskInfo.LastRunTime LastResult = $taskInfo.LastTaskResult Filter = $queries TaskObject = $task Code = $code } } } } } function Install-EventSubscription { <# .SYNOPSIS Installs a powershell task that triggers off a windows eventlog event. .DESCRIPTION Installs a powershell task that triggers off a windows eventlog event. The code is deployed to the target machine and will run locally on that machine when triggered. The scriptblock or scriptfile receives one input object: The eventlog event object as returned by Get-WinEvent. If the scriptblock/-file does not have a parameter block yet, one will be created with the paraneter "$EventObject", which can be used in the code. This command does not implement dependency handling: Required modules must be installed separately on the target computer(s) if any are needed. .PARAMETER SubscriptionName Name of the subscription. Value is arbitrary, but must be unique and legal as a filename. This will be the name of the task, so no duplicates possible. Will overwrite an existing task of that name. .PARAMETER ScriptPath Path to the scriptfile to execute. Will be copied to the machine. .PARAMETER ScriptCode A scriptblock to execute. Will be written as file on the target system. .PARAMETER LogName The name of the log to monitor for events. .PARAMETER Source The name of the source off which to trigger tasks. .PARAMETER EventID The ID of the event that will trigger the task. .PARAMETER SubscriptionXML Rather than offering LogName, Source and EventID, you can offer a filter XML instead. This allows more granular filtering. To generate filter XML, the easiest way to set things up is to use the eventviewer MMC console: - Use the UI wizard to create a filter - When done, switch to the XML tab in the filter UI: That's the XML needed for this parameter. .PARAMETER Description Description to include in the scheduled task. .PARAMETER ComputerName The name of the computers to install the task on. Defaults to localhost. .PARAMETER Credential The credentials to use when connecting to the target system. NOT the account under which the event will trigger. .PARAMETER Elevated Whether the task should trigger with elevation. .PARAMETER Identity The user account under which the event should trigger. NOT the account used to create the scheduled task. Defaults to: SYSTEM Only specify a password if the account is a regular user account requiring one. Builtin accounts or gMSA do not require a password. .PARAMETER Executable Which executable should be used to execute the task. Defaults to powershell.exe Use "pwsh.exe" if you want the task to execute under PowerShell core (requires PowerShell Core to be installed on the target computer). .PARAMETER Author The Author listed in the Task Scheduler MMC console. Defaults to the current user. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Install-EventSubscription -SubscriptionName 'Account Lockout' -ScriptPath '.\lockout.ps1' -LogName 'Security' -Source 'Microsoft-Windows-Security-Auditing' -EventID 4740 Registers the script lockout.ps1 to be executed every time an account gets locked out. #> [CmdletBinding(DefaultParameterSetName = 'dataPath')] param ( [Parameter(Mandatory = $true)] [string] $SubscriptionName, [Parameter(Mandatory = $true, ParameterSetName = 'dataPath')] [Parameter(Mandatory = $true, ParameterSetName = 'xmlPath')] [PsfValidateScript({ Test-Path $_ }, ErrorMessage = 'Path does not exist: {0}')] [string] $ScriptPath, [Parameter(Mandatory = $true, ParameterSetName = 'dataCode')] [Parameter(Mandatory = $true, ParameterSetName = 'xmlCode')] [scriptblock] $ScriptCode, [Parameter(Mandatory = $true, ParameterSetName = 'dataPath')] [Parameter(Mandatory = $true, ParameterSetName = 'dataCode')] [string] $LogName, [Parameter(Mandatory = $true, ParameterSetName = 'dataPath')] [Parameter(Mandatory = $true, ParameterSetName = 'dataCode')] [string] $Source, [Parameter(Mandatory = $true, ParameterSetName = 'dataPath')] [Parameter(Mandatory = $true, ParameterSetName = 'dataCode')] [int] $EventID, [Parameter(Mandatory = $true, ParameterSetName = 'xmlPath')] [Parameter(Mandatory = $true, ParameterSetName = 'xmlCode')] [string] $SubscriptionXML, [string] $Description, [Parameter(ValueFromPipeline = $true)] [PSFComputer[]] $ComputerName = $env:COMPUTERNAME, [PSCredential] $Credential, [switch] $Elevated, [PSCredential] $Identity, [string] $Executable = 'powershell.exe', [string] $Author = $env:USERNAME, [switch] $EnableException ) begin { #region Resolve Task XML $registrationXML = @' <RegistrationInfo> <Author>{0}</Author> <Description>{1}</Description> </RegistrationInfo> '@ -f $Author, $Description $filterXML = @" <QueryList> <Query Id="0" Path="$LogName"> <Select Path="$LogName">*[System[Provider[@Name='$Source'] and EventID=$EventID]]</Select> </Query> </QueryList> "@ if ($SubscriptionXML) { $filterXML = $SubscriptionXML } $subscriptionText = ($filterXML -split "`n" -replace '>', '>' -replace '<', '<' | ForEach-Object { $_.Trim() }) -join "" $triggerXML = @' <Triggers> <EventTrigger> <Enabled>true</Enabled> <Subscription>{0}</Subscription> <ValueQueries> <Value name="Channel">Event/System/Channel</Value> <Value name="EventRecordID">Event/System/EventRecordID</Value> </ValueQueries> </EventTrigger> </Triggers> '@ -f $subscriptionText $settingsXML = @' <Settings> <MultipleInstancesPolicy>Parallel</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <StartWhenAvailable>false</StartWhenAvailable> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <IdleSettings> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <AllowStartOnDemand>false</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>false</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>false</WakeToRun> <ExecutionTimeLimit>PT8H</ExecutionTimeLimit> <Priority>7</Priority> </Settings> '@ $actionXML = @' <Actions Context="Author"> <Exec> <Command>{0}</Command> <Arguments>-NoProfile -File "þfilepathþ" -Channel "$(Channel)" -EventRecordID "$(EventRecordID)" -Subscription {1}</Arguments> </Exec> </Actions> '@ -f $Executable, $SubscriptionName $runLevel = 'LeastPrivilege' if ($Elevated) { $runLevel = 'HighestAvailable' } $userText = ' <UserId>S-1-5-18</UserId>' if ($Identity -and $Identity.UserName -ne 'SYSTEM') { if ($Identity.UserName -as [System.Security.Principal.SecurityIdentifier]) { $userSID = $Identity.UserName -as [System.Security.Principal.SecurityIdentifier] } else { $userSID = ([System.Security.Principal.NTAccount]$Identity.UserName).Translate([System.Security.Principal.SecurityIdentifier]) } $userText = " <UserId>$($userSID)</UserId>" } if ($Identity) { if ($Identity.GetNetworkCredential().Password) { $userText += @' <LogonType>Password</LogonType> '@ } } $principalXML = @' <Principals> <Principal id="Author"> {0} <RunLevel>{1}</RunLevel> </Principal> </Principals> '@ -f $userText, $runLevel $taskXml = @' <?xml version="1.0" encoding="UTF-16"?> <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> {0} {1} {2} {3} {4} </Task> '@ -f $registrationXML, $triggerXML, $principalXML, $settingsXML, $actionXML #endregion Resolve Task XML #region Resolve ScriptCode to $newScriptText if ($ScriptCode) { $scriptText = $ScriptCode.ToString() } else { $scriptText = Get-Content -Path $ScriptPath -Raw } $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($scriptText, [ref]$null, [ref]$errors) if ($errors) { Stop-PSFFunction -String 'Install-EventSubscription.SyntaxError' -EnableException $EnableException return } if (-not $ast.ParamBlock) { $offset = 0 if ($ast.EndBlock) { $offset = $ast.EndBlock.Extent.StartOffset } if ($ast.ProcessBlock) { $offset = $ast.ProcessBlock.Extent.StartOffset } if ($ast.BeginBlock) { $offset = $ast.BeginBlock.Extent.StartOffset } $newScriptText = "" if ($offset) { $newScriptText = $scriptText.SubString(0, $offset) } $newScriptText += @' [CmdletBinding()] param ( $EventObject ) '@ $newScriptText += $scriptText.SubString($offset) } elseif (-not $ast.ParamBlock.Attributes.TypeName.FullName -eq 'CmdletBinding') { $offset = $ast.ParamBlock.Extent.StartOffset $newScriptText = "" if ($offset) { $newScriptText = $scriptText.SubString(0, $offset) } $newScriptText += @' [CmdletBinding()] '@ $newScriptText += $scriptText.SubString($offset) } else { $newScriptText = $scriptText } #endregion Resolve ScriptCode to $newScriptText $subscriberCode = Get-Content -Path "$script:ModuleRoot\internal\scripts\Subscriber_EventLauncher.ps1" -Raw } process { if (Test-PSFFunctionInterrupt) { return } Invoke-PSFCommand -ComputerName $ComputerName -Credential $Credential -ArgumentList $taskXml, $newScriptText, $subscriberCode, $SubscriptionName, $Identity -ScriptBlock { param ( [string] $TaskXml, [string] $NewScriptText, [string] $SubscriberCode, [string] $SubscriptionName, [AllowNull()] $Identity ) #region Set up scriptfiles $encoding = New-Object System.Text.UTF8Encoding($true) $rootPath = "$env:ProgramFiles\WindowsPowerShell\EventSubscriptions" if (-not (Test-Path -Path $rootPath)) { $null = New-Item -Path $rootPath -ItemType Directory -Force } $subscriberPath = "$rootPath\Subscriber_EventLauncher.ps1" [System.IO.File]::WriteAllText($subscriberPath, $SubscriberCode, $encoding) $scriptFolder = "$rootPath\subscriptions" if (-not (Test-Path -Path $scriptFolder)) { $null = New-Item -Path $scriptFolder -ItemType Directory -Force } $scriptFilePath = "$scriptFolder\$SubscriptionName.ps1" [System.IO.File]::WriteAllText($scriptFilePath, $NewScriptText, $encoding) #endregion Set up scriptfiles #region Set up task $parameters = @{ Force = $true Xml = $TaskXml -replace 'þfilepathþ', $subscriberPath TaskPath = '\PowerShell_EventSubscriptions\' TaskName = $SubscriptionName } if ($Identity.UserName) { $parameters['User'] = $Identity.UserName } if ($Identity -and $Identity.GetNetworkCredential().Password) { $parameters['Password'] = $Identity.GetNetworkCredential().Password } $null = Register-ScheduledTask @parameters #endregion Set up task } } } function Uninstall-EventSubscription { <# .SYNOPSIS Removes an eventsubscription created with Install-EventSubscription. .DESCRIPTION Removes an eventsubscription created with Install-EventSubscription. .PARAMETER SubscriptionName Name of the subscription to uninstall. .PARAMETER ComputerName Name of the computers against which to operate. Defaults to localhost. .PARAMETER Credential Credentials to use when connecting to computers. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Uninstall-EventSubscription -SubscriptionName 'MyTask' Uninstalls the subscription "MyTask" from the local computer. #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [string] $SubscriptionName, [Parameter(ValueFromPipeline = $true)] [PSFComputer[]] $ComputerName = $env:COMPUTERNAME, [PSCredential] $Credential ) begin { $shouldProcess = $PSBoundParameters | ConvertTo-PSFHashtable -Include WhatIf, Confirm } process { Invoke-PSFCommand -ComputerName $ComputerName -Credential $Credential -ArgumentList $SubscriptionName, $shouldProcess -ScriptBlock { param ( $SubscriptionName, $ShouldProcess ) try { $tasks = Get-ScheduledTask -TaskPath '\PowerShell_EventSubscriptions\' -ErrorAction Stop } catch { return } $scriptFolder = "$env:ProgramFiles\WindowsPowerShell\EventSubscriptions\subscriptions" foreach ($task in $tasks) { if ($task.TaskName -ne $SubscriptionName) { continue } Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop @ShouldProcess if (Test-Path -Path "$scriptFolder\$($task.TaskName).ps1") { Remove-Item -Path "$scriptFolder\$($task.TaskName).ps1" -Force -ErrorAction Stop @ShouldProcess } } } } } <# This is an example configuration file By default, it is enough to have a single one of them, however if you have enough configuration settings to justify having multiple copies of it, feel totally free to split them into multiple files. #> <# # Example Configuration Set-PSFConfig -Module 'Subscriber' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'" #> Set-PSFConfig -Module 'Subscriber' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging." Set-PSFConfig -Module 'Subscriber' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments." <# Stored scriptblocks are available in [PsfValidateScript()] attributes. This makes it easier to centrally provide the same scriptblock multiple times, without having to maintain it in separate locations. It also prevents lengthy validation scriptblocks from making your parameter block hard to read. Set-PSFScriptblock -Name 'Subscriber.ScriptBlockName' -Scriptblock { } #> <# # Example: Register-PSFTeppScriptblock -Name "Subscriber.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> <# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name Subscriber.alcohol #> New-PSFLicense -Product 'Subscriber' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2020-08-27") -Text @" Copyright (c) 2020 Friedrich Weinmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "@ #endregion Load compiled code |