Watch.psm1
|
Function Watch-Command { <# .SYNOPSIS Runs a scriptblock or the preceding pipeline repeatedly until there is change. .DESCRIPTION The Watch-Command cmdlet runs a specified scriptblock repeatedly at the specified interval (or every 1 second by default) and returns the result of the scriptblock when the output has changed. For the command to work the specified scriptblock must return a result to the pipeline. .PARAMETER ScriptBlock The scriptblock to execute, specified via curly braces. If you provide input via the pipeline that isn't a scriptblock then the entire invocation line that preceded the cmdlet will be used as the scriptblock input. .PARAMETER Seconds Number of seconds to wait between checks. Default = 1 .PARAMETER Difference Switch: Use to only output items in the collection that have changed (additions or modifications). .PARAMETER ChangeSummary Switch: Instead of returning raw objects, reports each change as a clean object with DetectedAt (when the change was detected), ChangeType ('Added', 'Removed' or 'Modified'), Key, ChangedProperties, Changes (each changed property with its PreviousValue and CurrentValue), and the whole item before and after the change as PreviousItem and CurrentItem. Unlike -Difference, this also reports items that were removed. Cannot be combined with -Difference. -Key is optional. Without it, changes are only reported as 'Added' or 'Removed' (a changed item appears as its old version removed and its new version added), and Key, ChangedProperties and Changes are $null. With -Key, items are paired up between checks, so a changed item is reported as 'Modified', with its key value in Key, the names of the properties that changed in ChangedProperties, and their previous and current values in Changes. .PARAMETER Key One or more property names that uniquely identify an item across checks (e.g. Name or Id). Items are paired up by this key between checks so that in-place changes are reported as 'Modified' (with the specific properties that changed) rather than appearing as an unrelated removal and addition. Implies -ChangeSummary, so specifying -ChangeSummary as well is optional. Cannot be used with -Difference or -AsString. .PARAMETER Continuous Switch: Run continuously (even after a change has occurred) until exited with CTRL+C. .PARAMETER AsString Switch: Converts the result of the scriptblock into an array of strings for comparison. .PARAMETER ClearScreen Switch: Clears the screen between each different result. You can also use 'cls' as an alias. .PARAMETER PassThru Switch: Passes through the initial result from the command (before any change has occurred). .PARAMETER Property Manually specify one or more property names to be used for comparison. If not specified, the default display property set is used. If there is not a default display property set, all properties are used. You can also use '*' to force all properties. .PARAMETER ExcludeProperty One or more property names to leave out of the comparison, so changes to them are ignored. Wildcards are supported (case-insensitive, e.g. 'Last*Time'). They are removed from whichever properties would otherwise be compared (see -Property), so they can be combined with -Property *. The properties are still output, as only the comparison changes. Cannot be used with -AsString. .PARAMETER Exclude One or more wildcard patterns (case-insensitive, e.g. '*Lease*'). Items whose text matches any of them are dropped from every result before comparing, so they are neither watched nor output. Each pattern must match the whole text, so use * either side to match part of it. For text output (e.g. from a native command, or with -AsString) this excludes matching lines. For objects it matches each object's string form; for files and folders that is their full path. This drops whole items: to ignore some of an object's properties, use -ExcludeProperty. Cannot be combined with -ExcludePattern. .PARAMETER ExcludePattern One or more regular expressions (case-insensitive). Works like -Exclude, but matches with regular expressions instead of wildcards, which match anywhere in the text unless anchored with ^ or $. Cannot be combined with -Exclude. .EXAMPLE Watch-Command -ScriptBlock { Get-Process } Runs Get-Process and returns the result when the data has changed. .EXAMPLE Get-Service | Watch-Command -Diff -Cont Runs Get-Service and returns any differences in the resultant data, continuously until interrupted by CTRL+C. .EXAMPLE Watch-Command { Get-Content test.txt } -Difference -Verbose -ClearScreen Uses Get-Content to monitor test.txt. Shows any changes and clears the screen between changes. .EXAMPLE Get-ChildItem | Watch-Command -Difference -AsString Monitors the result of Get-ChildItem for changes, returns any differences. Treats the input as strings not objects. .EXAMPLE Get-Process | Watch-Command -Difference -Property processname,id -Continuous Monitors Get-Process for differences in the specified properties only, continues until interrupted by CTRL+C. .EXAMPLE Get-ChildItem C:\Temp | Watch-Command -ChangeSummary -Key Name -Continuous Monitors a folder and reports each change as an 'Added', 'Removed' or 'Modified' object, including which properties changed and their previous/current values, continuously until interrupted by CTRL+C. .EXAMPLE ipconfig /all | Watch-Command -ChangeSummary -Continuous -Exclude '*Lease*' Monitors the network configuration for changes, excluding the lease times, which ipconfig can show shifting back and forth by a second between runs. .EXAMPLE ipconfig /all | Watch-Command -ChangeSummary -Continuous -ExcludePattern 'Lease (Obtained|Expires)' As above, but uses a regular expression to exclude only the lease time lines. .EXAMPLE Get-ChildItem C:\Temp | Watch-Command -ChangeSummary -Key Name -ExcludeProperty LastWriteTime* Monitors a folder like the example above, but ignores changes that only affect when the files were last written to. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '', Justification = 'Piped input only selects the pipeline shorthand: the piped values are discarded and the upstream commands are re-run from their source text, so there must be one watch, not one per item.')] [cmdletbinding(DefaultParameterSetName = 'Default')] Param( [parameter(ValueFromPipeline, Mandatory, Position = 0)] [object] $ScriptBlock, [parameter(Position = 1)] [int] $Seconds = 1, [parameter(ParameterSetName = 'Difference', Mandatory)] [switch] $Difference, [parameter(ParameterSetName = 'ChangeSummary')] [switch] $ChangeSummary, [parameter(ParameterSetName = 'ChangeSummary')] [string[]] $Key, [switch] $Continuous, [parameter(ParameterSetName = 'Default')] [parameter(ParameterSetName = 'Difference')] [parameter(ParameterSetName = 'ChangeSummary')] [switch] $AsString, [alias('cls')] [switch] $ClearScreen, [switch] $PassThru, [parameter(Position = 2)] [string[]] $Property, [ValidateNotNullOrEmpty()] [string[]] $ExcludeProperty, [ValidateNotNullOrEmpty()] [string[]] $Exclude, [ValidateNotNullOrEmpty()] [string[]] $ExcludePattern ) if ($Exclude -and $ExcludePattern) { Throw '-Exclude and -ExcludePattern cannot be used together. Use -Exclude for wildcards or -ExcludePattern for regular expressions.' } if ($ExcludeProperty) { if ($AsString) { Throw '-ExcludeProperty cannot be used with -AsString, as strings have no properties to compare.' } # Only checks the patterns are valid, so a bad one fails straight away. Resolve-WatchedProperty uses -like. $null = New-WildcardMatcher -Pattern $ExcludeProperty -ParameterName '-ExcludeProperty' } # Built up front, so an invalid pattern fails straight away rather than on the first check. Both # [WildcardPattern] and [regex] have IsMatch(). The regexes are combined into one so each item is only # matched once. $ExcludeMatchers = if ($Exclude) { New-WildcardMatcher -Pattern $Exclude -ParameterName '-Exclude' } elseif ($ExcludePattern) { try { [regex]::new((($ExcludePattern | ForEach-Object { "(?:$_)" }) -join '|'), 'IgnoreCase') } catch { Throw "-ExcludePattern contains an invalid regular expression: $($_.Exception.InnerException.Message)" } } # -Key only has meaning for a change summary, so it turns one on without needing -ChangeSummary too. if ($Key) { if ($AsString) { Throw '-Key cannot be used with -AsString, as strings have no properties to pair items up by.' } $ChangeSummary = [switch]$true } if ($ScriptBlock -isnot [scriptblock]) { # ExpectingInput rather than PipelinePosition: PipelinePosition only counts commands, so it is 1 for # pipelines that start with an expression (e.g. $Items | Watch-Command or 1..5 | Watch-Command). if (-not $MyInvocation.ExpectingInput) { Throw 'The -ScriptBlock parameter must be provided an object of type ScriptBlock unless invoked via the Pipeline.' } $CallerExtent = (Get-PSCallStack | Select-Object -Skip 1 -First 1).Position $PipelineText = Get-PipelineText -Invocation $MyInvocation -CallerExtent $CallerExtent if (-not $PipelineText) { Throw 'Could not determine the commands piped into Watch-Command. Use -ScriptBlock { ... } instead.' } $ScriptBlock = Get-PipelineScriptBlock -Text $PipelineText -SessionState $PSCmdlet.SessionState $Description = $PipelineText } else { $Description = $ScriptBlock.ToString().Trim() } Write-Verbose "Started executing $Description" $WarnedAllExcluded = $false $InvokeParams = @{ ScriptBlock = $ScriptBlock AsString = $AsString ExcludeMatcher = $ExcludeMatchers ExcludeParameterName = if ($Exclude) { '-Exclude' } else { '-ExcludePattern' } WarnedAllExcluded = [ref]$WarnedAllExcluded } # The watched properties and the -Key check both need an item, which isn't available until the command # returns something (e.g. when watching an empty folder for the first file to appear), so they're worked # out from each result until there is one. -AsString results are strings, so there's nothing to work out. $PropertyParams = @{ Property = $Property ExcludeProperty = $ExcludeProperty Key = $Key } $Initialized = [bool]$AsString $FirstResult = Invoke-WatchedCommand @InvokeParams if (-not $Initialized) { $Watched = Get-WatchedProperty -InputObject $FirstResult @PropertyParams if ($Watched) { $Property = $Watched.Property $Initialized = $true } } if ($PassThru) { if ($ClearScreen) { Clear-Host } Write-Output $FirstResult } # Warn about each duplicated -Key value only once, rather than on every check. $WarnedKey = [System.Collections.Generic.HashSet[string]]::new() $IsFirstCheck = $true do { do { # The first check runs straight away; every later one waits, including when the command returned # nothing (previously an empty result skipped the wait and re-ran the command without pausing). if (-not $IsFirstCheck) { Start-Sleep $Seconds } $IsFirstCheck = $false $Result = Invoke-WatchedCommand @InvokeParams if (-not $Initialized) { $Watched = Get-WatchedProperty -InputObject $Result @PropertyParams if ($Watched) { $Property = $Watched.Property $Initialized = $true } } $CompareParams = @{ ReferenceObject = @($FirstResult | Select-Object) DifferenceObject = @($Result | Select-Object) } if ($Property) { $CompareParams.Add('Property', $Property) } $Diff = Compare-Object @CompareParams -PassThru } until ($Diff) # Captured once per check so every change found in the same check shares one timestamp. $DetectedAt = Get-Date $Output = @( if ($ChangeSummary) { if ($Key) { # Compare-Object -PassThru attaches SideIndicator to the original objects it returns. Remove # it so it isn't reported as part of PreviousItem/CurrentItem. foreach ($DiffItem in $Diff) { $DiffItem.PSObject.Properties.Remove('SideIndicator') } Get-KeyedChange -PreviousResult @($FirstResult) -CurrentResult @($Result) -Key $Key -Property $Property -DetectedAt $DetectedAt -WarnedKey $WarnedKey } else { Get-UnkeyedChange -Difference @($Diff) -DetectedAt $DetectedAt } } elseif ($Difference) { $Diff | Where-Object { $_.SideIndicator -eq '=>' } } else { $Result } ) # A change summary compares items itself (pairing them up by -Key), so in rare cases it can find # nothing to report for a difference Compare-Object found. Treat that as no change and keep watching, # rather than returning with no output. $Reported = -not $ChangeSummary -or $Output.Count -gt 0 if ($Reported) { if ($ClearScreen) { Clear-Host } Write-Verbose "Change occurred at $DetectedAt" $Output } else { Write-Verbose "A difference was detected at $DetectedAt but no change could be summarised. Still watching." } $FirstResult = $Result } until ($Reported -and -not $Continuous) } if (-not (Test-Path alias:Watch)) { New-Alias -Name 'Watch' -Value 'Watch-Command' Export-ModuleMember -Alias 'Watch' } if (-not (Test-Path alias:wc)) { New-Alias -Name 'wc' -Value 'Watch-Command' Export-ModuleMember -Alias 'wc' } function Get-DefaultWatchProperty { <# .SYNOPSIS Returns the names of the properties to compare on an object that has no default display property set: its regular (Property/NoteProperty) members, minus ones that change without the item changing. .DESCRIPTION Excludes ScriptProperty/CodeProperty/AliasProperty members (e.g. a FileInfo's Target/LinkType), which are computed live from the filesystem on every access and throw if the item has since been deleted, rather than comparing against a snapshot of the value. See issue #3. Also excludes last-access times (e.g. a FileSystemInfo's LastAccessTime/LastAccessTimeUtc). Merely reading a file updates them, and NTFS only copies the new value into the directory listing that Get-ChildItem reads at some later point, so they produce "changes" at seemingly random times. They can still be watched by naming them with -Property (or using -Property *). This is the single definition used both to choose what Compare-Object compares and to decide which properties of a keyed item have changed, so the two can't drift apart. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [object] $InputObject ) $Excluded = 'LastAccessTime', 'LastAccessTimeUtc' foreach ($Member in $InputObject.PSObject.Properties) { if ($Member.MemberType -in 'Property', 'NoteProperty' -and $Member.Name -notin $Excluded) { $Member.Name } } } function Get-KeyedChange { <# .SYNOPSIS Compares two results by -Key and returns 'Added', 'Removed' and 'Modified' change summaries. .DESCRIPTION Items are paired up by their key value (compared case-sensitively, see Get-KeyedLookup). A key found only in the previous result is 'Removed', one found only in the current result is 'Added', and one found in both is 'Modified' if any watched property (other than the key) differs. If several items share a key value, they can't be paired reliably, so that group is compared as a set instead (like -ChangeSummary without -Key): changed items appear as 'Removed' and 'Added' rather than being missed. A warning is written the first time each duplicated key value is seen; pass the same -WarnedKey set on every call so it isn't repeated on each check. #> [CmdletBinding()] [OutputType([pscustomobject])] param( [AllowNull()] [AllowEmptyCollection()] [object[]] $PreviousResult, [AllowNull()] [AllowEmptyCollection()] [object[]] $CurrentResult, [Parameter(Mandatory)] [string[]] $Key, [string[]] $Property, [Parameter(Mandatory)] [datetime] $DetectedAt, [System.Collections.Generic.HashSet[string]] $WarnedKey = [System.Collections.Generic.HashSet[string]]::new() ) $Previous = Get-KeyedLookup -InputObject $PreviousResult -Key $Key $Current = Get-KeyedLookup -InputObject $CurrentResult -Key $Key # Previous keys in order, then keys that are new in this result. $AllKeys = [System.Collections.Generic.List[string]]::new($Previous.Keys) foreach ($KeyValue in $Current.Keys) { if (-not $Previous.Groups.ContainsKey($KeyValue)) { $AllKeys.Add($KeyValue) } } foreach ($KeyValue in $AllKeys) { # @() keeps these as arrays: an if-expression unrolls the list, and on Windows PowerShell 5.1 a single # [pscustomobject] has no .Count, so a one-item group would otherwise look empty. $PreviousItems = @(if ($Previous.Groups.ContainsKey($KeyValue)) { $Previous.Groups[$KeyValue] }) $CurrentItems = @(if ($Current.Groups.ContainsKey($KeyValue)) { $Current.Groups[$KeyValue] }) $KeySource = if ($CurrentItems.Count) { $CurrentItems[0] } else { $PreviousItems[0] } $KeyOutput = if ($Key.Count -eq 1) { $KeySource.($Key[0]) } else { $KeyProperties = [ordered]@{} foreach ($KeyName in $Key) { $KeyProperties[$KeyName] = $KeySource.$KeyName } [PSCustomObject]$KeyProperties } $CompareProperties = if ($Property) { $Property } else { Get-DefaultWatchProperty -InputObject $KeySource } if ($PreviousItems.Count -gt 1 -or $CurrentItems.Count -gt 1) { if ($WarnedKey.Add($KeyValue)) { Write-Warning ("Several items share the -Key value '{0}', so changes to them can't be paired up and are reported as 'Removed' and 'Added' instead of 'Modified'. Use -Key with a property (or properties) that is unique to each item." -f ($KeyValue -replace "`0", ', ')) } if (-not $PreviousItems.Count) { foreach ($Item in $CurrentItems) { New-ChangeSummary -DetectedAt $DetectedAt -ChangeType 'Added' -Key $KeyOutput -CurrentItem $Item } } elseif (-not $CurrentItems.Count) { foreach ($Item in $PreviousItems) { New-ChangeSummary -DetectedAt $DetectedAt -ChangeType 'Removed' -Key $KeyOutput -PreviousItem $Item } } else { $GroupDiff = @(Compare-Object -ReferenceObject @($PreviousItems) -DifferenceObject @($CurrentItems) -Property $CompareProperties -PassThru) $GroupChanges = @(Get-UnkeyedChange -Difference $GroupDiff -DetectedAt $DetectedAt -Key $KeyOutput) # Compare-Object -PassThru added SideIndicator to these items, which are still part of the results. Remove it so it isn't reported with them on a later check. foreach ($Item in $GroupDiff) { $Item.PSObject.Properties.Remove('SideIndicator') } $GroupChanges } } elseif (-not $PreviousItems.Count) { New-ChangeSummary -DetectedAt $DetectedAt -ChangeType 'Added' -Key $KeyOutput -CurrentItem $CurrentItems[0] } elseif (-not $CurrentItems.Count) { New-ChangeSummary -DetectedAt $DetectedAt -ChangeType 'Removed' -Key $KeyOutput -PreviousItem $PreviousItems[0] } else { $Changes = @(Get-PropertyChange -PreviousItem $PreviousItems[0] -CurrentItem $CurrentItems[0] -Property $CompareProperties -ExcludeProperty $Key) if ($Changes.Count) { New-ChangeSummary -DetectedAt $DetectedAt -ChangeType 'Modified' -Key $KeyOutput -Changes $Changes -PreviousItem $PreviousItems[0] -CurrentItem $CurrentItems[0] } } } } function Get-KeyedLookup { <# .SYNOPSIS Groups items by the value of their -Key property (or properties), keeping every item that shares a key value. .DESCRIPTION Returns an object with: - Keys: the key values, in the order they were first seen. - Groups: a dictionary of key value -> list of the items with that key value. Keys are compared case-sensitively (ordinal), so items whose keys differ only by case (e.g. readme and README on a case-sensitive filesystem, or a file renamed from a.txt to A.TXT) are kept apart rather than merged or matched with each other. A composite key is joined with a NUL character. A Dictionary[string, ...] is used rather than an OrderedDictionary because the latter also has a positional indexer, which Windows PowerShell 5.1 picks for numeric-looking keys such as '1'. #> [CmdletBinding()] [OutputType([pscustomobject])] param( [AllowNull()] [AllowEmptyCollection()] [object[]] $InputObject, [Parameter(Mandatory)] [string[]] $Key ) $Keys = [System.Collections.Generic.List[string]]::new() $Groups = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[object]]]::new([System.StringComparer]::Ordinal) foreach ($Item in $InputObject) { if ($null -eq $Item) { continue } $KeyParts = foreach ($KeyName in $Key) { "$($Item.$KeyName)" } $KeyValue = $KeyParts -join "`0" if (-not $Groups.ContainsKey($KeyValue)) { $Groups.Add($KeyValue, [System.Collections.Generic.List[object]]::new()) $Keys.Add($KeyValue) } $Groups[$KeyValue].Add($Item) } [PSCustomObject]@{ Keys = $Keys Groups = $Groups } } function Get-PipelineScriptBlock { <# .SYNOPSIS Turns the source text of the commands that were piped into a command (from Get-PipelineText) into a ScriptBlock that re-runs them, for the pipeline shorthand (e.g. Get-ChildItem | Watch-Command). .DESCRIPTION If -SessionState is given (the caller's, i.e. $PSCmdlet.SessionState), the returned ScriptBlock runs the piped commands in that session state, so they can see the caller's local variables (such as those of a function that uses the shorthand). Otherwise they would run in this module's scope. #> [CmdletBinding()] [OutputType([scriptblock])] param( [Parameter(Mandatory)] [string] $Text, [System.Management.Automation.SessionState] $SessionState ) $Inner = [scriptblock]::Create($Text) if (-not $SessionState) { return $Inner } { $SessionState.InvokeCommand.InvokeScript($SessionState, $Inner, @()) }.GetNewClosure() } function Get-PipelineText { <# .SYNOPSIS Returns the source text of the commands that were piped into the invoked command, or nothing if they can't be determined. .DESCRIPTION Parses the source of the invocation and takes only the pipeline elements that precede the command, so anything else on the line (an assignment such as '$r = ', earlier ';'-separated statements, or commands after it in the pipeline) is excluded. When invoked from a script file, the whole file is parsed so a pipeline split across several lines is recovered in full. Otherwise, a multi-line pipeline is recovered from -CallerExtent: the Position of the caller's call stack frame ((Get-PSCallStack)[1].Position from within the invoked command), whose script position gives the full source that was run. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [System.Management.Automation.InvocationInfo] $Invocation, [System.Management.Automation.Language.IScriptExtent] $CallerExtent ) $Parser = [System.Management.Automation.Language.Parser] $Sources = @() # From a script file: parse the whole file, so pipelines that span several lines are seen in full. Only # trusted if the file's line still matches the invocation (e.g. the code wasn't built with # [scriptblock]::Create inside that file, and the file hasn't changed since it was run). if ($Invocation.ScriptName -and (Test-Path -LiteralPath $Invocation.ScriptName -PathType Leaf)) { $FileAst = $Parser::ParseFile($Invocation.ScriptName, [ref]$null, [ref]$null) $FileLines = $FileAst.Extent.Text -split '\r?\n' $LineIndex = $Invocation.ScriptLineNumber - 1 if ($LineIndex -ge 0 -and $LineIndex -lt $FileLines.Count -and $FileLines[$LineIndex].TrimEnd() -eq "$($Invocation.Line)".TrimEnd()) { $Sources += , @($FileAst, $Invocation.ScriptLineNumber) } } # Interactive or -Command input (or as a fallback): parse just the line the command is on. if ($Invocation.Line) { $Sources += , @($Parser::ParseInput($Invocation.Line, [ref]$null, [ref]$null), 1) } foreach ($Source in $Sources) { $Text = Get-UpstreamPipelineText -Ast $Source[0] -LineNumber $Source[1] -ColumnNumber $Invocation.OffsetInLine if ($Text) { return $Text } } # A pipeline split over several lines that wasn't run from a script file (e.g. typed interactively): # .Line holds only the last line, so parse the full source the caller ran instead. The invocation's line # and column are relative to that source, so they locate the command exactly. # (InvocationInfo.Statement in PowerShell 7.4+ can't be used for this: it holds only the command itself.) $FullScript = if ($CallerExtent) { $CallerExtent.StartScriptPosition.GetFullScript() } if ($FullScript) { $FullAst = $Parser::ParseInput($FullScript, [ref]$null, [ref]$null) Get-UpstreamPipelineText -Ast $FullAst -LineNumber $Invocation.ScriptLineNumber -ColumnNumber $Invocation.OffsetInLine } } function Get-PropertyChange { <# .SYNOPSIS Compares two versions of the same item and returns a Watch.PropertyChange object (Property, PreviousValue, CurrentValue) for each property whose value differs. .DESCRIPTION Mirrors Compare-Object's semantics: values that aren't IComparable (e.g. the DirectoryInfo in a FileSystemInfo's Parent/Root/Directory) are compared by their string form, since -ne would otherwise compare them by reference and flag every freshly re-queried object as changed. Properties named in -ExcludeProperty (the -Key properties) are skipped, since they are what pairs the two versions up. #> [CmdletBinding()] [OutputType([pscustomobject])] param( [Parameter(Mandatory)] [object] $PreviousItem, [Parameter(Mandatory)] [object] $CurrentItem, [Parameter(Mandatory)] [string[]] $Property, [string[]] $ExcludeProperty ) foreach ($PropertyName in $Property) { if ($PropertyName -in $ExcludeProperty) { continue } $PreviousValue = $PreviousItem.$PropertyName $CurrentValue = $CurrentItem.$PropertyName $IsDifferent = if ($null -eq $PreviousValue -or $null -eq $CurrentValue) { ($null -eq $PreviousValue) -ne ($null -eq $CurrentValue) } elseif ($PreviousValue -is [System.IComparable]) { $PreviousValue -ne $CurrentValue } else { "$PreviousValue" -ne "$CurrentValue" } if ($IsDifferent) { # Displays as e.g. 'Length: 5 -> 10' via the ToString defined in Watch.types.ps1xml. [PSCustomObject]@{ PSTypeName = 'Watch.PropertyChange' Property = $PropertyName PreviousValue = $PreviousValue CurrentValue = $CurrentValue } } } } function Get-UnkeyedChange { <# .SYNOPSIS Turns Compare-Object -PassThru output into 'Added'/'Removed' change summaries, for -ChangeSummary without -Key. #> [CmdletBinding()] [OutputType([pscustomobject])] param( [AllowNull()] [AllowEmptyCollection()] [object[]] $Difference, [Parameter(Mandatory)] [datetime] $DetectedAt, [object] $Key ) foreach ($DiffItem in $Difference) { # Read SideIndicator before removing it: for .NET objects (e.g. FileInfo), PSObject.Copy() shares note # properties with the original, so removing it from the copy removes it from $DiffItem too, which # would turn every 'Added' item into 'Removed'. $SideIndicator = $DiffItem.SideIndicator $Clean = $DiffItem.PSObject.Copy() $Clean.PSObject.Properties.Remove('SideIndicator') if ($SideIndicator -eq '=>') { New-ChangeSummary -DetectedAt $DetectedAt -ChangeType 'Added' -Key $Key -CurrentItem $Clean } else { New-ChangeSummary -DetectedAt $DetectedAt -ChangeType 'Removed' -Key $Key -PreviousItem $Clean } } } function Get-UpstreamPipelineText { <# .SYNOPSIS Returns the source text of the pipeline elements that precede the command starting at the given line and column of a parsed script, or nothing if there is no such command or nothing precedes it. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [System.Management.Automation.Language.Ast] $Ast, [Parameter(Mandatory)] [int] $LineNumber, [Parameter(Mandatory)] [int] $ColumnNumber ) # Copied to locals because PSScriptAnalyzer doesn't count uses inside the predicate ScriptBlock. $TargetLine = $LineNumber $TargetColumn = $ColumnNumber $Command = $Ast.Find({ param($Node) $Node -is [System.Management.Automation.Language.CommandAst] -and $Node.Extent.StartLineNumber -eq $TargetLine -and $Node.Extent.StartColumnNumber -eq $TargetColumn }, $true) if (-not $Command -or $Command.Parent -isnot [System.Management.Automation.Language.PipelineAst]) { return } $Elements = $Command.Parent.PipelineElements $Index = $Elements.IndexOf($Command) if ($Index -lt 1) { return } ($Elements[0..($Index - 1)] | ForEach-Object { $_.Extent.Text }) -join ' | ' } function Get-WatchedProperty { <# .SYNOPSIS Works out which properties to compare from the first non-null item of a result, after checking the -Key properties exist on it. .DESCRIPTION Returns nothing if the result has no item yet (e.g. when watching an empty folder for the first file to appear), so call it with each result until it returns something. Then it returns an object whose Property is the list of properties to compare: - For text, which has no properties: -Property, unchanged. -ExcludeProperty has no effect, which is warned about. - Otherwise: as chosen by Resolve-WatchedProperty. If -ExcludeProperty leaves nothing, this throws, as Compare-Object would otherwise compare whole objects instead. The result is an object rather than the list itself because an empty list is a valid answer, and must be told apart from "no item yet". #> [CmdletBinding()] [OutputType([pscustomobject])] param( [AllowNull()] [AllowEmptyCollection()] [object[]] $InputObject, [string[]] $Property, [string[]] $ExcludeProperty, [string[]] $Key ) $Sample = foreach ($Item in $InputObject) { if ($null -ne $Item) { $Item break } } if ($null -eq $Sample) { return } if ($Key) { $AvailableProperties = $Sample.PSObject.Properties.Name foreach ($KeyName in $Key) { if ($KeyName -notin $AvailableProperties) { Throw "The property '$KeyName' specified via -Key was not found on the ScriptBlock's result." } } } if ($Sample -is [string]) { if ($ExcludeProperty) { Write-Warning '-ExcludeProperty has no effect here, as the command returns text, which has no properties. To leave out lines of text, use -Exclude or -ExcludePattern.' } return [PSCustomObject]@{ Property = $Property } } $Resolved = @(Resolve-WatchedProperty -InputObject $Sample -Property $Property -ExcludeProperty $ExcludeProperty) if ($ExcludeProperty -and -not $Resolved.Count) { Throw '-ExcludeProperty excludes every property that would be compared, so there is nothing left to watch.' } Write-Verbose "Watched properties: $($Resolved -join ',')" [PSCustomObject]@{ Property = $Resolved } } function Invoke-WatchedCommand { <# .SYNOPSIS Runs the watched command once and returns its result, converted to strings for -AsString and with the items -Exclude/-ExcludePattern match left out. .DESCRIPTION If the matchers exclude every item the command returned, there is nothing to compare, so Watch-Command would wait without saying why. A warning explains this the first time it happens: pass the same -WarnedAllExcluded reference on every call so it isn't repeated on each check. -ExcludeParameterName is the parameter the matchers came from, for the warning. #> [CmdletBinding()] [OutputType([object])] param( [Parameter(Mandatory)] [scriptblock] $ScriptBlock, [switch] $AsString, [AllowNull()] [AllowEmptyCollection()] [object[]] $ExcludeMatcher, [string] $ExcludeParameterName, [Parameter(Mandatory)] [ref] $WarnedAllExcluded ) $RawResult = @(Invoke-Command $ScriptBlock) if ($AsString) { $RawResult = @($RawResult | Out-String -Stream) } $KeptResult = @(Skip-ExcludedItem -InputObject $RawResult -Matcher $ExcludeMatcher) if ($ExcludeMatcher -and $RawResult.Count -and -not $KeptResult.Count -and -not $WarnedAllExcluded.Value) { $FirstItem = $RawResult[0] $FirstText = if ($FirstItem -is [System.IO.FileSystemInfo]) { $FirstItem.FullName } else { "$FirstItem" } Write-Warning "$ExcludeParameterName excluded every item the command returned, so there is nothing to watch until it returns something else. It matches each item's text (e.g. '$FirstText'), not its property names: to ignore some of an object's properties, use -ExcludeProperty." $WarnedAllExcluded.Value = $true } $KeptResult } function New-ChangeSummary { <# .SYNOPSIS Creates a Watch.ChangeSummary object, the single definition of the objects -ChangeSummary outputs. #> [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Only creates an in-memory object.')] [OutputType([pscustomobject])] param( [Parameter(Mandatory)] [datetime] $DetectedAt, [Parameter(Mandatory)] [ValidateSet('Added', 'Removed', 'Modified')] [string] $ChangeType, [object] $Key, [object[]] $Changes, [object] $PreviousItem, [object] $CurrentItem ) [PSCustomObject]@{ PSTypeName = 'Watch.ChangeSummary' DetectedAt = $DetectedAt ChangeType = $ChangeType Key = $Key # The leading comma stops the if-expression unrolling a one-item array into a single object. ChangedProperties = if ($Changes) { , @($Changes.Property) } else { $null } Changes = if ($Changes) { , @($Changes) } else { $null } PreviousItem = $PreviousItem CurrentItem = $CurrentItem } } function New-WildcardMatcher { <# .SYNOPSIS Returns a case-insensitive [WildcardPattern] for each pattern, throwing straight away if one is invalid. .DESCRIPTION [WildcardPattern] only parses a pattern when it is first used, so each one is used once here. That way an invalid pattern fails when Watch-Command starts, rather than on the first check. -ParameterName is the parameter the patterns came from, for the error message. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Only creates in-memory objects.')] [CmdletBinding()] [OutputType([System.Management.Automation.WildcardPattern])] param( [Parameter(Mandatory)] [string[]] $Pattern, [Parameter(Mandatory)] [string] $ParameterName ) foreach ($Item in $Pattern) { $Wildcard = [System.Management.Automation.WildcardPattern]::new($Item, 'IgnoreCase') try { $null = $Wildcard.IsMatch('') } catch { Throw "$ParameterName contains an invalid wildcard pattern '$Item': $($_.Exception.InnerException.Message)" } $Wildcard } } function Resolve-WatchedProperty { <# .SYNOPSIS Works out which properties to compare, from what was passed to -Property and -ExcludeProperty and a sample of the watched output. .DESCRIPTION 1. -Property *: every property of the sample. 2. -Property with names: those names, as given. 3. Otherwise the sample's default display property set (the properties shown by default), if it has one. 4. Otherwise its regular properties, as chosen by Get-DefaultWatchProperty. Any of those that match an -ExcludeProperty wildcard (case-insensitive) are then left out. This can leave nothing, which the caller must handle. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [object] $InputObject, [string[]] $Property, [string[]] $ExcludeProperty ) $Names = if ($Property -contains '*') { $InputObject.PSObject.Properties.Name } elseif ($Property) { $Property } else { $DefaultDisplay = $InputObject.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames if ($DefaultDisplay) { $DefaultDisplay } else { Get-DefaultWatchProperty -InputObject $InputObject } } foreach ($Name in $Names) { $IsExcluded = $false foreach ($Pattern in $ExcludeProperty) { if ($Name -like $Pattern) { $IsExcluded = $true break } } if (-not $IsExcluded) { $Name } } } function Skip-ExcludedItem { <# .SYNOPSIS Drops the items that any of the -Exclude/-ExcludePattern matchers match. .DESCRIPTION Each matcher is a [WildcardPattern] or [regex] (both have IsMatch()). When there are no matchers, the input is returned unchanged. FileSystemInfo.ToString() is the full path on .NET (PS 7) but only the name on .NET Framework (PS 5.1), so files are matched by FullName on both. #> [CmdletBinding()] param( [AllowNull()] [AllowEmptyCollection()] [object[]] $InputObject, [AllowNull()] [AllowEmptyCollection()] [object[]] $Matcher ) if (-not $Matcher) { return $InputObject } foreach ($Item in $InputObject) { $Text = if ($Item -is [System.IO.FileSystemInfo]) { $Item.FullName } else { "$Item" } $IsExcluded = $false foreach ($Pattern in $Matcher) { if ($Pattern.IsMatch($Text)) { $IsExcluded = $true break } } if (-not $IsExcluded) { $Item } } } |