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.
 
        .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.
    #>

    # Parameter sets enforce the valid combinations: -Difference and -ChangeSummary are mutually
    # exclusive, -Key implies -ChangeSummary (so can't be combined with -Difference), and -Key can't be
    # combined with -AsString.
    [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', Mandatory)]
        [parameter(ParameterSetName = 'ChangeSummaryKey')]
        [switch]
        $ChangeSummary,

        [parameter(ParameterSetName = 'ChangeSummaryKey', Mandatory)]
        [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
    )

    # -Key only has meaning for a change summary, so it turns one on without needing -ChangeSummary too.
    if ($Key) {
        $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.'
        }

        $PipelineText = Get-PipelineText -Invocation $MyInvocation

        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"

    # The watched properties and the -Key check both need a sample item, which isn't available until the
    # command returns something (e.g. when watching an empty folder for the first file to appear). This is
    # dot-sourced with each result until it has seen an item, so its assignments apply to this scope.
    $UserProperty = $Property
    $Initialized = [bool]$AsString
    $Initialize = {
        param($Items)

        if ($Initialized) {
            return
        }

        $Sample = foreach ($Item in $Items) {
            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 -isnot [string]) {
            $Property = Resolve-WatchedProperty -InputObject $Sample -Property $UserProperty
            Write-Verbose "Watched properties: $($Property -Join ',')"
        }

        $Initialized = $true
    }

    $FirstResult = Invoke-Command $ScriptBlock

    if ($AsString) {
        $FirstResult = $FirstResult | Out-String -Stream
    }

    . $Initialize $FirstResult

    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-Command $ScriptBlock

            if ($AsString) {
                $Result = $Result | Out-String -Stream
            }

            . $Initialize $Result

            $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. Works on Windows PowerShell
            5.1 and PowerShell 7.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.InvocationInfo]
        $Invocation
    )

    $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
        }
    }

    # PowerShell 7.4+ exposes the full text of the statement, which covers multi-line pipelines typed
    # interactively. Its position relative to the line isn't known, so only use it if exactly one pipeline
    # in it ends in a command of this name.
    $Statement = if ($Invocation.PSObject.Properties['Statement']) { $Invocation.Statement }

    if ($Statement) {
        $StatementAst = $Parser::ParseInput($Statement, [ref]$null, [ref]$null)
        $Matched = @($StatementAst.FindAll({
                    param($Node)
                    $Node -is [System.Management.Automation.Language.CommandAst] -and
                    $Node.GetCommandName() -eq $Invocation.InvocationName -and
                    $Node.Parent -is [System.Management.Automation.Language.PipelineAst] -and
                    $Node.Parent.PipelineElements.IndexOf($Node) -gt 0
                }, $true))

        if ($Matched.Count -eq 1) {
            $Text = Get-UpstreamPipelineText -Ast $StatementAst -LineNumber $Matched[0].Extent.StartLineNumber -ColumnNumber $Matched[0].Extent.StartColumnNumber

            if ($Text) {
                return $Text
            }
        }
    }
}
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 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 Resolve-WatchedProperty {
    <#
        .SYNOPSIS
            Works out which properties to compare, from what was passed to -Property 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.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [object]
        $InputObject,

        [string[]]
        $Property
    )

    if ($Property -contains '*') {
        return $InputObject.PSObject.Properties.Name
    }

    if ($Property) {
        return $Property
    }

    $DefaultDisplay = $InputObject.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames

    if ($DefaultDisplay) {
        return $DefaultDisplay
    }

    Get-DefaultWatchProperty -InputObject $InputObject
}