Elizium.Loopz.psm1
using module Elizium.Klassy; using module Elizium.Krayola; Set-StrictMode -Version 1.0 function Rename-Many { <# .NAME Rename-Many .SYNOPSIS Performs a bulk rename for all file system objects delivered through the pipeline, via regular expression replacement. .DESCRIPTION The user should assemble the candidate items from the file system, be they files or directories typically using Get-ChildItem, or can be any other function that delivers file systems items via the PowerShell pipeline. For each item in the pipeline, Rename-Many will perform a rename. Rename-Many is a powerful command and should be used with caution. Because of the potential of accidental misuse, a number of protections have been put in place: * By default, the command is locked. This means that the command will not actually perform any renames until it has been unlocked by the user. When locked, the command runs as though -WhatIf has been specified. There are indications in the output to show that the command is in a locked state (there is an indicator in the batch header and a 'Novice' indicator in the summary). To activate the command, the user needs to set the environment variable 'LOOPZ_REMY_LOCKED' to $false. The user should not unlock the command until they are comfortable with how to use this command properly and knows how to write regular expressions correctly. (See regex101.com) * An undo script is generated by default. If the user has invoked a rename operation by accident without specifying $WhatIf (or any other WhatIf equivalent like $Diagnose) then the user can execute the undo script to reverse the rename operation. The user should clearly do this immediately on recognising the error of their ways. In a panic, the user may terminate the command via ctrl-c. In this case, a partial undo script is still generated and should contain the undo operations for the renames that were performed up to the point of the termination request. The name of the undo script is based upon the current date and time and is displayed in the summary. (The user can, if they wish disable the undo feature if they don't want to have to manage the accumulation of undo scripts, by setting the environment variable LOOPZ_REMY_UNDO_DISABLED to $true) Another important point of note is that there are currently 3 modes of operation: 'move', 'update' or 'cut': * 'move': requires an anchor, which may be an $Anchor pattern or either $Start or $End switches. * 'update': requires $With or $Paste without an anchor. * 'cut': no anchor or $With/$Paste specified, the $Pattern match is simply removed from the name. The following regular expression parameters: * $Pattern * $Anchor * $Copy can optionally have an occurrence value specified that can be used to select which match is active. In the case where a provided expression has multiple matches, the occurrence value can be used to single out which one. When no occurrence is specified, the default is the first match only. The occurrence for a parameter can be: * f: first occurrence * l: last occurrence * <number>: the nth occurrence * *: all occurrences. The wild card occurrence can only be used with 'update' or 'cut' operations (it doesn't make sense for example to 'move' all occurrences of a pattern to the anchor) The occurrence is specified after the regular expression eg: -Pattern '\w\d{2,3}', l which means match the Last occurrence of the expression. (Actually, an occurrence may be specified for $Include and $Exclude but there is no point in doing so because these patterns only provide a filtering function and play no part in the actual renaming process). A note about escaping. If a pattern needs to use an regular expression character as a literal, it must be escaped. There are multiple ways of doing this: * use the 'esc' function; eg: -Pattern $($esc('(\d{2})')) * use a leading ~; -Pattern '~(123)' The above 2 approaches escape the entire string. The second approach is more concise and avoids the necessary use of extra brackets and $. * use 'esc' alongside other string concatenation: eg: -Pattern $($esc('(123)') + '-(?<ccy>GBP|SEK)'). This third method is required when the whole pattern should not be subjected to escaping. .PARAMETER Anchor Indicates that the rename operation will be a move of the token from its original point to the point indicated by Anchor. Anchor is a regular expression string applied to the pipeline item's name (after the $Pattern match has been removed). The $Pattern match that is removed is inserted at the position indicated by the anchor match in collaboration with the $Relation parameter. .PARAMETER Condition Provides another way of filtering pipeline items. This is not typically specified on the command line, rather it is meant for those wanting to build functionality on top of Rename-Many. .PARAMETER Context Provides another way of customising Rename-Many. This is not typically specified on the command line, rather it is meant for those wanting to build functionality on top of Rename-Many. $Context should be a PSCustomObject with the following note properties: * Title (default: 'Rename') the name used in the batch header. * ItemMessage (default: 'Rename Item') the operation name used for each renamed item. * SummaryMessage (default: 'Rename Summary') the name used in the batch summary. * Locked (default: 'LOOPZ_REMY_LOCKED) the name of the environment variable which controls the locking of the command. * DisabledEnVar (default: 'LOOPZ_REMY_UNDO_DISABLED') the name of the environment variable which controls if the undo script feature is disabled. * UndoDisabledEnVar (default: 'LOOPZ_REMY_UNDO_DISABLED') the name of the environment variable which determines if the Undo feature is disabled. This allows any other function built on top of Rename-Many to control the undo feature for itself independently of Rename-Many. .PARAMETER Copy Regular expression string applied to the pipeline item's name (after the $Pattern match has been removed), indicating a portion which should be copied and re-inserted (via the $Paste parameter; see $Paste or $With). Since this is a regular expression to be used in $Paste/$With, there is no value in the user specifying a static pattern, because that static string can just be defined in $Paste/$With. The value in the $Copy parameter comes when a generic pattern is defined eg \d{3} (is non static), specifies any 3 digits as opposed to say '123', which could be used directly in the $Paste/$With parameter without the need for $Copy. The match defined by $Copy is stored in special variable ${_c} and can be referenced as such from $Paste and $With. .PARAMETER Diagnose switch parameter that indicates the command should be run in WhatIf mode. When enabled it presents additional information that assists the user in correcting the un-expected results caused by an incorrect/un-intended regular expression. The current diagnosis will show the contents of named capture groups that they may have specified. When an item is not renamed (usually because of an incorrect regular expression), the user can use the diagnostics along side the 'Not Renamed' reason to track down errors. When $Diagnose has been specified, $WhatIf does not need to be specified. .PARAMETER Directory switch to indicate only Directory items in the pipeline will be processed. If neither this switch or the File switch are specified, then both File and Directory items are processed. .PARAMETER Drop A string parameter (only applicable to move operations, ie Anchor/Star/End) that defines what text is used to replace the Pattern match. So in this use-case, the user wants to move a particular token/pattern to another part of the name and at the same time drop a static string in the place where the $Pattern was removed from. .PARAMETER End Is another type of anchor used instead of $Anchor and specifies that the $Pattern match should be moved to the end of the new name. .PARAMETER Except Regular expression string applied to the original pipeline item's name (before the $Pattern match has been removed). Allows the user to exclude some items that have been fed in via the pipeline. Those items that match the exclusion are skipped during the rename batch. .PARAMETER File switch to indicate only File items in the pipeline will be processed. If neither this switch or the Directory switch are specified, then both File and Directory items are processed. .PARAMETER Include Regular expression string applied to the original pipeline item's name (before the $Pattern match has been removed). Allows the user to include some items that have been fed in via the pipeline. Only those items that match $Include pattern are included during the rename batch, the others are skipped. The value of the Include parameter comes when you want to define a pattern which pipeline items match, without it be removed from the original name, which is what happens with $Pattern. Eg, the user may want to specify the only items that should be considered a candidate to be renamed are those that match a particular pattern but doing so in $Pattern would simply remove that pattern. That may be ok, but if it's not, the user should specify a pattern in the $Include and use $Pattern for the match you do want to be moved (with Anchor/Start/End) or replaced (with $With/$Paste). .PARAMETER Paste This is a NON regular expression string. It would be more accurately described as a formatter, similar to the $With parameter. When $Paste is defined, the $Anchor (if specified) is removed from the original name and needs to be be re-inserted using the special variable ${_a}. The other special variables that can be used inside a $Paste string is documented under the $With parameter. The $Paste string can specify a format that defines the replacement and since it removes the $Anchor, the $Relation is not applicable ($Relation and $Paste can't be used together). .PARAMETER Pattern Regular expression string that indicates which part of the pipeline items' name that either needs to be moved or replaced as part of bulk rename operation. Those characters in the name which match are removed from the name. The pattern can be followed by an occurrence indicator. As the $Pattern parameter is strictly speaking an array, the user can specify the occurrence after the regular expression eg: $Pattern '(?<code>\w\d{2})', l => This indicates that the last match should be captured into named group 'code'. .PARAMETER Relation Used in conjunction with the $Anchor parameter and can be set to either 'before' or 'after' (the default). Defines the relationship of the $pattern match with the $Anchor match in the new name for the pipeline item. .PARAMETER Start Is another type of anchor used instead of $Anchor and specifies that the $Pattern match should be moved to the start of the new name. .PARAMETER Top A number indicating how many items to process. If it is known that the number of items that will be candidates to be renamed is large, the user can limit this is the first $Top number of items. This is typically used as an exploratory tool, to determine the effects of the rename operation. .PARAMETER Transform A script block which is given the chance to perform a modification to the finally named item. The transform is invoked prior to post-processing, so that the post-processing rules are not breached and the transform does not have to worry about breaking them. The transform function's signature is as follows: * Original: original item's name * Renamed: new name * CapturedPattern: pattern capture and should return the new name. If the transform does not change the name, it should return an empty string. .PARAMETER Whole Provides an alternative way to indicate that the regular expression parameters should be treated as a whole word (it just wraps the expression inside \b tokens). If set to '*', then it applies to all expression parameters otherwise a single letter can specify which of the parameters 'Whole' should be applied to. Valid values are: * 'p': $Pattern * 'a': $Anchor * 'c': $Copy * 'i': $Include * 'x': $Exclude * '*': All the above (NB: Currently, can't be set to more than 1 of the above items at a time) .PARAMETER With This is a NON regular expression string. It would be more accurately described as a formatter, similar to the $Paste parameter. Defines what text is used as the replacement for the $Pattern match. Works in concert with $Relation (whereas $Paste does not). $With can reference special variables: * $0: the pattern match * ${_a}: the anchor match * ${_c}: the copy match When $Pattern contains named capture groups, these variables can also be referenced. Eg if the $Pattern is defined as '(?<day>\d{1,2})-(?<mon>\d{1,2})-(?<year>\d{4})', then the variables ${day}, ${mon} and ${year} also become available for use in $With or $Paste. Typically, $With is static text which is used to replace the $Pattern match and is inserted according to the Anchor match, (or indeed $Start or $End) and $Relation. When using $With, whatever is defined in the $Anchor match is not removed from the pipeline's name (this is different to how $Paste works). If neither $With or Paste have been specified, then the rename operation becomes a 'Cut' operation and will be indicated as such in the batch summary. .PARAMETER underscore The pipeline item which should either be an instance of FileInfo or DirectoryInfo. .EXAMPLE 1 Move a static string before anchor (consider file items only): gci ... | Rename-Many -File -Pattern 'data' -Anchor 'loopz' -Relation 'before' .EXAMPLE 2 Move last occurrence of whole-word static string before anchor: gci ... | Rename-Many -Pattern 'data',l -Anchor 'loopz' -Relation 'before' -Whole p .EXAMPLE 3 Move a static string before anchor and drop (consider Directory items only): gci ... | Rename-Many -Directory -Pattern 'data' -Anchor 'loopz' -Relation 'before' -Drop '-' .EXAMPLE 4 Update a static string using $With (consider file items only): gci ... | Rename-Many -File -Pattern 'data' -With 'info' .EXAMPLE 5 Update last occurrence of whole-word static string using $With: gci ... | Rename-Many -Pattern 'data',l -With 'info' -Whole p .EXAMPLE 6 Update a static string using $Paste: gci ... | Rename-Many -Pattern 'data' -Paste '_info_' .EXAMPLE 7 Update last occurrence of whole-word static string using $Paste: gci ... | Rename-Many -Pattern 'data',l -Whole p -Paste '_info_' .EXAMPLE 8 Move a match before anchor: gci ... | Rename-Many -Pattern '\d{2}-data' -Anchor 'loopz' -Relation 'before' .EXAMPLE 9 Move last occurrence of whole-word static string before anchor: gci ... | Rename-Many -Pattern '\d{2}-data',l -Anchor 'loopz' -Relation 'before' -Whole p .EXAMPLE 10 Move a match before anchor and drop: gci ... | Rename-Many -Pattern '\d{2}-data' -Anchor 'loopz' -Relation 'before' -Drop '-' .EXAMPLE 11 Update a match using $With: gci ... | Rename-Many -Pattern '\d{2}-data' -With 'info' .EXAMPLE 12 Update last occurrence of whole-word match using $With: gci ... | Rename-Many -Pattern '\d{2}-data',l -With 'info' -Whole p .EXAMPLE 13 Update match contain named capture group using $With: gci ... | Rename-Many -Pattern '(?<day>\d{2})-(?<mon>\d{2})-(?<year>\d{2})' -With '(${year})-(${mon})-(${day})' .EXAMPLE 14 Update 2nd occurrence of whole-word match using $Paste and preserve anchor: gci ... | Rename-Many -Pattern '\d{2}-data', l -Paste '${_a}_info_' .EXAMPLE 15 Update match contain named capture group using $Paste and preserve the anchor: gci ... | Rename-Many -Pattern (?<day>\d{2})-(?<mon>\d{2})-(?<year>\d{2}) -Paste '(${year})-(${mon})-(${day}) ${_a}' .EXAMPLE 16 Update match contain named capture group using $Paste and preserve the anchor and copy whole last occurrence: gci ... | Rename-Many -Pattern (?<day>\d{2})-(?<mon>\d{2})-(?<year>\d{2}) -Copy '[A-Z]{3}',l -Whole c -Paste 'CCY_${_c} (${year})-(${mon})-(${day}) ${_a}' #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '', Justification = 'WhatIf IS accessed and passed into Exchange')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingEmptyCatchBlock', '')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'ReplaceWith')] [Alias('remy')] param ( # Defining parameter sets for File and Directory, just to ensure both of these switches # are mutually exclusive makes the whole parameter set definition exponentially more # complex. It's easier just to enforce this with a ValidateScript. # [Parameter()] [ValidateScript( { -not($PSBoundParameters.ContainsKey('Directory')); })] [switch]$File, [Parameter()] [ValidateScript( { -not($PSBoundParameters.ContainsKey('File')); })] [switch]$Directory, [Parameter(Mandatory, ValueFromPipeline = $true)] [System.IO.FileSystemInfo]$underscore, [Parameter()] [ValidateSet('p', 'a', 'c', 'i', 'x', '*')] [string]$Whole, [Parameter(Mandatory, Position = 0)] [ValidateScript( { { $(test-ValidPatternArrayParam -Arg $_ -AllowWildCard ) } })] [array]$Pattern, [Parameter(ParameterSetName = 'MoveToAnchor', Mandatory)] [ValidateScript( { $(test-ValidPatternArrayParam -Arg $_) })] [array]$Anchor, [Parameter(ParameterSetName = 'MoveToAnchor')] [ValidateSet('before', 'after')] [string]$Relation = 'after', [Parameter(ParameterSetName = 'MoveToAnchor')] [Parameter(ParameterSetName = 'ReplaceWith')] [ValidateScript( { { $(test-ValidPatternArrayParam -Arg $_) } })] [array]$Copy, [Parameter(ParameterSetName = 'ReplaceLiteralWith', Mandatory)] [string]$With, [Parameter()] [Alias('x')] [string]$Except = [string]::Empty, [Parameter()] [Alias('i')] [string]$Include, [Parameter()] [scriptblock]$Condition = ( { return $true; }), # Both Start & End are members of ReplaceWith, but they shouldn't be supplied at # the same time. So how to prevent this? Use ValidateScript instead. # [Parameter(ParameterSetName = 'ReplaceWith')] [Parameter(ParameterSetName = 'MoveToStart', Mandatory)] [ValidateScript( { -not($PSBoundParameters.ContainsKey('End')); })] [switch]$Start, [Parameter(ParameterSetName = 'ReplaceWith')] [Parameter(ParameterSetName = 'MoveToEnd', Mandatory)] [ValidateScript( { -not($PSBoundParameters.ContainsKey('Start')); })] [switch]$End, [Parameter()] [string]$Paste, [Parameter()] [PSCustomObject]$Context = $Loopz.Defaults.Remy.Context, [Parameter()] [switch]$Diagnose, [Parameter()] [string]$Drop, [Parameter()] [ValidateScript( { $_ -gt 0 } )] [int]$Top, [Parameter()] [scriptblock]$Transform ) begin { Write-Debug ">>> Rename-Many [ParameterSet: '$($PSCmdlet.ParameterSetName)]' >>>"; function get-fixedIndent { [OutputType([int])] param( [Parameter()] [hashtable]$Theme, [Parameter()] [string]$Message = [string]::Empty ) [int]$indent = $Message.Length; # 1 2 3 4 # 1234567890123456789012345678901234567890 # [🏷️] Rename Item // ["No" => " 1", # |<-- fixed bit -->| # $indent += $Theme['MESSAGE-SUFFIX'].Length; $indent += $Theme['OPEN'].Length; $indent += $Theme['FORMAT'].Replace($Theme['KEY-PLACE-HOLDER'], "No").Replace( $Theme['VALUE-PLACE-HOLDER'], '999').Length; $indent += $Theme['SEPARATOR'].Length; return $indent; } [scriptblock]$doRenameFsItems = { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] param( [Parameter(Mandatory)] [System.IO.FileSystemInfo]$_underscore, [Parameter(Mandatory)] [int]$_index, [Parameter(Mandatory)] [hashtable]$_exchange, [Parameter(Mandatory)] [boolean]$_trigger ) [boolean]$itemIsDirectory = ($_underscore.Attributes -band [System.IO.FileAttributes]::Directory) -eq [System.IO.FileAttributes]::Directory; $endAdapter = New-EndAdapter($_underscore); [string]$adjustedName = $endAdapter.GetAdjustedName(); [string]$action = $_exchange['LOOPZ.REMY.ACTION']; [hashtable]$actionParameters = @{ 'Value' = $adjustedName; 'Pattern' = $_exchange['LOOPZ.REMY.PATTERN-REGEX']; } [boolean]$performDiagnosis = ($_exchange.ContainsKey('LOOPZ.DIAGNOSE') -and $_exchange['LOOPZ.DIAGNOSE']); $actionParameters['PatternOccurrence'] = $_exchange.ContainsKey('LOOPZ.REMY.PATTERN-OCC') ` ? $_exchange['LOOPZ.REMY.PATTERN-OCC'] : 'f'; if ($_exchange.ContainsKey('LOOPZ.REMY.COPY')) { $actionParameters['Copy'] = $_exchange['LOOPZ.REMY.COPY']; if ($_exchange.ContainsKey('LOOPZ.REMY.COPY-OCC')) { $actionParameters['CopyOccurrence'] = $_exchange['LOOPZ.REMY.COPY-OCC']; } } elseif ($_exchange.ContainsKey('LOOPZ.REMY.WITH')) { $actionParameters['With'] = $_exchange['LOOPZ.REMY.WITH']; } if ($_exchange.ContainsKey('LOOPZ.REMY.PASTE')) { $actionParameters['Paste'] = $_exchange['LOOPZ.REMY.PASTE'] } if ($performDiagnosis) { $actionParameters['Diagnose'] = $_exchange['LOOPZ.DIAGNOSE'] } if ($action -eq 'Move-Match') { if ($_exchange.ContainsKey('LOOPZ.REMY.ANCHOR')) { $actionParameters['Anchor'] = $_exchange['LOOPZ.REMY.ANCHOR']; } if ($_exchange.ContainsKey('LOOPZ.REMY.ANCHOR-OCC')) { $actionParameters['AnchorOccurrence'] = $_exchange['LOOPZ.REMY.ANCHOR-OCC']; } if ($_exchange.ContainsKey('LOOPZ.REMY.DROP')) { $actionParameters['Drop'] = $_exchange['LOOPZ.REMY.DROP']; $actionParameters['Marker'] = $_exchange['LOOPZ.REMY.MARKER']; } switch ($_exchange['LOOPZ.REMY.ANCHOR-TYPE']) { 'MATCHED-ITEM' { if ($_exchange.ContainsKey('LOOPZ.REMY.RELATION')) { $actionParameters['Relation'] = $_exchange['LOOPZ.REMY.RELATION']; } break; } 'START' { $actionParameters['Start'] = $true; break; } 'END' { $actionParameters['End'] = $true; break; } default { throw "doRenameFsItems: encountered Invalid 'LOOPZ.REMY.ANCHOR-TYPE': '$AnchorType'"; } } } # $action [line]$properties = [line]::new(); [line[]]$lines = @(); [hashtable]$signals = $_exchange['LOOPZ.SIGNALS']; # Perform Rename Action, then post process # [PSCustomObject]$actionResult = & $action @actionParameters; [string]$newItemName = $actionResult.Payload; if ($_exchange.ContainsKey('LOOPZ.REMY.TRANSFORM')) { [scriptblock]$transform = $_exchange['LOOPZ.REMY.TRANSFORM']; if ($transform) { [string]$transformed = $transform.InvokeReturnAsIs( $_underscore.Name, $newItemName, $actionResult.CapturedPattern); if (-not([string]::IsNullOrEmpty($transformed))) { $newItemName = $transformed; } } } $postResult = invoke-PostProcessing -InputSource $newItemName -Rules $Loopz.Rules.Remy ` -Signals $signals; if ($postResult.Modified) { [couplet]$postSignal = Get-FormattedSignal -Name 'REMY.POST' ` -Signals $signals -Value $postResult.Indication -CustomLabel $postResult.Label; $properties.append($postSignal); $newItemName = $postResult.TransformResult; } $newItemName = $endAdapter.GetNameWithExtension($newItemName); Write-Debug "Rename-Many; New Item Name: '$newItemName'"; [boolean]$trigger = $false; [boolean]$affirm = $false; [boolean]$whatIf = $_exchange.ContainsKey('WHAT-IF') -and ($_exchange['WHAT-IF']); [string]$parent = $itemIsDirectory ? $_underscore.Parent.FullName : $_underscore.Directory.FullName; [boolean]$nameHasChanged = -not($_underscore.Name -ceq $newItemName); [string]$newItemFullPath = Join-Path -Path $parent -ChildPath $newItemName; [boolean]$clash = (Test-Path -LiteralPath $newItemFullPath) -and $nameHasChanged; [string]$fileSystemItemType = $itemIsDirectory ? 'Directory' : 'File'; [PSCustomObject]$context = $_exchange['LOOPZ.REMY.CONTEXT']; [int]$maxItemMessageSize = $_exchange['LOOPZ.REMY.MAX-ITEM-MESSAGE-SIZE']; [string]$normalisedItemMessage = $Context.ItemMessage.replace( $Loopz.FsItemTypePlaceholder, $fileSystemItemType); [string]$messageLabel = if ($context.psobject.properties.match('ItemMessage') -and ` -not([string]::IsNullOrEmpty($Context.ItemMessage))) { Get-PaddedLabel -Label $($Context.ItemMessage.replace( $Loopz.FsItemTypePlaceholder, $fileSystemItemType)) -Width $maxItemMessageSize; } else { $normalisedItemMessage; } [string]$signalName = $itemIsDirectory ? 'DIRECTORY-A' : 'FILE-A'; [string]$message = Get-FormattedSignal -Name $signalName ` -Signals $signals -CustomLabel $messageLabel -Format ' [{1}] {0}'; [int]$indent = $_exchange['LOOPZ.REMY.FIXED-INDENT'] + $message.Length; $_exchange['LOOPZ.WH-FOREACH-DECORATOR.INDENT'] = $indent; $_exchange['LOOPZ.WH-FOREACH-DECORATOR.MESSAGE'] = $message; $_exchange['LOOPZ.WH-FOREACH-DECORATOR.PRODUCT-LABEL'] = $(Get-PaddedLabel -Label $( $fileSystemItemType) -Width 9); if ($nameHasChanged -and -not($clash)) { $trigger = $true; [UndoRename]$operant = $_exchange.ContainsKey('LOOPZ.REMY.UNDO') ` ? $_exchange['LOOPZ.REMY.UNDO'] : $null; $product = rename-FsItem -From $_underscore -To $newItemName -WhatIf:$whatIf -UndoOperant $operant; } else { $product = $_underscore; } if ($trigger) { $null = $lines += (New-Line( New-Pair(@($_exchange['LOOPZ.REMY.FROM-LABEL'], $_underscore.Name)) )); } else { if ($clash) { Write-Debug "!!! doRenameFsItems; path: '$newItemFullPath' already exists, rename skipped"; [couplet]$clashSignal = Get-FormattedSignal -Name 'CLASH' ` -Signals $signals -EmojiAsValue -EmojiOnlyFormat '{0}'; $properties.append($clashSignal); } else { [couplet]$notActionedSignal = Get-FormattedSignal -Name 'NOT-ACTIONED' ` -Signals $signals -EmojiAsValue -CustomLabel 'Not Renamed' -EmojiOnlyFormat '{0}'; $properties.append($notActionedSignal); } } if (-not($actionResult.Success)) { [couplet]$failedSignal = Get-FormattedSignal -Name 'FAILED-A' ` -Signals $signals -Value $actionResult.FailedReason; $properties.append($failedSignal); } # Do diagnostics # if ($performDiagnosis -and $actionResult.Diagnostics.Named -and ($actionResult.Diagnostics.Named.Count -gt 0)) { [string]$diagnosticEmoji = Get-FormattedSignal -Name 'DIAGNOSTICS' -Signals $signals ` -EmojiOnly; [string]$captureEmoji = Get-FormattedSignal -Name 'CAPTURE' -Signals $signals ` -EmojiOnly -EmojiOnlyFormat '[{0}]'; foreach ($namedItem in $actionResult.Diagnostics.Named) { foreach ($namedKey in $namedItem.Keys) { [hashtable]$groups = $actionResult.Diagnostics.Named[$namedKey]; [string[]]$diagnosticLines = @(); foreach ($groupName in $groups.Keys) { [string]$captured = $groups[$groupName]; [string]$compoundValue = "({0} <{1}>)='{2}'" -f $captureEmoji, $groupName, $captured; [string]$namedLabel = Get-PaddedLabel -Label ($diagnosticEmoji + $namedKey); $diagnosticLines += $compoundValue; } $null = $lines += (New-Line( New-Pair(@($namedLabel, $($diagnosticLines -join ', '))) )); } } } if ($whatIf) { [couplet]$whatIfSignal = Get-FormattedSignal -Name 'WHAT-IF' ` -Signals $signals -EmojiAsValue -EmojiOnlyFormat '{0}'; $properties.append($whatIfSignal); } [PSCustomObject]$result = [PSCustomObject]@{ Product = $product; } $result | Add-Member -MemberType NoteProperty -Name 'Pairs' -Value $properties; if ($lines.Length -gt 0) { $result | Add-Member -MemberType NoteProperty -Name 'Lines' -Value $lines; } if ($trigger) { $result | Add-Member -MemberType NoteProperty -Name 'Trigger' -Value $true; } [boolean]$differsByCaseOnly = $newItemName.ToLower() -eq $_underscore.Name.ToLower(); [boolean]$affirm = $trigger -and ($product) -and -not($differsByCaseOnly); if ($affirm) { $result | Add-Member -MemberType NoteProperty -Name 'Affirm' -Value $true; } return $result; } # doRenameFsItems [System.IO.FileSystemInfo[]]$collection = @(); } # begin process { Write-Debug "=== Rename-Many [$($underscore.Name)] ==="; $collection += $underscore; } end { Write-Debug '<<< Rename-Many <<<'; [boolean]$locked = Get-IsLocked -Variable $( [string]::IsNullOrEmpty($Context.Locked) ? 'LOOPZ_REMY_LOCKED' : $Context.Locked ); [boolean]$whatIf = $PSBoundParameters.ContainsKey('WhatIf') -or $locked; [PSCustomObject]$containers = @{ Wide = [line]::new(); Props = [line]::new(); } [string]$adjustedWhole = if ($PSBoundParameters.ContainsKey('Whole')) { $Whole.ToLower(); } else { [string]::Empty; } [hashtable]$signals = $(Get-Signals); # RegEx/Occurrence parameters # [string]$patternExpression, [string]$patternOccurrence = Resolve-PatternOccurrence $Pattern Select-SignalContainer -Containers $containers -Name 'PATTERN' ` -Value $patternExpression -Signals $signals; if ($PSBoundParameters.ContainsKey('Anchor')) { [string]$anchorExpression, [string]$anchorOccurrence = Resolve-PatternOccurrence $Anchor Select-SignalContainer -Containers $containers -Name 'REMY.ANCHOR' ` -Value $anchorExpression -Signals $signals -CustomLabel $('Anchor ({0})' -f $Relation); } if ($PSBoundParameters.ContainsKey('Copy')) { [string]$copyExpression, [string]$copyOccurrence = Resolve-PatternOccurrence $Copy; Select-SignalContainer -Containers $containers -Name 'COPY-A' ` -Value $copyExpression -Signals $signals; } elseif ($PSBoundParameters.ContainsKey('With')) { if (-not([string]::IsNullOrEmpty($With))) { Select-SignalContainer -Containers $containers -Name 'WITH' ` -Value $With -Signals $signals; } elseif (-not($PSBoundParameters.ContainsKey('Paste'))) { Select-SignalContainer -Containers $containers -Name 'CUT-A' ` -Value $patternExpression -Signals $signals -Force 'Props'; } } if ($PSBoundParameters.ContainsKey('Include')) { [string]$includeExpression, [string]$includeOccurrence = Resolve-PatternOccurrence $Include; Select-SignalContainer -Containers $containers -Name 'INCLUDE' ` -Value $includeExpression -Signals $signals; } if ($PSBoundParameters.ContainsKey('Diagnose')) { [string]$switchOnEmoji = $signals['SWITCH-ON'].Value; [couplet]$diagnosticsSignal = Get-FormattedSignal -Name 'DIAGNOSTICS' ` -Signals $signals -Value $('[{0}]' -f $switchOnEmoji); $containers.Props.Line += $diagnosticsSignal; } [boolean]$doMoveToken = ($PSBoundParameters.ContainsKey('Anchor') -or $PSBoundParameters.ContainsKey('Start') -or $PSBoundParameters.ContainsKey('End')); if ($doMoveToken -and ($patternOccurrence -eq '*')) { [string]$errorMessage = "'Pattern' wildcard prohibited for move operation (Anchor/Start/End).`r`n"; $errorMessage += "Please use a digit, 'f' (first) or 'l' (last) for Pattern Occurrence"; Write-Error $errorMessage -ErrorAction Stop; } [boolean]$doCut = ( -not($doMoveToken) -and -not($PSBoundParameters.ContainsKey('Copy')) -and -not($PSBoundParameters.ContainsKey('With')) -and -not($PSBoundParameters.ContainsKey('Paste')) ) if ($doCut) { Select-SignalContainer -Containers $containers -Name 'CUT-A' ` -Value $patternExpression -Signals $signals -Force 'Props'; } if ($PSBoundParameters.ContainsKey('Paste')) { if (-not(Test-IsFileSystemSafe -Value $Paste)) { throw [System.ArgumentException]::new("Paste parameter ('$Paste') contains unsafe characters") } if (-not([string]::IsNullOrEmpty($Paste))) { Select-SignalContainer -Containers $containers -Name 'PASTE-A' ` -Value $Paste -Signals $signals; } } [scriptblock]$getResult = { param($result) $result.GetType() -in @([System.IO.FileInfo], [System.IO.DirectoryInfo]) ? $result.Name : $result; } [regex]$patternRegEx = New-RegularExpression -Expression $patternExpression ` -WholeWord:$(-not([string]::IsNullOrEmpty($adjustedWhole)) -and ($adjustedWhole -in @('*', 'p'))); [string]$title = $Context.psobject.properties.match('Title') -and ` -not([string]::IsNullOrEmpty($Context.Title)) ` ? $Context.Title : 'Rename'; if ($locked) { $title = Get-FormattedSignal -Name 'LOCKED' -Signals $signals ` -Format '{1} {0} {1}' -CustomLabel $('Locked: ' + $title); } [int]$maxItemMessageSize = $Context.ItemMessage.replace( $Loopz.FsItemTypePlaceholder, 'Directory').Length; [string]$summaryMessage = $Context.psobject.properties.match('SummaryMessage') -and ` -not([string]::IsNullOrEmpty($Context.SummaryMessage)) ` ? $Context.SummaryMessage : 'Rename Summary'; $summaryMessage = Get-FormattedSignal -Name 'SUMMARY-A' -Signals $signals -CustomLabel $summaryMessage; [hashtable]$theme = $(Get-KrayolaTheme); [Krayon]$krayon = New-Krayon -Theme $theme; [hashtable]$exchange = @{ 'LOOPZ.WH-FOREACH-DECORATOR.BLOCK' = $doRenameFsItems; 'LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT' = $getResult; 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL' = 'CRUMB-A'; 'LOOPZ.HEADER-BLOCK.LINE' = $LoopzUI.DashLine; 'LOOPZ.HEADER-BLOCK.MESSAGE' = $title; 'LOOPZ.SUMMARY-BLOCK.LINE' = $LoopzUI.EqualsLine; 'LOOPZ.SUMMARY-BLOCK.MESSAGE' = $summaryMessage; 'LOOPZ.REMY.PATTERN-REGEX' = $patternRegEx; 'LOOPZ.REMY.PATTERN-OCC' = $patternOccurrence; 'LOOPZ.REMY.CONTEXT' = $Context; 'LOOPZ.REMY.MAX-ITEM-MESSAGE-SIZE' = $maxItemMessageSize; 'LOOPZ.REMY.FIXED-INDENT' = $(get-fixedIndent -Theme $theme); 'LOOPZ.REMY.FROM-LABEL' = Get-PaddedLabel -Label 'From' -Width 9; 'LOOPZ.SIGNALS' = $signals; 'LOOPZ.KRAYON' = $krayon; } $exchange['LOOPZ.REMY.ACTION'] = $doMoveToken ? 'Move-Match' : 'Update-Match'; if ($PSBoundParameters.ContainsKey('Copy')) { [regex]$copyRegEx = New-RegularExpression -Expression $copyExpression ` -WholeWord:$(-not([string]::IsNullOrEmpty($adjustedWhole)) -and ($adjustedWhole -in @('*', 'c'))); $exchange['LOOPZ.REMY.COPY-OCC'] = $copyOccurrence; $exchange['LOOPZ.REMY.COPY'] = $copyRegEx; } elseif ($PSBoundParameters.ContainsKey('With')) { if (-not(Test-IsFileSystemSafe -Value $With)) { throw [System.ArgumentException]::new("With parameter ('$With') contains unsafe characters") } $exchange['LOOPZ.REMY.WITH'] = $With; } if ($PSBoundParameters.ContainsKey('Relation')) { $exchange['LOOPZ.REMY.RELATION'] = $Relation; } # NB: anchoredRegEx refers to whether -Start or -End anchors have been specified, # NOT the -Anchor pattern (when ANCHOR-TYPE = 'MATCHED-ITEM') itself. # [regex]$anchoredRegEx = $null; if ($PSBoundParameters.ContainsKey('Anchor')) { [regex]$anchorRegEx = New-RegularExpression -Expression $anchorExpression ` -WholeWord:$(-not([string]::IsNullOrEmpty($adjustedWhole)) -and ($adjustedWhole -in @('*', 'a'))); $exchange['LOOPZ.REMY.ANCHOR-OCC'] = $anchorOccurrence; $exchange['LOOPZ.REMY.ANCHOR-TYPE'] = 'MATCHED-ITEM'; $exchange['LOOPZ.REMY.ANCHOR'] = $anchorRegEx; } elseif ($PSBoundParameters.ContainsKey('Start')) { Select-SignalContainer -Containers $containers -Name 'REMY.ANCHOR' ` -Value $signals['SWITCH-ON'].Value -Signals $signals -CustomLabel 'Start' -Force 'Props'; $exchange['LOOPZ.REMY.ANCHOR-TYPE'] = 'START'; [regex]$anchoredRegEx = New-RegularExpression ` -Expression $('^' + $patternExpression); } elseif ($PSBoundParameters.ContainsKey('End')) { Select-SignalContainer -Containers $containers -Name 'REMY.ANCHOR' ` -Value $signals['SWITCH-ON'].Value -Signals $signals -CustomLabel 'End' -Force 'Props'; $exchange['LOOPZ.REMY.ANCHOR-TYPE'] = 'END'; [regex]$anchoredRegEx = New-RegularExpression ` -Expression $($patternExpression + '$'); } if ($PSBoundParameters.ContainsKey('Drop') -and -not([string]::IsNullOrEmpty($Drop))) { Select-SignalContainer -Containers $containers -Name 'REMY.DROP' ` -Value $Drop -Signals $signals -Force 'Wide'; $exchange['LOOPZ.REMY.DROP'] = $Drop; $exchange['LOOPZ.REMY.MARKER'] = $Loopz.Defaults.Remy.Marker; } if ($locked) { Select-SignalContainer -Containers $containers -Name 'NOVICE' ` -Value $signals['SWITCH-ON'].Value -Signals $signals -Force 'Wide'; } [boolean]$includeDefined = $PSBoundParameters.ContainsKey('Include'); [regex]$includeRegEx = $includeDefined ` ? (New-RegularExpression -Expression $includeExpression ` -WholeWord:$(-not([string]::IsNullOrEmpty($adjustedWhole)) -and ($adjustedWhole -in @('*', 'i')))) ` : $null; if ($PSBoundParameters.ContainsKey('Paste')) { $exchange['LOOPZ.REMY.PASTE'] = $Paste; } if ($PSBoundParameters.ContainsKey('Transform')) { $exchange['LOOPZ.REMY.TRANSFORM'] = $Transform; Select-SignalContainer -Containers $containers -Name 'TRANSFORM' ` -Value $signals['SWITCH-ON'].Value -Signals $signals -Force 'Wide'; } [PSCustomObject]$operantOptions = [PSCustomObject]@{ ShortCode = $Context.OperantShortCode; OperantName = 'UndoRename'; Shell = 'PoShShell'; BaseFilename = 'undo-rename'; DisabledEnVar = $Context.UndoDisabledEnVar; } [UndoRename]$operant = Initialize-ShellOperant -Options $operantOptions -DryRun:$whatIf; if ($operant) { $exchange['LOOPZ.REMY.UNDO'] = $operant; Select-SignalContainer -Containers $containers -Name 'REMY.UNDO' ` -Value $operant.Shell.FullPath -Signals $signals -Force 'Wide'; } else { Select-SignalContainer -Containers $containers -Name 'REMY.UNDO' ` -Value $signals['SWITCH-OFF'].Value -Signals $signals -Force 'Wide'; } if ($containers.Wide.Line.Length -gt 0) { $exchange['LOOPZ.SUMMARY-BLOCK.WIDE-ITEMS'] = $containers.Wide; } if ($containers.Props.Line.Length -gt 0) { $exchange['LOOPZ.SUMMARY.PROPERTIES'] = $containers.Props; } [scriptblock]$clientCondition = $Condition; [scriptblock]$compoundCondition = { param( [System.IO.FileSystemInfo]$pipelineItem ) [boolean]$clientResult = $clientCondition.InvokeReturnAsIs($pipelineItem); [boolean]$isAlreadyAnchoredAt = $anchoredRegEx -and $anchoredRegEx.IsMatch($pipelineItem.Name); return $($clientResult -and -not($isAlreadyAnchoredAt)); }; [regex]$excludedRegEx = [string]::IsNullOrEmpty($Except) ` ? $null : $(New-RegularExpression -Expression $Except); [scriptblock]$matchesPattern = { param( [System.IO.FileSystemInfo]$pipelineItem ) # Inside the scope of this script block, $Condition is assigned to Invoke-ForeachFsItem's # version of the Condition parameter which is this scriptblock and thus results in a stack # overflow due to infinite recursion. We need to use a temporary variable so that # the client's Condition (Rename-Many) is not accidentally hidden. # [boolean]$isIncluded = $includeDefined ? $includeRegEx.IsMatch($pipelineItem.Name) : $true; return ($patternRegEx.IsMatch($pipelineItem.Name)) -and $isIncluded -and ` ((-not($excludedRegEx)) -or -not($excludedRegEx.IsMatch($pipelineItem.Name))) -and ` $compoundCondition.InvokeReturnAsIs($pipelineItem); } [hashtable]$parameters = @{ 'Condition' = $matchesPattern; 'Exchange' = $exchange; 'Header' = $LoopzHelpers.HeaderBlock; 'Summary' = $LoopzHelpers.SummaryBlock; 'Block' = $LoopzHelpers.WhItemDecoratorBlock; } if ($PSBoundParameters.ContainsKey('File')) { $parameters['File'] = $true; } elseif ($PSBoundParameters.ContainsKey('Directory')) { $parameters['Directory'] = $true; } if ($PSBoundParameters.ContainsKey('Top')) { $parameters['Top'] = $Top; } if ($whatIf -or $Diagnose.ToBool()) { $exchange['WHAT-IF'] = $true; } if ($Diagnose.ToBool()) { $exchange['LOOPZ.DIAGNOSE'] = $true; } try { $null = $collection | Invoke-ForeachFsItem @parameters; } catch { # ctrl-c doesn't invoke an exception, it just abandons processing, # ending up in the finally block. # Write-Host $_.Exception.StackTrace; Write-Error $_.Exception.Message; } finally { # catch ctrl-c if ($operant -and -not($whatIf)) { $operant.finalise(); } } } # end } # Rename-Many function Select-Patterns { <# .NAME Select-Patterns .SYNOPSIS This is a simplified yet enhanced version of standard Select-String command (or the grep command on Linux/Unix/mac) that allows the user to run multiple searches which are chained together to produce its final result. .DESCRIPTION The main rationale for using this command ("greps" as in multiple grep invokes) instead of Select-String, is for the provision of multiple patterns. Now, Select-String does allow the user to provide multiple Patterns, but the result is a logical OR rather than an AND. greps uses AND by piping the result of each individual Pattern search to the next Pattern search so the result is those lines found that match all the patterns provided rather than all lines that match 1 or more of the patterns. The user can achieve OR functionality by using a | inside the same string; for example to find all lines that contain any of the patterns 'red', 'green' or 'blue', they could just use 'red|green|blue'. At the end of the run, greps displays the full command (containing multiple pipeline legs, one for each pattern provided). If so required, the user can re-run the command by running the full command which is displayed and providing different parameters not directly supported by greps. 'greps', does not currently support input from the pipeline. Perhaps this will be implemented in a future release. At some point in the future, it is intended to further enhance greps using a coloured output, whereby a colour is assigned to each pattern and that colour is used to render the result. So where the user has provided multiple patterns, currently, only the first pattern is highlighted in the result. With the coloured enhancement, the user will be able to see all pattern matches in the result with each match displayed in the corresponding allocated colour. .PARAMETER filter Defines which files are considered in the search. It can be a path with a wildcard or simply a wildcard. If its just a wildcard (eg *.txt), then files considered will be from the current directory only. The user can define a default filter in the environment as variable 'LOOPZ_GREPS_FILTER' which should be a glob such as '*.txt' to represent all text files. If no filter parameter is supplied to the greps invoke, then the filter is defined by the value of 'LOOPZ_GREPS_FILTER'. .PARAMETER Patterns An array of patterns. The result shows all lines that match all the patterns specified. An individual pattern can be prefixed with a not op: '!', which means exclude those lines which match the subsequent pattern; it is a more succinct way of specifying the -NotMatch operator on Select-String. The '!' is not part of the pattern. .EXAMPLE 1 Show lines in all .txt files in the current directory files that contain the patterns 'red' and 'blue': greps red, blue *.txt .EXAMPLE 2 Show lines in all .txt files in home directory that contain the patterns 'green lorry' and 'yellow lorry': greps 'green lorry', 'yellow lorry' ~/*.txt .EXAMPLE 3 Show lines in all files defined in environment as 'LOOPZ_GREPS_FILTER' that contains 'foo' but not 'bar': greps foo, !bar #> [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '')] [Alias("greps")] param ( [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [String[]]$Patterns, [parameter(Position = 1)] [String]$Filter = $(Get-EnvironmentVariable -Variable 'LOOPZ_GREPS_FILTER' -Default './*.*') ) function build-command { [OutputType([string])] param( [String]$Pattern, [String]$Filter, [Switch]$Pipe, [string]$NotOpSymbol = '!' ) [string]$platform = Get-PlatformName; [string]$builder = [string]::Empty; if ($Pipe.ToBool()) { $builder += ' | '; } if ($platform -eq 'windows') { $builder += 'select-string '; if ($pattern.StartsWith($NotOpSymbol)) { $builder += ('-notmatch -pattern "{0}" ' -f $Pattern.Substring(1)); } else { $builder += ('-pattern "{0}" ' -f $Pattern); } } else { $builder += 'grep '; if ($pattern.StartsWith($NotOpSymbol)) { $builder += ('-v -i "{0}" ' -f $Pattern.Substring(1)); } else { $builder += ('-i "{0}" ' -f $Pattern); } } if (-not([string]::IsNullOrWhiteSpace($Filter))) { $builder += "$Filter "; } return $builder; } # build-command [string]$command = [string]::Empty; [int]$count = 0; foreach ($pat in $Patterns) { $count++; if ($count -eq 1) { $command = build-command -Pattern $Patterns[0] -Filter $Filter; } else { $segment = build-command -Pipe -Pattern $pat; $command += $segment; } } [hashtable]$signals = $(Get-Signals); [hashtable]$theme = $(Get-KrayolaTheme); [Krayon]$krayon = New-Krayon -Theme $theme; [couplet]$formattedSignal = Get-FormattedSignal -Name 'GREPS' -Value $command -Signals $signals; Invoke-Expression $command; $null = $krayon.blue().Text($formattedSignal.Key). ` red().Text(' --> '). ` green().Text($formattedSignal.Value); } function Show-Signals { <# .NAME Show-Signals .SYNOPSIS Shows all defined signals, including user defined signals. .DESCRIPTION User can override signal definitions in their profile, typically using the provided function Update-CustomSignals. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] param( [Parameter()] [hashtable]$SourceSignals = $(Get-Signals), [Parameter()] [hashtable]$Custom = $global:Loopz.CustomSignals ) $result = $SourceSignals; [hashtable]$collection = @{} $result.GetEnumerator() | ForEach-Object { $collection[$_.Key] = [PSCustomObject]@{ Label = $_.Value.Key; Icon = $_.Value.Value; Length = $_.Value.Value.Length } } # result is array, because of the sort # $result = $collection.GetEnumerator() | Sort-Object -Property Name; return $result; } function Update-CustomSignals { param( [Parameter(Mandatory)] [hashtable]$Signals ) if ($Signals -and ($Signals.Count -gt 0)) { if ($Loopz) { if (-not($Loopz.CustomSignals)) { $Loopz.CustomSignals = @{} } $Signals.GetEnumerator() | ForEach-Object { if ($_.Value -and ($_.Value -is [couplet])) { $Loopz.CustomSignals[$_.Key] = $_.Value; } else { Write-Warning "Loopz: Skipping custom signal('$($_.Key)'); not a valid couplet/pair: -->$($_.Value)<--"; } } } } } function Format-Escape { <# .NAME Format-Escape .SYNOPSIS Escapes the regular expression specified. This is just a wrapper around the .net regex::escape method, but gives the user a much easier way to invoke it from the command line. .DESCRIPTION Various functions in Loopz have parameters that accept a regular expression. This function gives the user an easy way to escape the regex, without them having to do this manually themselves which could be tricky to get right depending on their requirements. .PARAMETER Source The source string to escape. #> [Alias('esc')] [OutputType([string])] param( [Parameter(Position = 0, Mandatory)]$Source ) [regex]::Escape($Source); } function Get-FormattedSignal { <# .NAME Get-FormattedSignal .SYNOPSIS Controls and standardises the way that signals are displayed. .DESCRIPTION This function enables the display of key/value pairs where the key includes an emoji. The value may also include the emoji depending on how the function is used. Generally, this function returns either a Pair object or a single string. The user can define a format string (or simply use the default) which controls how the signal is displayed. If the function is invoked without a Value, then a formatted string is returned, otherwise a pair object is returned. .PARAMETER CustomLabel An alternative label to display overriding the signal's defined label. .PARAMETER EmojiAsValue switch which changes the result so that the emoji appears as part of the value as opposed to the key. .PARAMETER EmojiOnly Changes what is returned, to be a single value only, formatted as EmojiOnlyFormat. .PARAMETER EmojiOnlyFormat When the switch EmojiOnly is enabled, EmojiOnlyFormat defines the format used to create the result. Should contain at least 1 occurrence of {1} representing the emoji. .PARAMETER Format A string defining the format defining how the signal is displayed. Should contain either {0} representing the signal's emoji or {1} the label. They can appear as many time as is required, but there should be at least either one of these. .PARAMETER Name The name of the signal .PARAMETER Signals The signals hashtable collection from which to select the signal from. .PARAMETER Value A string defining the Value displayed when the signal is a Key/Value pair. #> param( [Parameter(Mandatory)] [string]$Name, [Parameter()] [string]$Format = '[{1}] {0}', # 0=Label, 1=Emoji [Parameter()] [string]$Value, [Parameter()] [hashtable]$Signals = $(Get-Signals), [Parameter()] [string]$CustomLabel, [Parameter()] [string]$EmojiOnlyFormat = '[{0}] ', [Parameter()] [switch]$EmojiOnly, [Parameter()] [switch]$EmojiAsValue ) [couplet]$signal = $Signals.ContainsKey($Name) ` ? $Signals[$Name] ` : $(New-Pair(@($("??? ({0})" -f $Name), $(Resolve-ByPlatform -Hash $Loopz.MissingSignal).Value))); [string]$label = ($PSBoundParameters.ContainsKey('CustomLabel') -and (-not([string]::IsNullOrEmpty($CustomLabel)))) ? $CustomLabel : $signal.Key; [string]$formatted = $EmojiOnly.ToBool() ` ? $EmojiOnlyFormat -f $signal.Value : $Format -f $label, $signal.Value; $result = if ($PSBoundParameters.ContainsKey('Value')) { New-Pair($formatted, $Value); } elseif ($EmojiAsValue.ToBool()) { New-Pair($label, $($EmojiOnlyFormat -f $signal.Value)); } else { $formatted; } return $result; } function Get-PaddedLabel { <# .NAME Get-PaddedLabel .SYNOPSIS Controls and standardises the way that signals are displayed. .DESCRIPTION Pads out a string with leading or trailing spaces depending on alignment. .PARAMETER Align Left or right alignment of the label. .PARAMETER Label The string to be padded .PARAMETER Width Size of the field into which the label is to be placed. #> [OutputType([string])] param( [Parameter()] [string]$Label, [Parameter()] [string]$Align = 'right', [Parameter()] [int]$Width ) [int]$length = $Label.Length; [string]$result = if ($length -lt $Width) { [string]$padding = [string]::new(' ', $($Width - $length)) ($Align -eq 'right') ? $($padding + $Label) : $($Label + $padding); } else { $Label; } $result; } function Get-Signals { <# .NAME Get-Signals .SYNOPSIS Returns a copy of the Signals hashtable. .DESCRIPTION The signals returned include the user defined signal overrides. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] [OutputType([hashtable])] param( [Parameter()] [hashtable]$SourceSignals = $global:Loopz.Signals, [Parameter()] [hashtable]$Custom = $global:Loopz.CustomSignals ) [hashtable]$result = $SourceSignals.Clone(); if ($Custom -and ($Custom.Count -gt 0)) { $Custom.GetEnumerator() | ForEach-Object { try { $result[$_.Key] = $_.Value; } catch { Write-Error "Skipping custom signal: '$($_.Key)'"; } } } return $result; } $global:LoopzHelpers = @{ # Helper Script Blocks # WhItemDecoratorBlock = [scriptblock] { param( [Parameter(Mandatory)] $_underscore, [Parameter(Mandatory)] [int]$_index, [Parameter(Mandatory)] [hashtable]$_exchange, [Parameter(Mandatory)] [boolean]$_trigger ) return Write-HostFeItemDecorator -Underscore $_underscore ` -Index $_index ` -Exchange $_exchange ` -Trigger $_trigger } # WhItemDecoratorBlock HeaderBlock = [scriptblock] { param( [hashtable]$Exchange = @{} ) Show-Header -Exchange $Exchange; } # HeaderBlock SummaryBlock = [scriptblock] { param( [int]$Count, [int]$Skipped, [int]$Errors, [boolean]$Triggered, [hashtable]$Exchange = @{} ) Show-Summary -Count $Count -Skipped $Skipped ` -Errors $Errors -Triggered $Triggered -Exchange $Exchange; } # SummaryBlock } # Session UI state # [int]$global:_LineLength = 121; [int]$global:_SmallLineLength = 81; # $global:LoopzUI = [ordered]@{ # Line definitions: # UnderscoreLine = ([string]::new("_", $_LineLength)); EqualsLine = ([string]::new("=", $_LineLength)); DotsLine = ([string]::new(".", $_LineLength)); DashLine = ([string]::new("-", $_LineLength)); LightDotsLine = (([string]::new(".", (($_LineLength - 1) / 2))).Replace(".", ". ") + "."); LightDashLine = (([string]::new("-", (($_LineLength - 1) / 2))).Replace("-", "- ") + "-"); TildeLine = ([string]::new("~", $_LineLength)); SmallUnderscoreLine = ([string]::new("_", $_SmallLineLength)); SmallEqualsLine = ([string]::new("=", $_SmallLineLength)); SmallDotsLine = ([string]::new(".", $_SmallLineLength)); SmallDashLine = ([string]::new("-", $_SmallLineLength)); SmallLightDotsLine = (([string]::new(".", (($_SmallLineLength - 1) / 2))).Replace(".", ". ") + "."); SmallLightDashLine = (([string]::new("-", (($_SmallLineLength - 1) / 2))).Replace("-", "- ") + "-"); SmallTildeLine = ([string]::new("~", $_SmallLineLength)); } $global:Loopz = [PSCustomObject]@{ InlineCodeToOption = [hashtable]@{ 'm' = 'Multiline'; 'i' = 'IgnoreCase'; 'x' = 'IgnorePatternWhitespace'; 's' = 'Singleline'; 'n' = 'ExplicitCapture'; } FsItemTypePlaceholder = '*{_fileSystemItemType}'; SignalLabel = 0; SignalEmoji = 1; MissingSignal = @{ 'windows' = (New-Pair(@('???', '🔻'))); 'linux' = (New-Pair(@('???', '🔴'))); 'mac' = (New-Pair(@('???', '🔺'))); } # TODO: # - See # * https://devblogs.microsoft.com/commandline/windows-command-line-unicode-and-utf-8-output-text-buffer/ # * https://stackoverflow.com/questions/49476326/displaying-unicode-in-powershell # DefaultSignals = [ordered]@{ # Operations # 'CUT-A' = (New-Pair(@('Cut', '✂️'))); 'CUT-B' = (New-Pair(@('Cut', '🔪'))); 'COPY-A' = (New-Pair(@('Copy', '🍒'))); 'COPY-B' = (New-Pair(@('Copy', '🥒'))); 'MOVE-A' = (New-Pair(@('Move', '🍺'))); 'MOVE-B' = (New-Pair(@('Move', '🍻'))); 'PASTE-A' = (New-Pair(@('Paste', '🌶️'))); 'PASTE-B' = (New-Pair(@('Paste', '🥜'))); 'OVERWRITE-A' = (New-Pair(@('Overwrite', '♻️'))); 'OVERWRITE-B' = (New-Pair(@('Overwrite', '❗'))); # Thingies # 'DIRECTORY-A' = (New-Pair(@('Directory', '📁'))); 'DIRECTORY-B' = (New-Pair(@('Directory', '🗂️'))); 'FILE-A' = (New-Pair(@('File', '🏷️'))); 'FILE-B' = (New-Pair(@('File', '📝'))); 'PATTERN' = (New-Pair(@('Pattern', '🛡️'))); 'WITH' = (New-Pair(@('With', '🍑'))); 'CRUMB-A' = (New-Pair(@('Crumb', '🎯'))); 'CRUMB-B' = (New-Pair(@('Crumb', '🧿'))); 'CRUMB-C' = (New-Pair(@('Crumb', '💎'))); 'SUMMARY-A' = (New-Pair(@('Summary', '🔆'))); 'SUMMARY-B' = (New-Pair(@('Summary', '✨'))); 'MESSAGE' = (New-Pair(@('Message', '🗯️'))); 'CAPTURE' = (New-Pair(@('Capture', '☂️'))); # Media # 'AUDIO' = (New-Pair(@('Audio', '🎶'))); 'TEXT' = (New-Pair(@('Text', '🆎'))); 'DOCUMENT' = (New-Pair(@('Document', '📜'))); 'IMAGE' = (New-Pair(@('Image', '🖼️'))); 'MOVIE' = (New-Pair(@('Movie', '🎬'))); # Indicators # 'WHAT-IF' = (New-Pair(@('WhatIf', '☑️'))); 'WARNING-A' = (New-Pair(@('Warning', '⚠️'))); 'WARNING-B' = (New-Pair(@('Warning', '👻'))); 'SWITCH-ON' = (New-Pair(@('On', '✔️'))); 'SWITCH-OFF' = (New-Pair(@('Off', '❌'))); 'OK-A' = (New-Pair(@('🆗', '🚀'))); 'OK-B' = (New-Pair(@('🆗', '🌟'))); 'BAD-A' = (New-Pair(@('Bad', '💥'))); 'BAD-B' = (New-Pair(@('Bad', '💢'))); 'PROHIBITED' = (New-Pair(@('Prohibited', '🚫'))); 'INCLUDE' = (New-Pair(@('Include', '💠'))); 'SOURCE' = (New-Pair(@('Source', '🎀'))); 'DESTINATION' = (New-Pair(@('Destination', '☀️'))); 'TRIM' = (New-Pair(@('Trim', '🌊'))); 'MULTI-SPACES' = (New-Pair(@('Spaces', '❄️'))); 'DIAGNOSTICS' = (New-Pair(@('Diagnostics', '🧪'))); 'LOCKED' = (New-Pair(@('Locked', '🔐'))); 'NOVICE' = (New-Pair(@('Novice', '🔰'))); 'TRANSFORM' = (New-Pair(@('Transform', '🤖'))); # Outcomes # 'FAILED-A' = (New-Pair(@('Failed', '☢️'))); 'FAILED-B' = (New-Pair(@('Failed', '💩'))); 'SKIPPED-A' = (New-Pair(@('Skipped', '💤'))); 'SKIPPED-B' = (New-Pair(@('Skipped', '👾'))); 'ABORTED-A' = (New-Pair(@('Aborted', '✖️'))); 'ABORTED-B' = (New-Pair(@('Aborted', '👽'))); 'CLASH' = (New-Pair(@('Clash', '📛'))); 'NOT-ACTIONED' = (New-Pair(@('Not Actioned', '⛔'))); # Command Specific # 'REMY.ANCHOR' = (New-Pair(@('Anchor', '⚓'))); 'REMY.POST' = (New-Pair(@('Post Process', '🌈'))); 'REMY.DROP' = (New-Pair(@('Drop', '💧'))); 'REMY.UNDO' = (New-Pair(@('Undo Rename', '❎'))); 'GREPS' = (New-Pair(@('greps', '🔍'))); } OverrideSignals = @{ # Label, Emoji 'windows' = @{ # defaults based on windows, so there should be no need for overrides }; 'linux' = @{ # tbd }; 'mac' = @{ # tbd }; } # DefaultSignals resolved into Signals by Initialize-Signals # Signals = $null; # User defined signals, should be populated by profile # CustomSignals = $null; Defaults = [PSCustomObject]@{ Remy = [PSCustomObject]@{ Marker = [char]0x2BC1; Context = [PSCustomObject]@{ Title = 'Rename'; ItemMessage = 'Rename Item'; SummaryMessage = 'Rename Summary'; Locked = 'LOOPZ_REMY_LOCKED'; UndoDisabledEnVar = 'LOOPZ_REMY_UNDO_DISABLED'; OperantShortCode = 'remy'; } } } Rules = [PSCustomObject]@{ Remy = [PSCustomObject]@{ Trim = @{ 'IsApplicable' = [scriptblock] { param([string]$_Input) $($_Input.StartsWith(' ') -or $_Input.EndsWith(' ')); }; 'Transform' = [scriptblock] { param([string]$_Input) $_Input.Trim(); }; 'Signal' = 'TRIM' } Spaces = @{ 'IsApplicable' = [scriptblock] { param([string]$_Input) $_Input -match "\s{2,}"; }; 'Transform' = [scriptblock] { param([string]$_Input) $_Input -replace "\s{2,}", ' ' }; 'Signal' = 'MULTI-SPACES' } } } InvalidCharacterSet = [char[]]'<>:"/\|?*'; } function Initialize-ShellOperant { <# .NAME Initialize-ShellOperant .SYNOPSIS Operant factory function. .DESCRIPTION By default all operant related files are stored somewhere inside the home path. Actually, a predefined subpath under home is used. This can be customised by the user by them defining an alternative path (in the environment as 'LOOPZ_PATH'). This alternative path can be relative or absolute. Relative paths are relative to the home directory. The options specify how the operant is created and must be a PSCustomObject with the following fields (examples provided inside brackets relate to Rename-Many command): - ShortCode ('remy'): a short string denoting the related command - OperantName ('UndoRename'): name of the operant class required - Shell ('PoShShell'): The type of shell that the command should be generated for. So for PowerShell the user would specify 'PoShShell' (which for the time being is the only shell supported). - BaseFilename ('undo-rename'): the core part of the file name which should reflect the nature of the operant (the operation, which ideally should be a verb noun pair but is not enforced) - DisabledEnVar ('LOOPZ_REMY_UNDO_DISABLED'): The environment variable used to disable this operant. .PARAMETER DryRun Similar to WhatIf, but by passing ShouldProcess process for custom handling of dry run scenario. DryRun should be set if WhatIf is enabled. .PARAMETER HomePath User's home directory. (This parameter does not need to be set by client, just used for testing purposes.) .PARAMETER Options (See command description for $Options field descriptions). .EXAMPLE 1 Operant options for Rename-Many(remy) command [PSCustomObject]$operantOptions = [PSCustomObject]@{ ShortCode = 'remy'; OperantName = 'UndoRename'; Shell = 'PoShShell'; BaseFilename = 'undo-rename'; DisabledEnVar = 'LOOPZ_REMY_UNDO_DISABLED'; } #> [OutputType([Operant])] param( [Parameter()] [string]$HomePath = $(Resolve-Path "~"), [Parameter()] [PSCustomObject]$Options, [Parameter()] [switch]$DryRun ) [string]$envUndoRenameDisabled = $(Get-EnvironmentVariable -Variable $Options.DisabledEnVar); try { [boolean]$isDisabled = if (-not([string]::IsNullOrEmpty($envUndoRenameDisabled))) { [System.Convert]::ToBoolean($envUndoRenameDisabled); } else { $false; } } catch { [boolean]$isDisabled = $false; } [Operant]$operant = if (-not($isDisabled)) { [string]$loopzPath = $(Get-EnvironmentVariable -Variable 'LOOPZ_PATH'); [string]$subPath = ".loopz" + [System.IO.Path]::DirectorySeparatorChar + $($Options.ShortCode); if ([string]::IsNullOrEmpty($loopzPath)) { $loopzPath = Join-Path -Path $HomePath -ChildPath $subPath; } else { $loopzPath = [System.IO.Path]::IsPathRooted($loopzPath) ` ? $(Join-Path -Path $loopzPath -ChildPath $subPath) ` : $(Join-Path -Path $HomePath -ChildPath $loopzPath -AdditionalChildPath $subPath); } if (-not(Test-Path -Path $loopzPath -PathType Container)) { if (-not($DryRun)) { $null = New-Item -Type Directory -Path $loopzPath; } } New-ShellOperant -BaseFilename $Options.BaseFilename ` -Directory $loopzPath -Operant $($Options.OperantName) -Shell $Options.Shell; } else { $null; } return $operant; } function Move-Match { <# .NAME Move-Match .SYNOPSIS The core move match action function principally used by Rename-Many. Moves a match according to the specified anchor(s). .DESCRIPTION Returns a new string that reflects moving the specified $Pattern match to either the location designated by $Anchor/$AnchorOccurrence/$Relation or to the Start or End of the value indicated by the presence of the $Start/$End switch parameters. First Move-Match, removes the Pattern match from the source. This makes the With and Anchor match against the remainder ($patternRemoved) of the source. This way, there is no overlap between the Pattern match and With/Anchor and it also makes the functionality more understandable for the user. NB: $Pattern only tells you what to remove, but it's the $With, $Copy and $Paste that defines what to insert, with the $Anchor/$Start/$End defining where the replacement text should go. The user should not be using named capture groups in $Copy, or $Anchor, rather, they should be defined inside $Paste and referenced inside $Paste/$With. .PARAMETER Anchor Anchor is a regular expression string applied to $Value (after the $Pattern match has been removed). The $Pattern match that is removed is inserted at the position indicated by the anchor match in collaboration with the $Relation parameter. .PARAMETER AnchorOccurrence Can be a number or the letters f, l * f: first occurrence * l: last occurrence * <number>: the nth occurrence .PARAMETER Copy Regular expression string applied to $Value (after the $Pattern match has been removed), indicating a portion which should be copied and re-inserted (via the $Paste parameter; see $Paste or $With). Since this is a regular expression to be used in $Paste/$With, there is no value in the user specifying a static pattern, because that static string can just be defined in $Paste/$With. The value in the $Copy parameter comes when a generic pattern is defined eg \d{3} (is non static), specifies any 3 digits as opposed to say '123', which could be used directly in the $Paste/$With parameter without the need for $Copy. The match defined by $Copy is stored in special variable ${_c} and can be referenced as such from $Paste and $With. .PARAMETER CopyOccurrence Can be a number or the letters f, l * f: first occurrence * l: last occurrence * <number>: the nth occurrence .PARAMETER Diagnose switch parameter that indicates the command should be run in WhatIf mode. When enabled it presents additional information that assists the user in correcting the un-expected results caused by an incorrect/un-intended regular expression. The current diagnosis will show the contents of named capture groups that they may have specified. When an item is not renamed (usually because of an incorrect regular expression), the user can use the diagnostics along side the 'Not Renamed' reason to track down errors. When $Diagnose has been specified, $WhatIf does not need to be specified. .PARAMETER Drop A string parameter (only applicable to move operations, ie any of these Anchor/Star/End are present) that defines what text is used to replace the $Pattern match. So in this use-case, the user wants to move a particular token/pattern to another part of the name and at the same time drop a static string in the place where the $Pattern was removed from. .PARAMETER End Is another type of anchor used instead of $Anchor and specifies that the $Pattern match should be moved to the end of the new name. .PARAMETER Marker A character used to mark the place where the $Pattern was removed from. It should be a special character that is not easily typed on the keyboard by the user so as to not interfere wth $Anchor/$Copy matches which occur after $Pattern match is removed. .PARAMETER Paste This is a NON regular expression string. It would be more accurately described as a formatter, similar to the $With parameter. When $Paste is defined, the $Anchor (if specified) is removed from $Value and needs to be be re-inserted using the special variable ${_a}. The other special variables that can be used inside a $Paste string is documented under the $With parameter. The $Paste string can specify a format that defines the replacement and since it removes the $Anchor, the $Relation is not applicable ($Relation and $Paste can't be used together). .PARAMETER Pattern Regular expression string that indicates which part of the $Value that either needs to be moved or replaced as part of overall rename operation. Those characters in $Value which match $Pattern, are removed. .PARAMETER PatternOccurrence Can be a number or the letters f, l * f: first occurrence * l: last occurrence * <number>: the nth occurrence .PARAMETER Relation Used in conjunction with the $Anchor parameter and can be set to either 'before' or 'after' (the default). Defines the relationship of the $Pattern match with the $Anchor match in the new name for $Value. .PARAMETER Start Is another type of anchor used instead of $Anchor and specifies that the $Pattern match should be moved to the start of the new name. .PARAMETER Value The source value against which regular expressions are applied. .PARAMETER With This is a NON regular expression string. It would be more accurately described as a formatter, similar to the $Paste parameter. Defines what text is used as the replacement for the $Pattern match. Works in concert with $Relation (whereas $Paste does not). $With can reference special variables: * $0: the pattern match * ${_a}: the anchor match * ${_c}: the copy match When $Pattern contains named capture groups, these variables can also be referenced. Eg if the $Pattern is defined as '(?<day>\d{1,2})-(?<mon>\d{1,2})-(?<year>\d{4})', then the variables ${day}, ${mon} and ${year} also become available for use in $With or $Paste. Typically, $With is static text which is used to replace the $Pattern match and is inserted according to the Anchor match, (or indeed $Start or $End) and $Relation. When using $With, whatever is defined in the $Anchor match is not removed from $Value (this is different to how $Paste works). #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSPossibleIncorrectUsageOfAssignmentOperator', '')] [Alias('moma')] [OutputType([string])] param ( [Parameter(Mandatory)] [string]$Value, [Parameter()] [System.Text.RegularExpressions.RegEx]$Pattern, [Parameter()] [ValidateScript( { ($_ -ne '*') -and ($_ -ne '0') })] [string]$PatternOccurrence = 'f', [Parameter()] [System.Text.RegularExpressions.RegEx]$Anchor, [Parameter()] [ValidateScript( { ($_ -ne '*') -and ($_ -ne '0') })] [string]$AnchorOccurrence = 'f', [Parameter()] [ValidateSet('before', 'after')] [string]$Relation = 'after', [Parameter()] [System.Text.RegularExpressions.RegEx]$Copy, [Parameter()] [ValidateScript( { ($_ -ne '*') -and ($_ -ne '0') })] [string]$CopyOccurrence = 'f', [Parameter()] [string]$With, [Parameter()] [string]$Paste, [Parameter()] [switch]$Start, [Parameter()] [switch]$End, [Parameter()] [switch]$Diagnose, [Parameter()] [string]$Drop, [Parameter()] [char]$Marker = 0x20DE ) [string]$result = [string]::Empty; [string]$failedReason = [string]::Empty; [PSCustomObject]$groups = [PSCustomObject]@{ Named = @{} } [boolean]$isFormatted = $PSBoundParameters.ContainsKey('Paste') -and -not([string]::IsNullOrEmpty($Paste)); [boolean]$dropped = $PSBoundParameters.ContainsKey('Drop') -and -not([string]::IsNullOrEmpty($Drop)); [hashtable]$parameters = @{ 'Source' = $Value 'PatternRegEx' = $Pattern 'Occurrence' = ($PSBoundParameters.ContainsKey('PatternOccurrence') ? $PatternOccurrence : 'f') } if ($dropped) { $parameters['Marker'] = $Marker; } [string]$capturedPattern, [string]$patternRemoved, ` [System.Text.RegularExpressions.Match]$patternMatch = Split-Match @parameters; if (-not([string]::IsNullOrEmpty($capturedPattern))) { [boolean]$isVanilla = -not($PSBoundParameters.ContainsKey('Copy') -or ` ($PSBoundParameters.ContainsKey('With') -and -not([string]::IsNullOrEmpty($With)))); if ($Diagnose.ToBool()) { $groups.Named['Pattern'] = get-Captures -MatchObject $patternMatch; } # Determine the replacement text # if ($isVanilla) { # Insert the original pattern match, because there is no Copy/With. # [string]$replaceWith = $capturedPattern; } else { [string]$replaceWith = [string]::Empty; if ($PSBoundParameters.ContainsKey('Copy')) { if ($patternRemoved -match $Copy) { [hashtable]$parameters = @{ 'Source' = $patternRemoved 'PatternRegEx' = $Copy 'Occurrence' = ($PSBoundParameters.ContainsKey('CopyOccurrence') ? $CopyOccurrence : 'f') } if ($dropped) { $parameters['Marker'] = $Marker; } # With this implementation, it is up to the user to supply a regex proof # pattern, so if the Copy contains regex chars which must be treated literally, they # must pass in the string pre-escaped: -Copy $(esc('some-pattern') + 'other stuff'). # [string]$replaceWith, $null, ` [System.Text.RegularExpressions.Match]$copyMatch = Split-Match @parameters; if ($Diagnose.ToBool()) { $groups.Named['Copy'] = get-Captures -MatchObject $copyMatch; } } else { # Copy doesn't match so abort and return unmodified source # $failedReason = 'Copy Match'; } } elseif ($PSBoundParameters.ContainsKey('With')) { [string]$replaceWith = $With; } else { [string]$replaceWith = [string]::Empty; } } if (-not($PSBoundParameters.ContainsKey('Anchor')) -and ($isFormatted)) { $replaceWith = $Paste.Replace('${_c}', $replaceWith).Replace('$0', $capturedPattern); # Now apply the user defined Pattern named group references if they exist # to the captured pattern # $replaceWith = $capturedPattern -replace $pattern, $replaceWith; } if ($Start.ToBool()) { $result = $replaceWith + $patternRemoved; } elseif ($End.ToBool()) { $result = $patternRemoved + $replaceWith; } elseif ($PSBoundParameters.ContainsKey('Anchor')) { [hashtable]$parameters = @{ 'Source' = $patternRemoved 'PatternRegEx' = $Anchor 'Occurrence' = ($PSBoundParameters.ContainsKey('AnchorOccurrence') ? $AnchorOccurrence : 'f') } if ($dropped) { $parameters['Marker'] = $Marker; } # As with the Copy parameter, if the user wants to specify an anchor by a pattern # which contains regex chars, then can use -Anchor $(esc('anchor-pattern')). If # there are no regex chars, then they can use -Anchor 'pattern'. However, if the # user needs to do partial escapes, then they will have to do the escaping # themselves: -Anchor $(esc('partial-pattern') + 'remaining-pattern'). # [string]$capturedAnchor, $null, ` [System.Text.RegularExpressions.Match]$anchorMatch = Split-Match @parameters; if (-not([string]::IsNullOrEmpty($capturedAnchor))) { # Relation and Paste are not compatible, because if the user is defining the # replacement format, it is up to them to define the relationship of the anchor # with the replacement text. So exotic/vanilla-formatted can't use Relation. # # How do we handle group references in Pattern? These are done transparently # because any group defined in Pattern can be referenced by Paste as long as # there is a replace operation of the form regEx.Replace($Pattern, Paste). Of course # we can't do the replace in this simplistic way, because that form would replace # all matches, when we only want to replace the specified Pattern occurrence. # if ($isFormatted) { # Paste can be something like '___ ${_a}, (${a}, ${b}, [$0], ${_c} ___', where $0 # represents the pattern capture, the special variable _c represents $Copy, # _a represents the anchor and ${a} and ${b} represents user defined capture groups. # The Paste replaces the anchor, so to re-insert the anchor _a, it must be referenced # in the Paste format. Numeric captures may also be referenced. # [string]$format = $Paste.Replace('${_c}', $replaceWith).Replace( '$0', $capturedPattern).Replace('${_a}', $capturedAnchor); # Now apply the user defined Pattern named group references if they exist # to the captured pattern # $format = $capturedPattern -replace $pattern, $format; } else { # If the user has defined a Copy/With without a format(Paste), we define the format # in terms of the relationship specified. # [string]$format = ($Relation -eq 'before') ` ? $replaceWith + $capturedAnchor : $capturedAnchor + $replaceWith; } if ($Diagnose.ToBool()) { $groups.Named['Anchor'] = get-Captures -MatchObject $anchorMatch; } $result = $Anchor.Replace($patternRemoved, $format, 1, $anchorMatch.Index); } else { # Anchor doesn't match Pattern # $failedReason = 'Anchor Match'; } } else { # This is an error, because there is no place to move the pattern to, as there is no Anchor, # Start or End specified. Actually, we're in the twilight zone here as this scenario can't # happen and has been engineered out of existence! # $failedReason = 'Twilight Zone: Missing Anchor'; } } else { # Source doesn't match Pattern # $failedReason = 'Pattern Match'; } if ([boolean]$success = $([string]::IsNullOrEmpty($failedReason))) { if ($dropped -and $result.Contains([string]$Marker)) { $result = $result.Replace([string]$Marker, $Drop); } } else { $result = $Value; } [PSCustomObject]$moveResult = [PSCustomObject]@{ Payload = $result; Success = $success; CapturedPattern = $capturedPattern; } if (-not([string]::IsNullOrEmpty($failedReason))) { $moveResult | Add-Member -MemberType NoteProperty -Name 'FailedReason' -Value $failedReason; } if ($Diagnose.ToBool() -and ($groups.Named.Count -gt 0)) { $moveResult | Add-Member -MemberType NoteProperty -Name 'Diagnostics' -Value $groups; } return $moveResult; } # Move-Match function New-RegularExpression { <# .NAME New-RegularExpression .SYNOPSIS regex factory function. .DESCRIPTION Creates a regex object from the $Expression specified. Supports inline regex flags ('mixsn') which must be specified at the end of the $Expression after a '/'. .PARAMETER Escape switch parameter to indicate that the expression should be escaped. (This is an alternative to the '~' prefix). .PARAMETER Expression The pattern for the regular expression. If it starts with a tilde ('~'), then the whole expression is escaped so any special regex characters are interpreted literally. .PARAMETER Label string that gives a name to the regular expression being created and is used for logging/error reporting purposes only, so it's not mandatory. .PARAMETER WholeWord switch parameter to indicate the expression should be wrapped with word boundary markers \b, so an $Expression defined as 'foo' would be adjusted to '\bfoo\b'. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Not a state changing function, its a factory')] [OutputType([System.Text.RegularExpressions.RegEx])] param( [Parameter(Position = 0, Mandatory)] [string]$Expression, [Parameter()] [switch]$Escape, [Parameter()] [switch]$WholeWord, [Parameter()] [string]$Label ) [System.Text.RegularExpressions.RegEx]$resultRegEx = $null; [System.Text.RegularExpressions.RegEx]$extractOptionsRegEx = New-Object ` -TypeName System.Text.RegularExpressions.RegEx -ArgumentList ( '[\/\\](?<codes>[mixsn]{1,5})$'); try { [string]$adjustedExpression = $Expression.StartsWith('~') ` ? [regex]::Escape($Expression.Substring(1)) : $Expression; [string[]]$optionsArray = @(); [string]$options = if ($extractOptionsRegEx.IsMatch($adjustedExpression)) { $null, $adjustedExpression, [System.Text.RegularExpressions.Match]$optionsMatch = ` Split-Match -Source $adjustedExpression -PatternRegEx $extractOptionsRegEx; [string]$inlineCodes = $optionsMatch.Groups['codes']; # NOTE, beware of [string]::ToCharArray, the returned result MUST be cast to [string[]] # [string[]]$inlineCodes.ToCharArray() | ForEach-Object { $optionsArray += $Loopz.InlineCodeToOption[$_] } $optionsArray -join ', '; } else { $null; } if (-not([string]::IsNullOrEmpty($options))) { Write-Debug "New-RegularExpression; created RegEx for pattern: '$adjustedExpression', with options: '$options'"; } if ($Escape.ToBool()) { $adjustedExpression = [regex]::Escape($adjustedExpression); } if ($WholeWord.ToBool()) { $adjustedExpression = '\b{0}\b' -f $adjustedExpression; } $arguments = $options ? @($adjustedExpression, $options) : @(, $adjustedExpression); $resultRegEx = New-Object -TypeName System.Text.RegularExpressions.RegEx -ArgumentList ( $arguments); } catch [System.Management.Automation.MethodInvocationException] { [string]$message = ($PSBoundParameters.ContainsKey('Label')) ` ? $('Regular expression ({0}) "{1}" is not valid, ... terminating ({2}).' ` -f $Label, $adjustedExpression, $_.Exception.Message) : $('Regular expression "{0}" is not valid, ... terminating ({1}).' ` -f $adjustedExpression, $_.Exception.Message); Write-Error -Message $message -ErrorAction Stop; } $resultRegEx; } function Resolve-PatternOccurrence { <# .NAME Resolve-PatternOccurrence .SYNOPSIS Helper function to assist in processing regular expression parameters that can be adorned with an occurrence value. .DESCRIPTION Since the occurrence part is optional and defaults to mean first occurrence only, this function will fill in the default 'f' when occurrence is not specified. .PARAMETER Value The value of a regex parameter, which is an array whose first element is the pattern and the second if present is the match occurrence. #> param ( [Parameter(Position = 0)] [array]$Value ) $Value[0], $(($Value.Length -eq 1) ? 'f' : $Value[1]); } # resolve-PatternOccurrence function Select-FsItem { <# .NAME Select-FsItem .SYNOPSIS A predicate function that indicates whether an item identified by the Name matches the include/exclude filters specified. .DESCRIPTION Use this utility function to help specify a Condition for Invoke-TraverseDirectory. This function is partly required because the Include/Exclude parameters on functions such as Get-ChildItems/Copy-Item/Get-Item etc only work on files not directories. .PARAMETER Case Switch parameter which controls case sensitivity of inclusion/exclusion. By default filtering is case insensitive. When The Case switch is specified, filtering is case sensitive. .PARAMETER Excludes An array containing a list of filters, each must contain a wild-card ('*'). If a particular filter does not contain a wild-card, then it will be ignored. If the Name matches any of the filters in the list, will cause the end result to be false. Any match in the Excludes overrides a match in Includes, so an item that is matched in Include, can be excluded by the Exclude. .PARAMETER Includes An array containing a list of filters, each must contain a wild-card ('*'). If a particular filter does not contain a wild-card, then it will be ignored. If Name matches any of the filters in Includes, and are not Excluded, the result will be true. .PARAMETER Name A string to be matched against the filters. .EXAMPLE 1 Define a Condition that allows only directories beginning with A, but also excludes any directory containing '_' or '-'. [scriptblock]$filterDirectories = { [OutputType([boolean])] param( [System.IO.DirectoryInfo]$directoryInfo ) [string[]]$directoryIncludes = @('A*'); [string[]]$directoryExcludes = @('*_*', '*-*'); $filterDirectories = Select-FsItem -Name $directoryInfo.Name ` -Includes $directoryIncludes -Excludes $directoryExcludes; Invoke-TraverseDirectory -Path <path> -Block <block> -Condition $filterDirectories; } #> [OutputType([boolean])] param( [Parameter(Mandatory)] [string]$Name, [Parameter()] [string[]]$Includes = @(), [Parameter()] [string[]]$Excludes = @(), [Parameter()] [switch]$Case ) # Note we wrap the result inside @() array designator just in-case the where-object # returns just a single item in which case the array would be flattened out into # an individual scalar value which is what we don't want, damn you powershell for # doing this and making life just so much more difficult. Actually, on further # investigation, we don't need to wrap inside @(), because we've explicitly defined # the type of the includes variables to be arrays, which would preserve the type # even in the face of powershell annoyingly flattening the single item array. @() # being left in for clarity and show of intent. # [string[]]$validIncludes = @($Includes | Where-Object { $_.Contains('*') }) [string[]]$validExcludes = @($Excludes | Where-Object { $_.Contains('*') }) [boolean]$resolvedInclude = $validIncludes ` ? (select-ResolvedFsItem -FsItem $Name -Filter $Includes -Case:$Case) ` : $false; [boolean]$resolvedExclude = $validExcludes ` ? (select-ResolvedFsItem -FsItem $Name -Filter $Excludes -Case:$Case) ` : $false; ($resolvedInclude) -and -not($resolvedExclude) } # Select-FsItem function Select-SignalContainer { <# .NAME Select-SignalContainer .SYNOPSIS Selects a signal into the container specified (either 'Wide' or 'Props'). Wide items will appear on their own line, Props are for items which are short in length and can be combined into the same line. .DESCRIPTION This is a wrapper around Get-FormattedSignal in addition to selecting the signal into a container. .PARAMETER Containers PSCustomObject that contains Wide and Props properties which must be of Krayola's type [line]. .PARAMETER CustomLabel A custom label applied to the formatted signal. .PARAMETER Force An override (bypassing $Threshold) to push a signal into a specific collection. .PARAMETER Format The format applied to the formatted signal. .PARAMETER Name The signal name. .PARAMETER Signals The signal hashtable collection from which to select the required signal denoted by $Name. .PARAMETER Threshold A threshold that defines whether the signal is added to Wide or Props. .PARAMETER Value The value associated wih the signal. #> param( [Parameter(Mandatory)] [PSCustomObject]$Containers, [Parameter(Mandatory)] [string]$Name, [Parameter(Mandatory)] [string]$Value, [Parameter()] [hashtable]$Signals = $(Get-Signals), [Parameter()] [string]$Format = '[{1}] {0}', # 0=Label, 1=Emoji, [Parameter()] [int]$Threshold = 6, [Parameter()] [string]$CustomLabel, [Parameter()] [ValidateSet('Wide', 'Props')] [string]$Force ) [couplet]$formattedSignal = Get-FormattedSignal -Name $Name -Format $Format -Value $Value ` -Signals $Signals -CustomLabel $CustomLabel; if ($PSBoundParameters.ContainsKey('Force')) { if ($Force -eq 'Wide') { $null = $Containers.Wide.append($formattedSignal); } else { $null = $Containers.Props.append($formattedSignal); } } else { if ($Value.Length -gt $Threshold) { $null = $Containers.Wide.append($formattedSignal); } else { $null = $Containers.Props.append($formattedSignal); } } } function Split-Match { <# .NAME Split-Match .SYNOPSIS Splits out a match from the remainder of the $Source text returning the matched test, the remainder and the corresponding match object. .DESCRIPTION Helper function to get the pattern match and the remaining text. This helper helps us to avoid unnecessary duplicated reg ex matches. It returns up to 3 items inside an array, the first is the matched text, the second is the source with the matched text removed and the third is the match object that represents the matched text. .PARAMETER CapturedOnly switch parameter to indicate what should be returned. When the client does not need the match object or the remainder, they can use this switch to ensure only the matched text is returned. .PARAMETER Marker A character used to mark the place where the $PatternRegEx's match was removed from. It should be a special character that is not easily typed on the keyboard by the user so as to not interfere wth $Anchor/$Copy matches which occur after $Pattern match is removed. .PARAMETER Occurrence Denotes which match should be used. .PARAMETER PatternRegEx The regex object to apply to the $Source. .PARAMETER Source The source value against which regular expression is applied. #> param( [Parameter(Mandatory)] [string]$Source, [Parameter()] [System.Text.RegularExpressions.RegEx]$PatternRegEx, [Parameter()] [ValidateScript( { $_ -ne '0' })] [string]$Occurrence = 'f', [Parameter()] [switch]$CapturedOnly, [Parameter()] [char]$Marker = 0x20DE ) [System.Text.RegularExpressions.MatchCollection]$mc = $PatternRegEx.Matches($Source); if ($mc.Count -gt 0) { # Get the match instance # [System.Text.RegularExpressions.Match]$m = if ($Occurrence -eq 'f') { $mc[0]; } elseif ($Occurrence -eq 'l') { $mc[$mc.Count - 1]; } else { try { [int]$nth = [int]::Parse($Occurrence); } catch { [int]$nth = 1; } ($nth -le $mc.Count) ? $mc[$nth - 1] : $null; } } else { [System.Text.RegularExpressions.Match]$m = $null; } $result = $null; if ($m) { [string]$capturedText = $m.Value; $result = if ($CapturedOnly.ToBool()) { $capturedText; } else { # Splatting the arguments fails because the parameter validation in Get-InverseSubString # fails, due to parameters not having been bound yet. # https://github.com/PowerShell/PowerShell/issues/14457 # [string]$remainder = $PSBoundParameters.ContainsKey('Marker') ` ? $(Get-InverseSubString -Source $Source -StartIndex $m.Index -Length $m.Length -Marker $Marker) ` : $(Get-InverseSubString -Source $Source -StartIndex $m.Index -Length $m.Length); @($capturedText, $remainder, $m); } } return $result; } # Split-Match function Update-Match { <# .NAME Update-Match .SYNOPSIS The core update match action function principally used by Rename-Many. Updates $Pattern match in it's current location and can update all $Pattern matches if '*' is specified as the $PatternOccurrence. .DESCRIPTION Returns a new string that reflects updating the specified $Pattern match. First Update-Match, removes the Pattern match from $Value. This makes the With and Copy match against the remainder ($patternRemoved) of $Value. This way, there is no overlap between the Pattern match and $With and it also makes the functionality more understandable for the user. NB: Pattern only tells you what to remove, but it's the With, Copy and Paste that defines what to insert. The user should not be using named capture groups in Copy rather, they should be defined inside $Paste and referenced inside Paste. .PARAMETER Copy Regular expression string applied to $Value (after the $Pattern match has been removed), indicating a portion which should be copied and re-inserted (via the $Paste parameter; see $Paste or $With). Since this is a regular expression to be used in $Paste/$With, there is no value in the user specifying a static pattern, because that static string can just be defined in $Paste/$With. The value in the $Copy parameter comes when a generic pattern is defined eg \d{3} (is non static), specifies any 3 digits as opposed to say '123', which could be used directly in the $Paste/$With parameter without the need for $Copy. The match defined by $Copy is stored in special variable ${_p} and can be referenced as such from $Paste and $With. .PARAMETER CopyOccurrence Can be a number or the letters f, l * f: first occurrence * l: last occurrence * <number>: the nth occurrence .PARAMETER Diagnose switch parameter that indicates the command should be run in WhatIf mode. When enabled it presents additional information that assists the user in correcting the un-expected results caused by an incorrect/un-intended regular expression. The current diagnosis will show the contents of named capture groups that they may have specified. When an item is not renamed (usually because of an incorrect regular expression), the user can use the diagnostics along side the 'Not Renamed' reason to track down errors. When $Diagnose has been specified, $WhatIf does not need to be specified. .PARAMETER Paste This is a NON regular expression string. It would be more accurately described as a formatter, similar to the $With parameter. The other special variables that can be used inside a $Paste string is documented under the $With parameter. .PARAMETER Pattern Regular expression string that indicates which part of the $Value that either needs to be moved or replaced as part of overall rename operation. Those characters in $Value which match $Pattern, are removed. .PARAMETER PatternOccurrence Can be a number or the letters f, l * f: first occurrence * l: last occurrence * <number>: the nth occurrence .PARAMETER Value The source value against which regular expressions are applied. .PARAMETER With This is a NON regular expression string. It would be more accurately described as a formatter, similar to the $Paste parameter. Defines what text is used as the replacement for the $Pattern match. Works in concert with $Relation (whereas $Paste does not). $With can reference special variables: * $0: the pattern match * ${_c}: the copy match When $Pattern contains named capture groups, these variables can also be referenced. Eg if the $Pattern is defined as '(?<day>\d{1,2})-(?<mon>\d{1,2})-(?<year>\d{4})', then the variables ${day}, ${mon} and ${year} also become available for use in $With or $Paste. Typically, $With is static text which is used to replace the $Pattern match. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [OutputType([string])] param( [Parameter()] [string]$Value, [Parameter()] [System.Text.RegularExpressions.RegEx]$Pattern, [Parameter()] [ValidateScript( { $_ -ne '0' })] [string]$PatternOccurrence = 'f', [Parameter()] [System.Text.RegularExpressions.RegEx]$Copy, [Parameter()] [ValidateScript( { $_ -ne '0' })] [string]$CopyOccurrence = 'f', [Parameter()] [string]$With, [Parameter()] [string]$Paste, [Parameter()] [switch]$Diagnose ) [string]$failedReason = [string]::Empty; [PSCustomObject]$groups = [PSCustomObject]@{ Named = @{} } [string]$capturedPattern, $patternRemoved, [System.Text.RegularExpressions.Match]$patternMatch = ` Split-Match -Source $Value -PatternRegEx $Pattern ` -Occurrence ($PSBoundParameters.ContainsKey('PatternOccurrence') ? $PatternOccurrence : 'f'); if (-not([string]::IsNullOrEmpty($capturedPattern))) { if ($PSBoundParameters.ContainsKey('Copy')) { [string]$replaceWith, $null, [System.Text.RegularExpressions.Match]$copyMatch = ` Split-Match -Source $patternRemoved -PatternRegEx $Copy ` -Occurrence ($PSBoundParameters.ContainsKey('CopyOccurrence') ? $CopyOccurrence : 'f'); if ([string]::IsNullOrEmpty($replaceWith)) { $failedReason = 'Copy Match'; } elseif ($Diagnose.ToBool()) { $groups.Named['Copy'] = get-Captures -MatchObject $copyMatch; } } elseif ($PSBoundParameters.ContainsKey('With')) { [string]$replaceWith = $With; } else { [string]$replaceWith = [string]::Empty; } if ([string]::IsNullOrEmpty($failedReason)) { if ($PSBoundParameters.ContainsKey('Paste')) { [string]$format = $Paste.Replace('${_c}', $replaceWith).Replace( '$0', $capturedPattern); } else { # Just do a straight swap of the pattern match for the replaceWith # [string]$format = $replaceWith; } [string]$result = ($PatternOccurrence -eq '*') ` ? $Pattern.Replace($Value, $format) ` : $Pattern.Replace($Value, $format, 1, $patternMatch.Index); if ($Diagnose.ToBool()) { $groups.Named['Pattern'] = get-Captures -MatchObject $patternMatch; } } } else { $failedReason = 'Pattern Match'; } [boolean]$success = $([string]::IsNullOrEmpty($failedReason)); if (-not($success)) { $result = $Value; } [PSCustomObject]$updateResult = [PSCustomObject]@{ Payload = $result; Success = $success; CapturedPattern = $capturedPattern; } if (-not([string]::IsNullOrEmpty($failedReason))) { $updateResult | Add-Member -MemberType NoteProperty -Name 'FailedReason' -Value $failedReason; } if ($Diagnose.ToBool() -and ($groups.Named.Count -gt 0)) { $updateResult | Add-Member -MemberType NoteProperty -Name 'Diagnostics' -Value $groups; } return $updateResult; } # Update-Match function Invoke-ForeachFsItem { <# .NAME Invoke-ForeachFsItem .SYNOPSIS Allows a custom defined script-block or function to be invoked for all file system objects delivered through the pipeline. .DESCRIPTION 2 parameters sets are defined, one for invoking a named function (InvokeFunction) and the other (InvokeScriptBlock, the default) for invoking a script-block. An optional Summary script block can be specified which will be invoked at the end of the pipeline batch. The user should assemble the candidate items from the file system, be they files or directories typically using Get-ChildItem, or can be any other function that delivers file systems items via the PowerShell pipeline. For each item in the pipeline, Invoke-ForeachFsItem will invoke the script-block/function specified. Invoke-ForeachFsItem will deliver what ever is returned from the script-block/function, so the result of Invoke-ForeachFsItem can be piped to another command. .PARAMETER Block The script block to be invoked. The script block is invoked for each item in the pipeline that satisfy the Condition with the following positional parameters: * pipelineItem: the item from the pipeline * index: the 0 based index representing current pipeline item * Exchange: a hash table containing miscellaneous information gathered internally throughout the pipeline batch. This can be of use to the user, because it is the way the user can perform bi-directional communication between the invoked custom script block and client side logic. * trigger: a boolean value, useful for state changing idempotent operations. At the end of the batch, the state of the trigger indicates whether any of the items were actioned. When the script block is invoked, the trigger should indicate if the trigger was pulled for any of the items so far processed in the pipeline. This is the responsibility of the client's block implementation. The trigger is only of use for state changing operations and can be ignored otherwise. In addition to these fixed positional parameters, if the invoked script-block is defined with additional parameters, then these will also be passed in. In order to achieve this, the client has to provide excess parameters in BlockParam and these parameters must be defined as the same type and in the same order as the additional parameters in the script-block. .PARAMETER BlockParams Optional array containing the excess parameters to pass into the script block. .PARAMETER Condition This is a predicate script-block, which is invoked with either a DirectoryInfo or FileInfo object presented as a result of invoking Get-ChildItem. It provides a filtering mechanism that is defined by the user to define which file system objects are selected for function/script-block invocation. .PARAMETER Directory Switch to indicate that the invoked function/script-block (invokee) is to handle Directory objects. .PARAMETER File Switch to indicate that the invoked function/script-block (invokee) is to handle FileInfo objects. Is mutually exclusive with the Directory switch. If neither switch is specified, then the invokee must be able to handle both therefore the Underscore parameter it defines must be declared as FileSystemInfo. .PARAMETER Functee String defining the function to be invoked. Works in a similar way to the Block parameter for script-blocks. The Function's base signature is as follows: * Underscore: (See pipelineItem described above) * Index: (See index described above) * Exchange: (See PathThru described above) * Trigger: (See trigger described above) .PARAMETER FuncteeParams Optional hash-table containing the named parameters which are splatted into the Functee function invoke. As it's a hash table, order is not significant. .PARAMETER Exchange A hash table containing miscellaneous information gathered internally throughout the pipeline batch. This can be of use to the user, because it is the way the user can perform bi-directional communication between the invoked custom script block and client side logic. .PARAMETER Header A script-block that is invoked at the start of the pipeline batch. The script-block is invoked with the following positional parameters: * Exchange: (see Exchange previously described) The Header can be customised with the following Exchange entries: * 'LOOPZ.KRAYOLA-THEME': Krayola Theme generally in use * 'LOOPZ.HEADER-BLOCK.MESSAGE': message displayed as part of the header * 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL': Lead text displayed in header, default: '[+] ' * 'LOOPZ.HEADER.PROPERTIES': An array of Key/Value pairs of items to be displayed * 'LOOPZ.HEADER-BLOCK.LINE': A string denoting the line to be displayed. (There are predefined lines available to use in $LoopzUI, or a custom one can be used instead) .PARAMETER Summary A script-block that is invoked at the end of the pipeline batch. The script-block is invoked with the following positional parameters: * count: the number of items processed in the pipeline batch. * skipped: the number of items skipped in the pipeline batch. An item is skipped if it fails the defined condition or is not of the correct type (eg if its a directory but we have specified the -File flag). Also note that, if the script-block/function sets the Break flag causing further iteration to stop, then those subsequent items in the pipeline which have not been processed are not reflected in the skip count. * trigger: Flag set by the script-block/function, but should typically be used to indicate whether any of the items processed were actively updated/written in this batch. This helps in written idempotent operations that can be re-run without adverse consequences. * Exchange: (see Exchange previously described) .PARAMETER Top Restricts the number of items processed in the rename batch, the remaining items are skipped. User can set this for experimental purposes. .PARAMETER pipelineItem This is the pipeline object, so should not be specified explicitly and can represent a file object (System.IO.FileInfo) or a directory object (System.IO.DirectoryInfo). .EXAMPLE 1 Invoke a script-block to handle .txt file objects from the same directory (without -Recurse): (NB: first parameter is of type FileInfo, -File specified on Get-ChildItem and Invoke-ForeachFsItem. If Get-ChildItem is missing -File, then any Directory objects passed in are filtered out by Invoke-ForeachFsItem. If -File is missing from Invoke-ForeachFsItem, then the script-block's first parameter, must be a FileSystemInfo to handle both types) [scriptblock]$block = { param( [System.IO.FileInfo]$FileInfo, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger ) ... } Get-ChildItem './Tests/Data/fefsi' -Recurse -Filter '*.txt' -File | ` Invoke-ForeachFsItem -File -Block $block; .EXAMPLE 2 Invoke a function with additional parameters to handle directory objects from multiple directories (with -Recurse): function invoke-Target { param( [System.IO.DirectoryInfo]$Underscore, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger, [string]$Format ) ... } [hashtable]$parameters = @{ 'Format' } Get-ChildItem './Tests/Data/fefsi' -Recurse -Directory | ` Invoke-ForeachFsItem -Directory -Functee 'invoke-Target' -FuncteeParams $parameters .EXAMPLE 3 Invoke a script-block to handle empty .txt file objects from the same directory (without -Recurse): [scriptblock]$block = { param( [System.IO.FileInfo]$FileInfo, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger ) ... } [scriptblock]$fileIsEmpty = { param( [System.IO.FileInfo]$FileInfo ) return (0 -eq $FileInfo.Length) } Get-ChildItem './Tests/Data/fefsi' -Recurse -Filter '*.txt' -File | Invoke-ForeachFsItem ` -Block $block -File -condition $fileIsEmpty; .EXAMPLE 4 Invoke a script-block only for directories whose name starts with "A" from the same directory (without -Recurse); Note the use of the LOOPZ function "Select-FsItem" in the directory include filter: [scriptblock]$block = { param( [System.IO.FileInfo]$FileInfo, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger ) ... } [scriptblock]$filterDirectories = { [OutputType([boolean])] param( [System.IO.DirectoryInfo]$directoryInfo ) Select-FsItem -Name $directoryInfo.Name -Includes 'A*'; } Get-ChildItem './Tests/Data/fefsi' -Directory | Invoke-ForeachFsItem ` -Block $block -Directory -DirectoryIncludes $filterDirectories; .EXAMPLE 5 Invoke a script-block to handle .txt file objects from the same directory. This example illustrates the use of the Header and Summary blocks. Blocks predefined in LoopzHelpers are illustrated but the user can defined their own. [scriptblock]$block = { param( [System.IO.FileInfo]$FileInfo, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger ) ... } $exchange = @{ 'LOOPZ.KRAYOLA-THEME' = $(Get-KrayolaTheme); 'LOOPZ.HEADER-BLOCK.MESSAGE' = 'The owls are not what they seem'; 'LOOPZ.HEADER-BLOCK.PROPERTIES' = @(@('A', 'One'), @('B', 'Two'), @('C', 'Three')); 'LOOPZ.HEADER-BLOCK.LINE' = $LoopzUI.TildeLine; 'LOOPZ.SUMMARY-BLOCK.LINE' = $LoopzUI.DashLine; } Get-ChildItem './Tests/Data/fefsi' -Recurse -Filter '*.txt' -File | ` Invoke-ForeachFsItem -File -Block $block -Exchange $exchange ` -Header $LoopzHelpers.DefaultHeaderBlock -Summary $LoopzHelpers.SimpleSummaryBlock; #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] [CmdletBinding(DefaultParameterSetName = 'InvokeScriptBlock')] [Alias('ife', 'Foreach-FsItem')] param( [Parameter(ParameterSetName = 'InvokeScriptBlock', Mandatory, ValueFromPipeline = $true)] [Parameter(ParameterSetName = 'InvokeFunction', Mandatory, ValueFromPipeline = $true)] [System.IO.FileSystemInfo]$pipelineItem, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$Condition = ( { return $true; }), [Parameter(ParameterSetName = 'InvokeScriptBlock', Mandatory)] [scriptblock]$Block, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [ValidateScript( { $_ -is [Array] })] $BlockParams = @(), [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)] [ValidateScript( { -not([string]::IsNullOrEmpty($_)); })] [string]$Functee, [Parameter(ParameterSetName = 'InvokeFunction')] [hashtable]$FuncteeParams = @{}, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [hashtable]$Exchange = @{}, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$Header = ( { param( [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$Summary = ( { param( [int]$_count, [int]$_skipped, [int]$_errors, [boolean]$_trigger, [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [ValidateScript( { -not($PSBoundParameters.ContainsKey('Directory')) })] [switch]$File, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [ValidateScript( { -not($PSBoundParameters.ContainsKey('File')) })] [switch]$Directory, [Parameter()] [ValidateScript( { $_ -gt 0 } )] [int]$Top ) # param begin { if (-not($Exchange.ContainsKey('LOOPZ.CONTROLLER'))) { $Exchange['LOOPZ.CONTROLLER'] = New-Controller -Type ForeachCtrl -Exchange $Exchange ` -Header $Header -Summary $Summary; } $controller = $Exchange['LOOPZ.CONTROLLER']; $controller.ForeachBegin(); [boolean]$topBreached = $false; } process { [boolean]$itemIsDirectory = ($pipelineItem.Attributes -band [System.IO.FileAttributes]::Directory) -eq [System.IO.FileAttributes]::Directory; [boolean]$acceptAll = -not($File.ToBool()) -and -not($Directory.ToBool()); if (-not($controller.IsBroken())) { if ( $acceptAll -or ($Directory.ToBool() -and $itemIsDirectory) -or ($File.ToBool() -and -not($itemIsDirectory)) ) { if ($Condition.InvokeReturnAsIs($pipelineItem) -and -not($topBreached)) { [PSCustomObject]$result = $null; [int]$index = $controller.RequestIndex(); [boolean]$trigger = $controller.GetTrigger(); if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) { $positional = @($pipelineItem, $index, $Exchange, $trigger); if ($BlockParams.Length -gt 0) { $BlockParams | ForEach-Object { $positional += $_; } } $result = Invoke-Command -ScriptBlock $Block -ArgumentList $positional; } elseif ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) { [hashtable]$parameters = $FuncteeParams.Clone(); $parameters['Underscore'] = $pipelineItem; $parameters['Index'] = $index; $parameters['Exchange'] = $Exchange; $parameters['Trigger'] = $trigger; $result = & $Functee @parameters; } $controller.HandleResult($result); if ($result -and $result.psobject.properties.match('Product') -and $result.Product) { $result.Product; } if ($PSBoundParameters.ContainsKey('Top') -and ($index -eq ($Top - 1))) { $topBreached = $true; } } else { # IDEA! We could allow the user to provide an extra script block which we # invoke for skipped items and set a string containing the reason why it was # skipped. $controller.SkipItem(); } } else { $controller.SkipItem(); } } else { $controller.SkipItem(); } } end { $controller.ForeachEnd(); } } # Invoke-ForeachFsItem function Invoke-MirrorDirectoryTree { <# .NAME Invoke-MirrorDirectoryTree .SYNOPSIS Mirrors a directory tree to a new location, invoking a custom defined scriptblock or function as it goes. .DESCRIPTION Copies a source directory tree to a new location applying custom functionality for each directory. 2 parameters set are defined, one for invoking a named function (InvokeFunction) and the other (InvokeScriptBlock, the default) for invoking a scriptblock. An optional Summary script block can be specified which will be invoked at the end of the mirroring batch. .PARAMETER Block The script block to be invoked. The script block is invoked for each directory in the source directory tree that satisfy the specified Directory Include/Exclude filters with the following positional parameters: * underscore: the DirectoryInfo object representing the directory in the source tree * index: the 0 based index representing current directory in the source tree * Exchange object: a hash table containing miscellaneous information gathered internally throughout the mirroring batch. This can be of use to the user, because it is the way the user can perform bi-directional communication between the invoked custom script block and client side logic. * trigger: a boolean value, useful for state changing idempotent operations. At the end of the batch, the state of the trigger indicates whether any of the items were actioned. When the script block is invoked, the trigger should indicate if the trigger was pulled for any of the items so far processed in the batch. This is the responsibility of the client's script-block/function implementation. In addition to these fixed positional parameters, if the invoked scriptblock is defined with additional parameters, then these will also be passed in. In order to achieve this, the client has to provide excess parameters in BlockParams and these parameters must be defined as the same type and in the same order as the additional parameters in the script-block. The destination DirectoryInfo object can be accessed via the Exchange denoted by the 'LOOPZ.MIRROR.DESTINATION' entry. .PARAMETER BlockParams Optional array containing the excess parameters to pass into the script-block/function. .PARAMETER CopyFiles Switch parameter that indicates that files matching the specified filters should be copied .PARAMETER CreateDirs switch parameter indicates that directories should be created in the destination tree. If not set, then Invoke-MirrorDirectoryTree turns into a function that traverses the source directory invoking the function/script-block for matching directories. .PARAMETER DestinationPath The destination Path denoting the root of the directory tree where the source tree will be mirrored to. .PARAMETER DirectoryIncludes An array containing a list of filters, each must contain a wild-card ('*'). If a particular filter does not contain a wild-card, then it will be ignored. If the directory matches any of the filters in the list, it will be mirrored in the destination tree. If DirectoryIncludes contains just a single element which is the empty string, this means that nothing is included (rather than everything being included). .PARAMETER DirectoryExcludes An array containing a list of filters, each must contain a wild-card ('*'). If a particular filter does not contain a wild-card, then it will be ignored. If the directory matches any of the filters in the list, it will NOT be mirrored in the destination tree. Any match in the DirectoryExcludes overrides a match in DirectoryIncludes, so a directory that is matched in Include, can be excluded by the Exclude. .PARAMETER Exchange A hash table containing miscellaneous information gathered internally throughout the pipeline batch. This can be of use to the user, because it is the way the user can perform bi-directional communication between the invoked custom script block and client side logic. .PARAMETER FileExcludes An array containing a list of filters, each may contain a wild-card ('*'). If a particular filter does not contain a wild-card, then it will be treated as a file suffix. If the file in the source tree matches any of the filters in the list, it will NOT be mirrored in the destination tree. Any match in the FileExcludes overrides a match in FileIncludes, so a file that is matched in Include, can be excluded by the Exclude. .PARAMETER FileIncludes An array containing a list of filters, each may contain a wild-card ('*'). If a particular filter does not contain a wild-card, then it will be treated as a file suffix. If the file in the source tree matches any of the filters in the list, it will be mirrored in the destination tree. If FileIncludes contains just a single element which is the empty string, this means that nothing is included (rather than everything being included). .PARAMETER Functee String defining the function to be invoked. Works in a similar way to the Block parameter for script-blocks. The Function's base signature is as follows: * "Underscore": (See underscore described above) * "Index": (See index described above) * "Exchange": (See PathThru described above) * "Trigger": (See trigger described above) The destination DirectoryInfo object can be accessed via the Exchange denoted by the 'LOOPZ.MIRROR.DESTINATION' entry. .PARAMETER FuncteeParams Optional hash-table containing the named parameters which are splatted into the Functee function invoke. As it's a hash table, order is not significant. .PARAMETER Header A script-block that is invoked for each directory that also contains child directories. The script-block is invoked with the following positional parameters: * Exchange: (see Exchange previously described) The Header can be customised with the following Exchange entries: * 'LOOPZ.KRAYOLA-THEME': Krayola Theme generally in use * 'LOOPZ.HEADER-BLOCK.MESSAGE': message displayed as part of the header * 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL': Lead text displayed in header, default: '[+] ' * 'LOOPZ.HEADER.PROPERTIES': An array of Key/Value pairs of items to be displayed * 'LOOPZ.HEADER-BLOCK.LINE': A string denoting the line to be displayed. (There are predefined lines available to use in $LoopzUI, or a custom one can be used instead) .PARAMETER Hoist switch parameter. Without Hoist being specified, the filters can prove to be too restrictive on matching against directories. If a directory does not match the filters then none of its descendants will be considered to be mirrored in the destination tree. When Hoist is specified then a descendant directory that does match the filters will be mirrored even though any of its ancestors may not match the filters. .PARAMETER Path The source Path denoting the root of the directory tree to be mirrored. .PARAMETER SessionHeader A script-block that is invoked at the start of the mirroring batch. The script-block has the same signature as the Header script block. .PARAMETER SessionSummary A script-block that is invoked at the end of the mirroring batch. The script-block has the same signature as the Summary script block. .PARAMETER Summary A script-block that is invoked foreach directory that also contains child directories, after all its descendants have been processed and serves as a sub-total for the current directory. The script-block is invoked with the following positional parameters: * count: the number of items processed in the mirroring batch. * skipped: the number of items skipped in the mirroring batch. An item is skipped if it fails the defined condition or is not of the correct type (eg if its a directory but we have specified the -File flag). * errors: the number of items which resulted in error. An error occurs when the function or the script-block has set the Error property on the invoke result. * trigger: Flag set by the script-block/function, but should typically be used to indicate whether any of the items processed were actively updated/written in this batch. This helps in written idempotent operations that can be re-run without adverse consequences. * Exchange: (see Exchange previously described) .EXAMPLE 1 Invoke a named function for every directory in the source tree and mirror every directory in the destination tree. The invoked function has an extra parameter in it's signature, so the extra parameters must be passed in via FuncteeParams (the standard signature being the first 4 parameters shown.) function Test-Mirror { param( [System.IO.DirectoryInfo]$Underscore, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger, [string]$Format ) ... } [hashtable]$parameters = @{ 'Format' = '---- {0} ----'; } Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' ` -DestinationPath './Tests/Data/mirror' -CreateDirs ` -Functee 'Test-Mirror' -FuncteeParams $parameters; .EXAMPLE 2 Invoke a script-block for every directory in the source tree and copy all files Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' ` -DestinationPath './Tests/Data/mirror' -CreateDirs -CopyFiles -block { param( [System.IO.DirectoryInfo]$Underscore, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger ) ... }; .EXAMPLE 3 Mirror a directory tree, including only directories beginning with A (filter A*) Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' ` -DirectoryIncludes @('A*') Note the possible issue with this example is that any descendants named A... which are located under an ancestor which is not named A..., will not be mirrored; eg './Tests/Data/fefsi/Audio/mp3/A/Amorphous Androgynous', even though "Audio", "A" and "Amorphous Androgynous" clearly match the A* filter, they will not be mirrored because the "mp3" directory, would be filtered out. See the following example for a resolution. .EXAMPLE 4 Mirror a directory tree, including only directories beginning with A (filter A*) regardless of the matching of intermediate ancestors (specifying -Hoist flag resolves the possible issue in the previous example) Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' ` -DirectoryIncludes @('A*') -CreateDirs -CopyFiles -Hoist Note that the directory filter must include a wild-card, otherwise it will be ignored. So a directory include of @('A'), is problematic, because A is not a valid directory filter so its ignored and there are no remaining filters that are able to include any directory, so no directory passes the filter. .EXAMPLE 5 Mirror a directory tree, including files with either .flac or .wav suffix Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' ` -FileIncludes @('flac', '*.wav') -CreateDirs -CopyFiles -Hoist Note that for files, a filter may or may not contain a wild-card. If the wild-card is missing then it is automatically treated as a file suffix; so 'flac' means '*.flac'. .EXAMPLE 6 Mirror a directory tree copying over just flac files [scriptblock]$summary = { param( [int]$_count, [int]$_skipped, [boolean]$_triggered, [hashtable]$_exchange ) ... } Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' ` -FileIncludes @('flac') -CopyFiles -Hoist -Summary $summary Note that -CreateDirs is missing which means directories will not be mirrored by default. They are only mirrored as part of the process of copying over flac files, so in the end the resultant mirror directory tree will contain directories that include flac files. .EXAMPLE 7 Same as EXAMPLE 6, but using predefined Header and Summary script-blocks for Session header/summary and per directory header/summary. Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' ` -FileIncludes @('flac') -CopyFiles -Hoist ` -Header $LoopzHelpers.DefaultHeaderBlock -Summary $DefaultHeaderBlock.SimpleSummaryBlock ` -SessionHeader $LoopzHelpers.DefaultHeaderBlock -SessionSummary $DefaultHeaderBlock.SimpleSummaryBlock; #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'InvokeScriptBlock')] [Alias('imdt', 'Mirror-Directory')] param ( [Parameter(Mandatory, ParameterSetName = 'InvokeScriptBlock')] [Parameter(Mandatory, ParameterSetName = 'InvokeFunction')] [ValidateScript( { Test-path -Path $_; })] [String]$Path, [Parameter(Mandatory, ParameterSetName = 'InvokeScriptBlock')] [Parameter(Mandatory, ParameterSetName = 'InvokeFunction')] [String]$DestinationPath, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [String[]]$DirectoryIncludes = @('*'), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [String[]]$DirectoryExcludes = @(), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [String[]]$FileIncludes = @('*'), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [String[]]$FileExcludes = @(), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [hashtable]$Exchange = @{}, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [scriptblock]$Block = ( { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] param( [System.IO.DirectoryInfo]$underscore, [int]$index, [hashtable]$exchange, [boolean]$trigger ) } ), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [ValidateScript( { $_ -is [Array] })] $BlockParams = @(), [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)] [ValidateScript( { -not([string]::IsNullOrEmpty($_)); })] [string]$Functee, [Parameter(ParameterSetName = 'InvokeFunction')] [hashtable]$FuncteeParams = @{}, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [switch]$CreateDirs, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [switch]$CopyFiles, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [switch]$Hoist, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$Header = ( { param( [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$Summary = ( { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] param( [int]$_index, [int]$_skipped, [int]$_errors, [boolean]$_trigger, [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$SessionHeader = ( { param( [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$SessionSummary = ( { param( [int]$_count, [int]$_skipped, [int]$_errors, [boolean]$_trigger, [hashtable]$_exchange ) }) ) # param # ================================================================== [doMirrorBlock] === # [scriptblock]$doMirrorBlock = { param( [Parameter(Mandatory)] [System.IO.DirectoryInfo]$_underscore, [Parameter(Mandatory)] [int]$_index, [Parameter(Mandatory)] [hashtable]$_exchange, [Parameter(Mandatory)] [boolean]$_trigger ) # Write-Host "[+] >>> doMirrorBlock: $($_underscore.Name)"; [string]$rootSource = $_exchange['LOOPZ.MIRROR.ROOT-SOURCE']; [string]$rootDestination = $_exchange['LOOPZ.MIRROR.ROOT-DESTINATION']; $sourceDirectoryFullName = $_underscore.FullName; # sourceDirectoryFullName must end with directory separator # if (-not($sourceDirectoryFullName.EndsWith([System.IO.Path]::DirectorySeparatorChar))) { $sourceDirectoryFullName += [System.IO.Path]::DirectorySeparatorChar; } $destinationBranch = edit-RemoveSingleSubString -Target $sourceDirectoryFullName -Subtract $rootSource; $destinationDirectory = Join-Path -Path $rootDestination -ChildPath $destinationBranch; $_exchange['LOOPZ.MIRROR.BRANCH-DESTINATION'] = $destinationBranch; [boolean]$whatIf = $_exchange.ContainsKey('WHAT-IF') -and ($_exchange['WHAT-IF']); Write-Debug "[+] >>> doMirrorBlock: destinationDirectory: '$destinationDirectory'"; if ($whatIf) { if (Test-Path -Path $destinationDirectory) { Write-Debug " [-] (WhatIf) Get existing destination branch directory: '$destinationBranch'"; $destinationInfo = (Get-Item -Path $destinationDirectory); } else { Write-Debug " [-] (WhatIf) Creating synthetic destination branch directory: '$destinationBranch'"; $destinationInfo = ([System.IO.DirectoryInfo]::new($destinationDirectory)); } } else { if ($CreateDirs.ToBool()) { Write-Debug " [-] Creating destination branch directory: '$destinationBranch'"; $destinationInfo = (Test-Path -Path $destinationDirectory) ` ? (Get-Item -Path $destinationDirectory) ` : (New-Item -ItemType 'Directory' -Path $destinationDirectory); } else { Write-Debug " [-] Creating destination branch directory INFO obj: '$destinationBranch'"; $destinationInfo = New-Object -TypeName System.IO.DirectoryInfo ($destinationDirectory); } } if ($CopyFiles.ToBool()) { Write-Debug " [-] Creating files for branch directory: '$destinationBranch'"; # To use the include/exclude parameters on Copy-Item, the Path specified # must end in /*. We only need to add the star though because we added the / # previously. # [string]$sourceDirectoryWithWildCard = $sourceDirectoryFullName + '*'; [string[]]$adjustedFileIncludes = $FileIncludes | ForEach-Object { $_.Contains('*') ? $_ : "*.$_".Replace('..', '.'); } [string[]]$adjustedFileExcludes = $FileExcludes | ForEach-Object { $_.Contains('*') ? $_ : "*.$_".Replace('..', '.'); } # Ensure that the destination directory exists, but only if there are # files to copy over which pass the include/exclude filters. This is # required in the case where CreateDirs has not been specified. # [array]$filesToCopy = Get-ChildItem $sourceDirectoryWithWildCard ` -Include $adjustedFileIncludes -Exclude $adjustedFileExcludes -File; if ($filesToCopy) { if (-not($whatIf)) { if (-not(Test-Path -Path $destinationDirectory)) { New-Item -ItemType 'Directory' -Path $destinationDirectory; } Copy-Item -Path $sourceDirectoryWithWildCard ` -Include $adjustedFileIncludes -Exclude $adjustedFileExcludes ` -Destination $destinationDirectory; } $_exchange['LOOPZ.MIRROR.COPIED-FILES.COUNT'] = $filesToCopy.Count; Write-Debug " [-] No of files copied: '$($filesToCopy.Count)'"; } else { $_exchange.Remove('LOOPZ.MIRROR.COPIED-FILES.COUNT'); $_exchange.Remove('LOOPZ.MIRROR.COPIED-FILES.INCLUDES'); } } # To be consistent with Invoke-ForeachFsItem, the user function/block is invoked # with the source directory info. The destination for this mirror operation is # returned via 'LOOPZ.MIRROR.DESTINATION' within the Exchange. # $_exchange['LOOPZ.MIRROR.DESTINATION'] = $destinationInfo; $invokee = $_exchange['LOOPZ.MIRROR.INVOKEE']; if ($invokee -is [scriptblock]) { $positional = @($_underscore, $_index, $_exchange, $_trigger); if ($_exchange.ContainsKey('LOOPZ.MIRROR.INVOKEE.PARAMS')) { $_exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] | ForEach-Object { $positional += $_; } } $invokee.InvokeReturnAsIs($positional); } elseif ($invokee -is [string]) { [hashtable]$parameters = $_exchange.ContainsKey('LOOPZ.MIRROR.INVOKEE.PARAMS') ` ? $_exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] : @{}; $parameters['Underscore'] = $_underscore; $parameters['Index'] = $_index; $parameters['Exchange'] = $_exchange; $parameters['Trigger'] = $_trigger; & $invokee @parameters; } else { Write-Warning "User defined function/block not valid, not invoking."; } @{ Product = $destinationInfo } } #doMirrorBlock # ===================================================== [Invoke-MirrorDirectoryTree] === [string]$resolvedSourcePath = Convert-Path $Path; [string]$resolvedDestinationPath = Convert-Path $DestinationPath; $Exchange['LOOPZ.MIRROR.ROOT-SOURCE'] = $resolvedSourcePath; $Exchange['LOOPZ.MIRROR.ROOT-DESTINATION'] = $resolvedDestinationPath; if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) { $Exchange['LOOPZ.MIRROR.INVOKEE'] = $Block; if ($BlockParams.Count -gt 0) { $Exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] = $BlockParams; } } else { $Exchange['LOOPZ.MIRROR.INVOKEE'] = $Functee; if ($FuncteeParams.Count -gt 0) { $Exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] = $FuncteeParams.Clone(); } } if ($PSBoundParameters.ContainsKey('WhatIf') -and ($true -eq $PSBoundParameters['WhatIf'])) { $Exchange['WHAT-IF'] = $true; } if ($CopyFiles.ToBool()) { $Exchange['LOOPZ.MIRROR.COPIED-FILES.INCLUDES'] = $FileIncludes -join ', '; } [scriptblock]$filterDirectories = { [OutputType([boolean])] param( [System.IO.DirectoryInfo]$directoryInfo ) Select-FsItem -Name $directoryInfo.Name ` -Includes $DirectoryIncludes -Excludes $DirectoryExcludes; } $null = Invoke-TraverseDirectory -Path $resolvedSourcePath ` -Block $doMirrorBlock -Exchange $Exchange -Header $Header -Summary $Summary ` -SessionHeader $SessionHeader -SessionSummary $SessionSummary -Condition $filterDirectories -Hoist:$Hoist; } # Invoke-MirrorDirectoryTree function Invoke-TraverseDirectory { <# .NAME Invoke-TraverseDirectory .SYNOPSIS Traverses a directory tree invoking a custom defined script-block or named function as it goes. .DESCRIPTION Navigates a directory tree applying custom functionality for each directory. A Condition script-block can be applied for conditional functionality. 2 parameters set are defined, one for invoking a named function (InvokeFunction) and the other (InvokeScriptBlock, the default) for invoking a scriptblock. An optional Summary script block can be specified which will be invoked at the end of the traversal batch. .PARAMETER Block The script block to be invoked. The script block is invoked for each directory in the source directory tree that satisfy the specified Condition predicate with the following positional parameters: * underscore: the DirectoryInfo object representing the directory in the source tree * index: the 0 based index representing current directory in the source tree * Exchange object: a hash table containing miscellaneous information gathered internally throughout the mirroring batch. This can be of use to the user, because it is the way the user can perform bi-directional communication between the invoked custom script block and client side logic. * trigger: a boolean value, useful for state changing idempotent operations. At the end of the batch, the state of the trigger indicates whether any of the items were actioned. When the script block is invoked, the trigger should indicate if the trigger was pulled for any of the items so far processed in the batch. This is the responsibility of the client's script-block/function implementation. In addition to these fixed positional parameters, if the invoked scriptblock is defined with additional parameters, then these will also be passed in. In order to achieve this, the client has to provide excess parameters in BlockParams and these parameters must be defined as the same type and in the same order as the additional parameters in the script-block. .PARAMETER BlockParams Optional array containing the excess parameters to pass into the script-block. .PARAMETER Condition This is a predicate script-block, which is invoked with a DirectoryInfo object presented as a result of invoking Get-ChildItem. It provides a filtering mechanism that is defined by the user to define which directories are selected for function/script-block invocation. .PARAMETER Exchange A hash table containing miscellaneous information gathered internally throughout the traversal batch. This can be of use to the user, because it is the way the user can perform bi-directional communication between the invoked custom script block and client side logic. .PARAMETER Functee String defining the function to be invoked. Works in a similar way to the Block parameter for script-blocks. The Function's base signature is as follows: * "Underscore": (See underscore described above) * "Index": (See index described above) * "Exchange": (See PathThru described above) * "Trigger": (See trigger described above) The destination DirectoryInfo object can be accessed via the Exchange denoted by the 'LOOPZ.MIRROR.DESTINATION' entry. .PARAMETER FuncteeParams Optional hash-table containing the named parameters which are splatted into the Functee function invoke. As it's a hash table, order is not significant. .PARAMETER Header A script-block that is invoked for each directory that also contains child directories. The script-block is invoked with the following positional parameters: * Exchange: (see Exchange previously described) The Header can be customised with the following Exchange entries: * 'LOOPZ.KRAYOLA-THEME': Krayola Theme generally in use * 'LOOPZ.HEADER-BLOCK.MESSAGE': message displayed as part of the header * 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL': Lead text displayed in header, default: '[+] ' * 'LOOPZ.HEADER.PROPERTIES': An array of Key/Value pairs of items to be displayed * 'LOOPZ.HEADER-BLOCK.LINE': A string denoting the line to be displayed. (There are predefined lines available to use in $LoopzUI, or a custom one can be used instead) .PARAMETER Hoist Switch parameter. Without Hoist being specified, the Condition can prove to be too restrictive on matching against directories. If a directory does not match the Condition then none of its descendants will be considered to be traversed. When Hoist is specified then a descendant directory that does match the Condition will be traversed even though any of its ancestors may not match the same Condition. .PARAMETER Path The source Path denoting the root of the directory tree to be traversed. .PARAMETER SessionHeader A script-block that is invoked at the start of the traversal batch. The script-block has the same signature as the Header script block. .PARAMETER SessionSummary A script-block that is invoked at the end of the traversal batch. The script-block has the same signature as the Summary script block. .PARAMETER Summary A script-block that is invoked foreach directory that also contains child directories, after all its descendants have been processed and serves as a sub-total for the current directory. The script-block is invoked with the following positional parameters: * count: the number of items processed in the mirroring batch. * skipped: the number of items skipped in the mirroring batch. An item is skipped if it fails the defined condition or is not of the correct type (eg if its a directory but we have specified the -File flag). * errors: the number of items which resulted in error. An error occurs when the function or the script-block has set the Error property on the invoke result. * trigger: Flag set by the script-block/function, but should typically be used to indicate whether any of the items processed were actively updated/written in this batch. This helps in written idempotent operations that can be re-run without adverse consequences. * Exchange: (see Exchange previously described) .EXAMPLE 1 Invoke a script-block for every directory in the source tree. [scriptblock]$block = { param( $underscore, [int]$index, [hashtable]$exchange, [boolean]$trigger ) ... } Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Block $block .EXAMPLE 2 Invoke a named function with extra parameters for every directory in the source tree. function Test-Traverse { param( [System.IO.DirectoryInfo]$Underscore, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger, [string]$Format ) ... } [hashtable]$parameters = @{ 'Format' = "=== {0} ==="; } Invoke-TraverseDirectory -Path './Tests/Data/fefsi' ` -Functee 'Test-Traverse' -FuncteeParams $parameters; .EXAMPLE 3 Invoke a named function, including only directories beginning with A (filter A*) function Test-Traverse { param( [System.IO.DirectoryInfo]$Underscore, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger ) ... } [scriptblock]$filterDirectories = { [OutputType([boolean])] param( [System.IO.DirectoryInfo]$directoryInfo ) Select-FsItem -Name $directoryInfo.Name -Includes @('A*'); } Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Functee 'Test-Traverse' ` -Condition $filterDirectories; Note the possible issue with this example is that any descendants named A... which are located under an ancestor which is not named A..., will not be processed by the provided function .EXAMPLE 4 Mirror a directory tree, including only directories beginning with A (filter A*) regardless of the matching of intermediate ancestors (specifying -Hoist flag resolves the possible issue in the previous example) function Test-Traverse { param( [System.IO.DirectoryInfo]$Underscore, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger ) ... } [scriptblock]$filterDirectories = { [OutputType([boolean])] param( [System.IO.DirectoryInfo]$directoryInfo ) Select-FsItem -Name $directoryInfo.Name -Includes @('A*'); } Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Functee 'Test-Traverse' ` -Condition $filterDirectories -Hoist; Note that the directory filter must include a wild-card, otherwise it will be ignored. So a directory include of @('A'), is problematic, because A is not a valid directory filter so its ignored and there are no remaining filters that are able to include any directory, so no directory passes the filter. .EXAMPLE 5 Same as EXAMPLE 4, but using predefined Header and Summary script-blocks for Session header/summary and per directory header/summary. (Test-Traverse and filterDirectories as per EXAMPLE 4) Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Functee 'Test-Traverse' ` -Condition $filterDirectories -Hoist ` -Header $LoopzHelpers.DefaultHeaderBlock -Summary $DefaultHeaderBlock.SimpleSummaryBlock ` -SessionHeader $LoopzHelpers.DefaultHeaderBlock -SessionSummary $DefaultHeaderBlock.SimpleSummaryBlock; #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] [CmdletBinding(DefaultParameterSetName = 'InvokeScriptBlock')] [Alias('itd', 'Traverse-Directory')] param ( [Parameter(ParameterSetName = 'InvokeScriptBlock', Mandatory)] [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)] [ValidateScript( { Test-path -Path $_ })] [String]$Path, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [ValidateScript( { -not($_ -eq $null) })] [scriptblock]$Condition = ( { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] param([System.IO.DirectoryInfo]$directoryInfo) return $true; } ), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [hashtable]$Exchange = @{}, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [ValidateScript( { -not($_ -eq $null) })] [scriptblock]$Block, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [ValidateScript( { $_ -is [Array] })] $BlockParams = @(), [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)] [ValidateScript( { -not([string]::IsNullOrEmpty($_)); })] [string]$Functee, [Parameter(ParameterSetName = 'InvokeFunction')] [hashtable]$FuncteeParams = @{}, [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$Header = ( { param( [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$Summary = ( { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] param( [int]$_count, [int]$_skipped, [int]$_errors, [boolean]$_triggered, [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$SessionHeader = ( { param( [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [scriptblock]$SessionSummary = ( { param( [int]$_count, [int]$_skipped, [int]$_errors, [boolean]$_trigger, [hashtable]$_exchange ) }), [Parameter(ParameterSetName = 'InvokeScriptBlock')] [Parameter(ParameterSetName = 'InvokeFunction')] [switch]$Hoist ) # param # ======================================================= [recurseTraverseDirectory] === # [scriptblock]$recurseTraverseDirectory = { # Invoked by adapter [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] param( [Parameter(Position = 0, Mandatory)] [System.IO.DirectoryInfo]$directoryInfo, [Parameter(Position = 1)] [ValidateScript( { -not($_ -eq $null) })] [scriptblock]$condition, [Parameter(Position = 2, Mandatory)] [ValidateScript( { -not($_ -eq $null) })] [hashtable]$exchange, [Parameter(Position = 3)] [ValidateScript( { ($_ -is [scriptblock]) -or ($_ -is [string]) })] $invokee, # (scriptblock or function name; hence un-typed parameter) [Parameter(Position = 4)] [boolean]$trigger ) $result = $null; $index = $exchange['LOOPZ.FOREACH.INDEX']; # This is the invoke, for the current directory # if ($invokee -is [scriptblock]) { $positional = @($directoryInfo, $index, $exchange, $trigger); if ($exchange.ContainsKey('LOOPZ.TRAVERSE.INVOKEE.PARAMS') -and ($exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'].Count -gt 0)) { $exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] | ForEach-Object { $positional += $_; } } $result = $invokee.InvokeReturnAsIs($positional); } else { [hashtable]$parameters = $exchange.ContainsKey('LOOPZ.TRAVERSE.INVOKEE.PARAMS') ` ? $exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] : @{}; # These are directory specific overwrites. The custom parameters # will still be present # $parameters['Underscore'] = $directoryInfo; $parameters['Index'] = $index; $parameters['Exchange'] = $exchange; $parameters['Trigger'] = $trigger; $result = & $invokee @parameters; } [string]$fullName = $directoryInfo.FullName; [System.IO.DirectoryInfo[]]$directoryInfos = Get-ChildItem -Path $fullName ` -Directory | Where-Object { $condition.InvokeReturnAsIs($_) }; [scriptblock]$adapter = $Exchange['LOOPZ.TRAVERSE.ADAPTOR']; if ($directoryInfos) { # adapter is always a script block, this has nothing to do with the invokee, # which may be a script block or a named function(functee) # $directoryInfos | Invoke-ForeachFsItem -Directory -Block $adapter ` -Exchange $Exchange -Condition $condition -Summary $Summary; } return $result; } # recurseTraverseDirectory # ======================================================================== [adapter] === # [scriptblock]$adapter = { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] param( [Parameter(Mandatory)] [System.IO.DirectoryInfo]$_underscore, [Parameter(Mandatory)] [int]$_index, [Parameter(Mandatory)] [hashtable]$_exchange, [Parameter(Mandatory)] [boolean]$_trigger ) [scriptblock]$adapted = $_exchange['LOOPZ.TRAVERSE.ADAPTED']; $controller = $_exchange['LOOPZ.CONTROLLER']; try { $adapted.InvokeReturnAsIs( $_underscore, $_exchange['LOOPZ.TRAVERSE.CONDITION'], $_exchange, $Exchange['LOOPZ.TRAVERSE.INVOKEE'], $_trigger ); } catch [System.Management.Automation.MethodInvocationException] { $controller.ErrorItem(); # This is a mystery exception, that has no effect on processing the batch: # # Exception calling ".ctor" with "2" argument(s): "Count cannot be less than zero. # # Resolve-Error # Write-Error "Problem with: '$_underscore'" -ErrorAction Stop; } catch { $controller.ErrorItem(); Write-Error "[!] Error: $($_.Exception.Message)" -ErrorAction Continue; throw; } } # adapter # ======================================================= [Invoke-TraverseDirectory] === $controller = New-Controller -Type TraverseCtrl -Exchange $Exchange ` -Header $Header -Summary $Summary -SessionHeader $SessionHeader -SessionSummary $SessionSummary; $Exchange['LOOPZ.CONTROLLER'] = $controller; $controller.BeginSession(); # Handle top level directory, before recursing through child directories # [System.IO.DirectoryInfo]$directory = Get-Item -Path $Path; [boolean]$itemIsDirectory = ($directory.Attributes -band [System.IO.FileAttributes]::Directory) -eq [System.IO.FileAttributes]::Directory; if ($itemIsDirectory) { if ($Condition.InvokeReturnAsIs($directory)) { [boolean]$trigger = $controller.GetTrigger(); # The index of the top level directory is always 0 # [int]$index = $controller.RequestIndex(); if ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) { # set-up custom parameters # [hashtable]$parameters = $FuncteeParams.Clone(); $parameters['Underscore'] = $directory; $parameters['Index'] = $index; $parameters['Exchange'] = $Exchange; $parameters['Trigger'] = $trigger; $Exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] = $parameters; } elseif ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) { $positional = @($directory, $index, $Exchange, $trigger); if ($BlockParams.Count -gt 0) { $BlockParams | Foreach-Object { $positional += $_; } } # Note, for the positional parameters, we can only pass in the additional # custom parameters provided by the client here via the Exchange otherwise # we could accidentally build up the array of positional parameters with # duplicated entries. This is in contrast to splatted arguments for function # invokes where parameter names are paired with parameter values in a # hashtable and naturally prevent duplicated entries. This is why we set # 'LOOPZ.TRAVERSE.INVOKEE.PARAMS' to $BlockParams and not $positional. # $Exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] = $BlockParams; } $result = $null; # This is the top level invoke # try { if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) { $result = $Block.InvokeReturnAsIs($positional); } elseif ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) { $result = & $Functee @parameters; } } catch { $controller.IncrementError(); } finally { $controller.HandleResult($result); } } else { $controller.SkipItem(); } # --- end of top level invoke ---------------------------------------------------------- if ($Hoist.ToBool()) { # Perform non-recursive retrieval of descendant directories # [System.IO.DirectoryInfo[]]$directoryInfos = Get-ChildItem -Path $Path ` -Directory -Recurse | Where-Object { $Condition.InvokeReturnAsIs($_) } Write-Debug " [o] Invoke-TraverseDirectory (Hoist); Count: $($directoryInfos.Count)"; if ($directoryInfos) { # No need to manage the index, let Invoke-ForeachFsItem do this for us, # except we do need to inform Invoke-ForeachFsItem to start the index at # +1, because 0 is for the top level directory which has already been # handled. # [hashtable]$parametersFeFsItem = @{ 'Directory' = $true; 'Exchange' = $Exchange; 'Summary' = $Summary; } if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) { $parametersFeFsItem['Block'] = $Block; $parametersFeFsItem['BlockParams'] = $BlockParams; } else { $parametersFeFsItem['Functee'] = $Functee; $parametersFeFsItem['FuncteeParams'] = $FuncteeParams; } $directoryInfos | & 'Invoke-ForeachFsItem' @parametersFeFsItem; } } else { # Top level descendants # # Set up the adapter. (NB, can't use splatting because we're invoking a script block # as opposed to a named function.) # $Exchange['LOOPZ.TRAVERSE.CONDITION'] = $Condition; $Exchange['LOOPZ.TRAVERSE.ADAPTED'] = $recurseTraverseDirectory; $Exchange['LOOPZ.TRAVERSE.ADAPTOR'] = $adapter; if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) { $Exchange['LOOPZ.TRAVERSE.INVOKEE'] = $Block; } elseif ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) { $Exchange['LOOPZ.TRAVERSE.INVOKEE'] = $Functee; } # Now perform start of recursive traversal # [System.IO.DirectoryInfo[]]$directoryInfos = Get-ChildItem -Path $Path ` -Directory | Where-Object { $Condition.InvokeReturnAsIs($_) } if ($directoryInfos) { $directoryInfos | Invoke-ForeachFsItem -Directory -Block $adapter ` -Exchange $Exchange -Condition $Condition -Summary $Summary; } } } else { $controller.SkipItem(); Write-Error "Path specified '$($Path)' is not a directory"; } $controller.EndSession(); } # Invoke-TraverseDirectory function Format-StructuredLine { <# .NAME Format-StructuredLine .SYNOPSIS Helper function to make it easy to generate a line to be displayed. .DESCRIPTION A structured line is some text that includes embedded colour instructions that will be interpreted by the Krayola krayon writer. This function behaves like a layout manager for a single line. .PARAMETER CrumbKey The key used to index into the $Exchange hashtable to denote which crumb is used. .PARAMETER Exchange The exchange hashtable object. .PARAMETER Krayon The writer object which contains the Krayola theme. .PARAMETER LineKey The key used to index into the $Exchange hashtable to denote the core line. .PARAMETER MessageKey The key used to index into the $Exchange hashtable to denote what message to display. .PARAMETER Options + this is the crumb | V <-- message ->| [@@] --------------------------------------------------- [ Rename (WhatIf) ] --- |<-- This is a trailing wing whose length is WingLength |<--- flex part (which must be at least -------->| MinimumFlexSize in length, it shrinks to accommodate the message) A PSCustomObject that allows further customisation of the structured line. Can contain the following fields: - WingLength: The size of the lead and tail portions of the line ('---') - MinimumFlexSize: The smallest size that the flex part can shrink to, to accommodate the message. If the message is so large that is pushes up against the minimal flex size it will be truncated according to the presence of Truncate switch - Ellipses: When message truncation occurs, the ellipses string is used to indicate that the message has been truncated. - WithLead: boolean flag to indicate whether a leading wing is displayed which would precede the crumb. In the above example and by default, there is no leading wing. .PARAMETER Truncate switch parameter to indicate whether the message is truncated to fit the line length. #> [OutputType([string])] param( [Parameter(Mandatory)] [hashtable]$Exchange, # We need to replace the exchange key parameters with direct parameters [Parameter(Mandatory)] [string]$LineKey, [Parameter()] [string]$CrumbKey, [Parameter()] [string]$MessageKey, [Parameter()] [switch]$Truncate, [Parameter()] [Krayon]$Krayon, [Parameter()] [PSCustomObject]$Options = (@{ WingLength = 3; MinimumFlexSize = 6; Ellipses = ' ...'; WithLead = $false; }) ) [int]$wingLength = Get-PsObjectField $Options 'WingLength' 3; [int]$minimumFlexSize = Get-PsObjectField $Options 'MinimumFlexSize' 6; [string]$ellipses = Get-PsObjectField $Options 'Ellipses' ' ...'; [boolean]$withLead = Get-PsObjectField $Options 'WithLead' $false; [string]$formatWithArg = $Krayon.ApiFormatWithArg; [hashtable]$theme = $Krayon.Theme; [string]$line = $Exchange.ContainsKey($LineKey) ` ? $Exchange[$LineKey] : ([string]::new("_", 81)); [string]$char = ($line -match '[^\s]') ? $matches[0] : ' '; [string]$wing = [string]::new($char, $wingLength); [string]$message = -not([string]::IsNullOrEmpty($MessageKey)) -and ($Exchange.ContainsKey($MessageKey)) ` ? $Exchange[$MessageKey] : $null; [string]$crumb = if (-not([string]::IsNullOrEmpty($CrumbKey)) -and ($Exchange.ContainsKey($CrumbKey))) { if ($Exchange.ContainsKey('LOOPZ.SIGNALS')) { [hashtable]$signals = $Exchange['LOOPZ.SIGNALS']; [string]$crumbName = $Exchange[$CrumbKey]; $signals[$crumbName].Value; } else { '+'; } } else { $null; } [string]$structuredLine = if ([string]::IsNullOrEmpty($message) -and [string]::IsNullOrEmpty($crumb)) { $($formatWithArg -f "ThemeColour", "meta") + $line; } else { [string]$open = $theme['OPEN']; [string]$close = $theme['CLOSE']; # TODO: The deductions need to be calculated in a dynamic form, to cater # for optional fields. # if (-not([string]::IsNullOrEmpty($message)) -and -not([string]::IsNullOrEmpty($crumb))) { # 'lead' + 'open' + 'crumb' + 'close' + 'mid' + 'open' + 'message' + 'close' + 'tail' # # '*{lead} *{open}*{crumb}*{close} *{mid} *{open} *{message} *{close} *{tail}' => Format # +-----------------------------------------------|--------|-----------------+ # | Start | | End | => Snippet # [string]$startFormat = '*{open}*{crumb}*{close} *{mid} *{open} '; if ($withLead) { $startFormat = '*{lead} ' + $startFormat; } [string]$endFormat = ' *{close} *{tail}'; [string]$startSnippet = $startFormat.Replace('*{lead}', $wing). ` Replace('*{open}', $open). ` Replace('*{crumb}', $crumb). ` Replace('*{close}', $close); [string]$endSnippet = $endFormat.Replace('*{close}', $close). ` Replace('*{tail}', $wing); [string]$withoutMid = $startSnippet.Replace('*{mid}', '') + $endSnippet; [int]$deductions = $withoutMid.Length + $minimumFlexSize; [int]$messageSpace = $line.Length - $deductions; [boolean]$overflow = $message.Length -gt $messageSpace; [int]$midSize = if ($overflow) { # message size is the unknown variable and $midSize is a known # quantity: minimumFlexSize. # if ($Truncate.ToBool()) { [int]$messageKeepAmount = $messageSpace - $ellipses.Length; $message = $message.Substring(0, $messageKeepAmount) + $ellipses; } $minimumFlexSize; } else { # midSize is the unknown variable and the message size is a known # quantity: $message.Length # [int]$deductions = $withoutMid.Length + $message.Length; $line.Length - $deductions; } [string]$mid = [string]::new($char, $midSize); $startSnippet = $startSnippet.Replace('*{mid}', $mid); $($formatWithArg -f "ThemeColour", "meta") + $startSnippet + ` $($formatWithArg -f "ThemeColour", "message") + $message + ` $($formatWithArg -f "ThemeColour", "meta") + $endSnippet; } elseif (-not([string]::IsNullOrEmpty($message))) { # 'lead' + 'open' + 'message' + 'close' + 'tail' # # '*{lead} *{open} *{message} *{close} *{tail}' # +----------------|--------|-----------------+ # | Start | | End | => Snippet # # The lead is mandatory in this case so ignore withLead # [string]$startFormat = '*{lead} *{open} '; [string]$endFormat = ' *{close} *{tail}'; [string]$endSnippet = $endFormat.Replace('*{close}', $close). ` Replace('*{tail}', $wing); [string]$withoutLead = $startFormat.Replace('*{lead}', ''). ` Replace('*{open}', $open); [int]$deductions = $minimumFlexSize + $withoutLead.Length + $endSnippet.Length; [int]$messageSpace = $line.Length - $deductions; [boolean]$overflow = $message.Length -gt $messageSpace; [int]$leadSize = if ($overflow) { if ($Truncate.ToBool()) { # Truncate the message # [int]$messageKeepAmount = $messageSpace - $Ellipses.Length; $message = $message.Substring(0, $messageKeepAmount) + $Ellipses; } $minimumFlexSize; } else { $line.Length - $withoutLead.Length - $message.Length - $endSnippet.Length; } # The lead is now the variable part so should be calculated last # [string]$lead = [string]::new($char, $leadSize); [string]$startSnippet = $startFormat.Replace('*{lead}', $lead). ` Replace('*{open}', $open); $($formatWithArg -f "ThemeColour", "meta") + $startSnippet + ` $($formatWithArg -f "ThemeColour", "message") + $message + ` $($formatWithArg -f "ThemeColour", "meta") + $endSnippet; } elseif (-not([string]::IsNullOrEmpty($crumb))) { # 'lead' + 'open' + 'crumb' + 'close' + 'tail' # # '*{lead} *{open}*{crumb}*{close} *{tail}' # +--------------------------------+------+ # |Start |End | => 2 Snippets can be combined into lineSnippet # because they use the same colours. # [string]$startFormat = '*{open}*{crumb}*{close} '; if ($withLead) { $startFormat = '*{lead} ' + $startFormat; } [string]$startFormat = '*{open}*{crumb}*{close} '; [string]$startSnippet = $startFormat.Replace('*{lead}', $wing). ` Replace('*{open}', $open). ` Replace('*{crumb}', $crumb). ` Replace('*{close}', $close); [string]$withTailFormat = $startSnippet + '*{tail}'; [int]$deductions = $startSnippet.Length; [int]$tailSize = $line.Length - $deductions; [string]$tail = [string]::new($char, $tailSize); [string]$lineSnippet = $withTailFormat.Replace('*{tail}', $tail); $($formatWithArg -f "ThemeColour", "meta") + $lineSnippet; } } return $structuredLine; } function Show-Header { <# .NAME Show-Header .SYNOPSIS Function to display header as part of an iteration batch. .DESCRIPTION Behaviour can be customised by the following entries in the Exchange: * 'LOOPZ.KRAYON' (mandatory): the Krayola Krayon writer object. * 'LOOPZ.HEADER-BLOCK.MESSAGE': The custom message to be displayed as part of the header. * 'LOOPZ.HEADER.PROPERTIES': A Krayon [line] instance contain a collection of Krayola [couplet]s. When present, the header displayed will be a static line, the collection of these properties then another static line. * 'LOOPZ.HEADER-BLOCK.LINE': The static line text. The length of this line controls how everything else is aligned (ie the flex part and the message if present). .PARAMETER Exchange The exchange hashtable object. #> param( [Parameter()] [hashtable]$Exchange ) [Krayon]$krayon = $Exchange['LOOPZ.KRAYON']; if (-not($krayon)) { throw "Writer missing from Exchange under key 'LOOPZ.KRAYON'" } $null = $krayon.Reset(); [string]$writerFormatWithArg = $krayon.ApiFormatWithArg; [string]$message = $Exchange.ContainsKey( 'LOOPZ.HEADER-BLOCK.MESSAGE') ? $Exchange['LOOPZ.HEADER-BLOCK.MESSAGE'] : [string]::Empty; # get the properties from Exchange ('LOOPZ.HEADER.PROPERTIES') # properties should not be a line, because line implies all these properties are # written on the same line. Rather it is better described as array of Krayola pairs, # which is does not share the same semantics as line. However, since line is just a # collection of pairs, the client can use the line abstraction, but not the line # method on the writer, unless they want it to actually represent a line. # [line]$properties = $Exchange.ContainsKey( 'LOOPZ.HEADER.PROPERTIES') ? $Exchange['LOOPZ.HEADER.PROPERTIES'] : [line]::new(); if ($properties.Line.Length -gt 0) { # First line # [string]$line = $Exchange.ContainsKey('LOOPZ.HEADER-BLOCK.LINE') ` ? $Exchange['LOOPZ.HEADER-BLOCK.LINE'] : ([string]::new('_', $_LineLength)); # $_LineLength ??? (oops my bad) [string]$structuredLine = $($writerFormatWithArg -f 'ThemeColour', 'meta') + $line; $null = $krayon.ScribbleLn($structuredLine); # Inner detail # if (-not([string]::IsNullOrEmpty($message))) { $null = $krayon.Message($message); } $null = $krayon.Line($properties); # Second line # [string]$structuredLine = $($writerFormatWithArg -f 'ThemeColour', 'meta') + $line; $null = $krayon.ScribbleLn($structuredLine); } else { # Alternative line # [string]$lineKey = 'LOOPZ.HEADER-BLOCK.LINE'; [string]$crumbKey = 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL'; [string]$messageKey = 'LOOPZ.HEADER-BLOCK.MESSAGE'; [string]$structuredLine = Format-StructuredLine -Exchange $exchange ` -LineKey $LineKey -CrumbKey $CrumbKey -MessageKey $messageKey -Krayon $krayon -Truncate; $null = $krayon.ScribbleLn($structuredLine); } } function Show-Summary { <# .NAME Show-Header .SYNOPSIS Function to display summary as part of an iteration batch. .DESCRIPTION Behaviour can be customised by the following entries in the Exchange: * 'LOOPZ.KRAYON' (mandatory): the Krayola Krayon writer object. * 'LOOPZ.SUMMARY-BLOCK.MESSAGE': The custom message to be displayed as part of the summary. * 'LOOPZ.SUMMARY.PROPERTIES': A Krayon [line] instance contain a collection of Krayola [couplet]s. The first line of summary properties shows the values of $Count, $Skipped and $Triggered. The properties, if present are appended to this line. * 'LOOPZ.SUMMARY-BLOCK.LINE': The static line text. The length of this line controls how everything else is aligned (ie the flex part and the message if present). * 'LOOPZ.SUMMARY-BLOCK.WIDE-ITEMS': The collection (an array of Krayola [lines]s) containing 'wide' items and therefore should be on their own separate line. * 'LOOPZ.SUMMARY-BLOCK.GROUP-WIDE-ITEMS': Perhaps the wide items are not so wide after all, so if this entry is set (a boolean value), the all wide items appear on their own line. .PARAMETER CapturedOnly .PARAMETER Count The number items processed, this is the number of items in the pipeline which match the $Pattern specified and therefore are allocated an index. .PARAMETER Errors The number of errors that occurred during the batch. .PARAMETER Exchange The exchange hashtable object. .PARAMETER Skipped The number of pipeline items skipped. An item is skipped for the following reasons: * Item name does not match the $Include expression * Item name satisfies the $Exclude expression. ($Exclude overrides $Include) * Iteration is terminated early by the invoked function/script-block returning a PSCustomObject with a Break property set to $true. * FileSystem item is not of the request type. Eg, if File is specified, then all directory items will be skipped. * An item fails to satisfy the $Condition predicate. * Number of items processed breaches Top. .PARAMETER Triggered Indicates whether any of the processed pipeline items were actioned in a modifying batch; ie if no items were mutated, then Triggered would be $false. #> param( [Parameter()] [int]$Count, [Parameter()] [int]$Skipped, [Parameter()] [int]$Errors, [Parameter()] [boolean]$Triggered, [Parameter()] [hashtable]$Exchange = @{} ) [Krayon]$krayon = $Exchange['LOOPZ.KRAYON']; if (-not($krayon)) { throw "Writer missing from Exchange under key 'LOOPZ.KRAYON'" } [string]$writerFormatWithArg = $krayon.ApiFormatWithArg; # First line # if ($Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.LINE')) { [string]$line = $Exchange['LOOPZ.SUMMARY-BLOCK.LINE']; # Assuming writerFormatWithArg is &[{0},{1}] # => generates &[ThemeColour,meta] which is an instruction to set the # colours to the krayola theme's 'META-COLOURS' # [string]$structuredBorderLine = $($writerFormatWithArg -f 'ThemeColour', 'meta') + $line; $null = $krayon.ScribbleLn($structuredBorderLine); } else { $structuredBorderLine = [string]::Empty; } # Inner detail # [line]$properties = New-Line(@( $(New-Pair('Count', $Count)), $(New-Pair('Skipped', $Skipped)), $(New-Pair('Errors', $Errors)), $(New-Pair('Triggered', $Triggered)) )); [string]$message = $Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.MESSAGE') ` ? $Exchange['LOOPZ.SUMMARY-BLOCK.MESSAGE'] : 'Summary'; $null = $krayon.Line($message, $properties); [string]$blank = [string]::new(' ', $message.Length); # Custom properties # [line]$summaryProperties = $Exchange.ContainsKey( 'LOOPZ.SUMMARY.PROPERTIES') ? $Exchange['LOOPZ.SUMMARY.PROPERTIES'] : [line]::new(@()); if ($summaryProperties.Line.Length -gt 0) { $null = $krayon.Line($blank, $summaryProperties); } # Wide items # if ($Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.WIDE-ITEMS')) { [line]$wideItems = $Exchange['LOOPZ.SUMMARY-BLOCK.WIDE-ITEMS']; [boolean]$group = ($Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.GROUP-WIDE-ITEMS') -and $Exchange['LOOPZ.SUMMARY-BLOCK.GROUP-WIDE-ITEMS']); if ($group) { $null = $krayon.Line($blank, $wideItems); } else { foreach ($couplet in $wideItems.Line) { [line]$syntheticLine = New-Line($couplet); $null = $krayon.Line($blank, $syntheticLine); } } } # Second line # if (-not([string]::IsNullOrEmpty($structuredBorderLine))) { $null = $krayon.ScribbleLn($structuredBorderLine); } } function Write-HostFeItemDecorator { <# .NAME Write-HostFeItemDecorator .SYNOPSIS Wraps a function or script-block as a decorator writing appropriate user interface info to the host for each entry in the pipeline. .DESCRIPTION The script-block/function (invokee) being decorated may or may not Support ShouldProcess. If it does, then the client should add 'WHAT-IF' to the pass through, set to the current value of WhatIf; or more accurately the existence of 'WhatIf' in PSBoundParameters. Or another way of putting it is, the presence of WHAT-IF indicates SupportsShouldProcess, and the value of 'WHAT-IF' dictates the value of WhatIf. This way, we only need a single value in the Exchange, rather than having to represent SupportShouldProcess explicitly with another value. The Exchange must contain either a 'LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME' entry meaning a named function is being decorated or 'LOOPZ.WH-FOREACH-DECORATOR.BLOCK' meaning a script block is being decorated, but not both. By default, Write-HostFeItemDecorator will display an item no for each object in the pipeline and a property representing the Product. The Product is a property that the invokee can set on the PSCustomObject it returns. However, additional properties can be displayed. This can be achieved by the invokee populating another property Pairs, which is an array of string based key/value pairs. All properties found in Pairs will be written out by Write-HostFeItemDecorator. By default, to render the value displayed (ie the 'Product' property item on the PSCustomObject returned by the invokee), ToString() is called. However, the 'Product' property may not have a ToString() method, in this case (you will see an error indicating ToString method not being available), the user should provide a custom script-block to determine how the value is constructed. This can be done by assigning a custom script-block to the 'LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT' entry in Exchange. eg: [scriptblock]$customGetResult = { param($result) $result.SomeCustomPropertyOfRelevanceThatIsAString; } $Exchange['LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT'] = $customGetResult; ... Note also, the user can provide a custom 'GET-RESULT' in order to control what is displayed by Write-HostFeItemDecorator. This function is designed to be used with Invoke-ForeachFsItem and as such, it's signature needs to match that required by Invoke-ForeachFsItem. Any additional parameters can be passed in via the Exchange. The rationale behind Write-HostFeItemDecorator is to maintain separation of concerns that allows development of functions that could be used with Invoke-ForeachFsItem which do not contain any UI related code. This strategy also helps for the development of different commands that produce output to the terminal in a consistent manner. .PARAMETER Exchange A hash table containing miscellaneous information gathered internally throughout the iteration batch. This can be of use to the user, because it is the way the user can perform bi-directional communication between the invoked custom script block and client side logic. .PARAMETER Index The 0 based index representing current item in the pipeline. .PARAMETER Trigger A boolean value, useful for state changing idempotent operations. At the end of the batch, the state of the trigger indicates whether any of the items were actioned. When the script block is invoked, the trigger should indicate if the trigger was pulled for any of the items so far processed in the batch. This is the responsibility of the client's block implementation. .PARAMETER Underscore The current pipeline object. .RETURNS The result of invoking the decorated script-block. .EXAMPLE 1 function Test-FN { param( [System.IO.DirectoryInfo]$Underscore, [int]$Index, [hashtable]$Exchange, [boolean]$Trigger, ) $format = $Exchange['CLIENT.FORMAT']; @{ Product = $format -f $Underscore.Name, $Underscore.Exists } ... } [Systems.Collection.Hashtable]$exchange = @{ 'LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME' = 'Test-FN'; 'CLIENT.FORMAT' = '=== [{0}] -- [{1}] ===' } Get-ChildItem ... | Invoke-ForeachFsItem -Path <path> -Exchange $exchange -Functee 'Write-HostFeItemDecorator' So, Test-FN is not concerned about writing any output to the console, it simply does what it does silently and Write-HostFeItemDecorator handles generation of output. It invokes the function defined in 'LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME' and generates corresponding output. It happens to use the console colouring facility provided by a a dependency Elizium.Krayola to create colourful output in a predefined format via the Krayola Theme. Note, Write-HostFeItemDecorator does not forward additional parameters to the decorated function (Test-FN), but this can be circumvented via the Exchange as illustrated by the 'CLIENT.FORMAT' parameter in this example. #> [OutputType([PSCustomObject])] [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")] [Alias('wife', 'Decorate-Foreach')] param ( [Parameter( Mandatory = $true )] $Underscore, [Parameter( Mandatory = $true )] [int]$Index, [Parameter( Mandatory = $true )] [ValidateScript( { return ($_.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME') -xor $_.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.BLOCK')) })] [hashtable] $Exchange, [Parameter()] [boolean]$Trigger ) [scriptblock]$defaultGetResult = { param($result) $result.ToString(); } [Krayon]$krayon = $_exchange['LOOPZ.KRAYON']; [scriptblock]$decorator = { param ($_underscore, $_index, $_exchange, $_trigger) if ($_exchange.Contains('LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME')) { [string]$functee = $_exchange['LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME']; [hashtable]$parameters = @{ 'Underscore' = $_underscore; 'Index' = $_index; 'Exchange' = $_exchange; 'Trigger' = $_trigger; } if ($_exchange.Contains('WHAT-IF')) { $parameters['WhatIf'] = $_exchange['WHAT-IF']; } return & $functee @parameters; } elseif ($_exchange.Contains('LOOPZ.WH-FOREACH-DECORATOR.BLOCK')) { [scriptblock]$block = $_exchange['LOOPZ.WH-FOREACH-DECORATOR.BLOCK']; return $block.InvokeReturnAsIs($_underscore, $_index, $_exchange, $_trigger); } } $invokeResult = $decorator.InvokeReturnAsIs($Underscore, $Index, $Exchange, $Trigger); [string]$message = $Exchange['LOOPZ.WH-FOREACH-DECORATOR.MESSAGE']; [string]$productValue = [string]::Empty; [boolean]$ifTriggered = $Exchange.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.IF-TRIGGERED'); [boolean]$resultIsTriggered = $invokeResult.psobject.properties.match('Trigger') -and $invokeResult.Trigger; # Suppress the write if client has set IF-TRIGGERED and the result is not triggered. # This makes re-runs of a state changing operation less verbose if that's required. # if (-not($ifTriggered) -or ($resultIsTriggered)) { $getResult = $Exchange.Contains('LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT') ` ? $Exchange['LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT'] : $defaultGetResult; [line]$themedPairs = $( New-Line( $(New-Pair('No', $("{0,3}" -f ($Index + 1)))) ) ); # Get Product if it exists # [string]$productLabel = [string]::Empty; if ($invokeResult -and $invokeResult.psobject.properties.match('Product') -and $invokeResult.Product) { [boolean]$affirm = $invokeResult.psobject.properties.match('Affirm') -and $invokeResult.Affirm; $productValue = $getResult.InvokeReturnAsIs($invokeResult.Product); $productLabel = $Exchange.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.PRODUCT-LABEL') ` ? $Exchange['LOOPZ.WH-FOREACH-DECORATOR.PRODUCT-LABEL'] : 'Product'; if (-not([string]::IsNullOrWhiteSpace($productLabel))) { $themedPairs.append($(New-Pair(@($productLabel, $productValue, $affirm)))); } } # Get Key/Value Pairs # if ($invokeResult -and $invokeResult.psobject.properties.match('Pairs') -and $invokeResult.Pairs -and ($invokeResult.Pairs -is [line]) -and ($invokeResult.Pairs.Line.Count -gt 0)) { $themedPairs.append($invokeResult.Pairs); } [hashtable]$krayolaTheme = $krayon.Theme; # Write the primary line # if (-not([string]::IsNullOrEmpty($message))) { $null = $krayon.Message($message); } $null = $krayon.Line($themedPairs); # Write additional lines # if ($invokeResult -and $invokeResult.psobject.properties.match('Lines') -and $invokeResult.Lines) { [int]$indent = $Exchange.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.INDENT') ` ? $Exchange['LOOPZ.WH-FOREACH-DECORATOR.INDENT'] : 3; [string]$blank = [string]::new(' ', $indent); [Krayon]$adjustedWriter = if ($Exchange.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.WRITER')) { $Exchange['LOOPZ.WH-FOREACH-DECORATOR.WRITER']; } else { [hashtable]$adjustedTheme = $krayolaTheme.Clone(); $adjustedTheme['MESSAGE-SUFFIX'] = [string]::Empty; $adjustedTheme['OPEN'] = [string]::Empty; $adjustedTheme['CLOSE'] = [string]::Empty; $Exchange['LOOPZ.WH-FOREACH-DECORATOR.WRITER'] = New-Krayon -Theme $adjustedTheme; $Exchange['LOOPZ.WH-FOREACH-DECORATOR.WRITER']; } [line[]]$additionalLines = if ([string]::IsNullOrEmpty($invokeResult.ErrorReason)) { $invokeResult.Lines; } else { $( New-Line( $(New-Pair('Error', $invokeResult.ErrorReason)) ) ) + $invokeResult.Lines; } foreach ($line in $additionalLines) { $null = $adjustedWriter.Message($blank).Line($line); } } } return $invokeResult; } # Write-HostFeItemDecorator function Edit-RemoveSingleSubString { <# .NAME edit-RemoveSingleSubString .SYNOPSIS Removes a sub-string from the target string provided. .DESCRIPTION Either the first or the last occurrence of a single substring can be removed depending on whether the Last flag has been set. .PARAMETER Last Flag to indicate whether the last occurrence of a sub string is to be removed from the Target. .PARAMETER Subtract The sub string to subtract from the Target. .PARAMETER Target The string from which the subtraction is to occur. .PARAMETER Insensitive Flag to indicate if the search is case sensitive or not. By default, search is case sensitive. #> [CmdletBinding(DefaultParameterSetName = 'Single')] [OutputType([string])] param ( [Parameter(ParameterSetName = 'Single')] [String]$Target, [Parameter(ParameterSetName = 'Single')] [String]$Subtract, [Parameter(ParameterSetName = 'Single')] [switch]$Insensitive, [Parameter(ParameterSetName = 'Single')] [Parameter(ParameterSetName = 'LastOnly')] [switch]$Last ) [StringComparison]$comparison = $Insensitive.ToBool() ? ` [StringComparison]::OrdinalIgnoreCase : [StringComparison]::Ordinal; $result = $Target; # https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings # if (($Subtract.Length -gt 0) -and ($Target.Contains($Subtract, $comparison))) { $slen = $Subtract.Length; $foundAt = $Last.ToBool() ? $Target.LastIndexOf($Subtract, $comparison) : ` $Target.IndexOf($Subtract, $comparison); if ($foundAt -eq 0) { $result = $Target.Substring($slen); } elseif ($foundAt -gt 0) { $result = $Target.Substring(0, $foundAt); $result += $Target.Substring($foundAt + $slen); } } $result; } function Get-InverseSubString { <# .NAME Get-InverseSubString .SYNOPSIS Performs the opposite of [string]::Substring. .DESCRIPTION Returns the remainder of that part of the substring denoted by the $StartIndex $Length. .PARAMETER Length The number of characters in the sub-string. .PARAMETER Marker A character used to mark the position of the sub-string. If the client specifies a marker, then this marker is inserted between the head and the tail. .PARAMETER Source The source string .PARAMETER Split When getting the inverse sub-string there are two elements that are returned, the head (prior to sub-string) and the tail, what comes after the sub-string. This switch indicates whether the function returns the head and tail as separate entities in an array, or should simply return the tail appended to the head. .PARAMETER StartIndex The index of sub-string. #> param( [Parameter(Position = 0, Mandatory)] [string]$Source, [Parameter()] [ValidateScript( { $_ -lt $Source.Length })] [int]$StartIndex = 0, [Parameter()] [ValidateScript( { $_ -le ($Source.Length - $StartIndex ) })] [int]$Length = 0, [Parameter()] [switch]$Split, [Parameter()] [char]$Marker ) $result = if ($StartIndex -eq 0) { $PSBoundParameters.ContainsKey('Marker') ` ? $($Marker + $Source.SubString($Length)) : $Source.SubString($Length); } else { [string]$head = $Source.SubString(0, $StartIndex); if ($PSBoundParameters.ContainsKey('Marker')) { $head += $Marker; } [string]$tail = $Source.SubString($StartIndex + $Length); ($Split.ToBool()) ? ($head, $tail) : ($head + $tail); } $result; } function Get-IsLocked { <# .NAME Get-IsLocked .SYNOPSIS Utility function to determine whether the environment variable specified denotes that it is set to $true to indicate the associated function is in a locked state. .DESCRIPTION Returns a boolean indicating the 'locked' status of the associated functionality. Eg, for the Rename-Many command, a user can only use it for real when it has been unlocked by setting it's associated environment variable 'LOOPZ_REMY_LOCKED' to $false. .PARAMETER Variable The environment variable to check. #> [OutputType([boolean])] param( [Parameter(Mandatory)] [string]$Variable ) [string]$lockedEnv = Get-EnvironmentVariable $Variable; [boolean]$locked = ([string]::IsNullOrEmpty($lockedEnv) -or (-not([string]::IsNullOrEmpty($lockedEnv)) -and ($lockedEnv -eq [boolean]::TrueString))); return $locked; } function Get-PlatformName { <# .NAME Get-PlatformName .SYNOPSIS Get the name of the operating system. .DESCRIPTION There are multiple ways to get the OS type in PowerShell but they are convoluted and can return an unfriendly name such as 'Win32NT'. This command simply returns 'windows', 'linux' or 'mac', simples! This function is typically used alongside Invoke-ByPlatform and Resolve-ByPlatform. #> $result = if ($IsWindows) { 'windows'; } elseif ($IsLinux) { 'linux'; } elseif ($IsMacOS) { 'mac'; } else { [string]::Empty; } $result; } function Get-PsObjectField { <# .NAME Get-PsObjectField .SYNOPSIS Simplifies getting the value of a field from a PSCustomObject. .DESCRIPTION Returns the value of the specified field. If the field is missing, then the default is returned. .PARAMETER Default Default value to return if the $Field doesn't exist on the $Object. .PARAMETER Field The field to get value of. .PARAMETER Object The object to get the field value from. #> param( [Parameter(Position = 0, Mandatory)] [PSCustomObject]$Object, [Parameter(Position = 1, Mandatory)] [string]$Field, [Parameter(Position = 2)] $Default = $null ) ($Object.psobject.properties.match($Field) -and $Object.$Field) ? ($Object.$Field) : $Default; } function Invoke-ByPlatform { <# .NAME Invoke-ByPlatform .SYNOPSIS Given a hashtable, invokes the function/script-block whose corresponding key matches the operating system name as returned by Get-PlatformName. .DESCRIPTION Provides a way to provide OS specific functionality. Returns $null if the $Hash does not contain an entry corresponding to the current platform. (Doesn't support invoking a function with named parameters; PowerShell doesn't currently support this, not even via splatting, if this changes, this will be implemented.) .PARAMETER Hash A hashtable object whose keys are values that can be returned by Get-PlatformName. The values are of type PSCustomObject and can contain the following properties: + FnInfo: A FunctionInfo instance. This can be obtained from an existing function by invoking Get-Command -Name <function-name> + Positional: an array of positional parameter values #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSPossibleIncorrectUsageOfAssignmentOperator", "")] param( [Parameter()] [hashtable]$Hash ) $result = $null; [string]$platform = Get-PlatformName; [PSCustomObject]$invokeInfo = if ($Hash.ContainsKey($platform)) { $Hash[$platform]; } elseif ($Hash.ContainsKey('default')) { $Hash['default']; } else { Write-Error "!!!!!! Missing platform: '$platform' (and no default available)" -ErrorAction Continue; $null; } if ($invokeInfo -and $invokeInfo.FnInfo) { if ($invokeInfo.psobject.properties.match('Positional') -and $invokeInfo.Positional) { [array]$positional = $invokeInfo.Positional; if ([scriptblock]$block = $invokeInfo.FnInfo.ScriptBlock) { $result = $block.InvokeReturnAsIs($positional); } else { Write-Error $("ScriptBlock for function: '$($invokeInfo.FnInfo.Name)', ('$platform': platform) is missing") ` -ErrorAction Continue; } } elseif ($invokeInfo.psobject.properties.match('Named') -and $invokeInfo.Named) { [hashtable]$named = $invokeInfo.Named; $result = & $invokeInfo.FnInfo.Name @named; } else { Write-Error $("Missing Positional/Named: '$($invokeInfo.FnInfo.Name)', ('$platform': platform)") ` -ErrorAction Continue; } } return $result; } function Resolve-ByPlatform { <# .NAME Resolve-ByPlatform .SYNOPSIS Given a hashtable, resolves to the value whose corresponding key matches the operating system name as returned by Get-PlatformName. .DESCRIPTION Provides a way to select data depending on the current OS as determined by Get-PlatformName. .PARAMETER Hash A hashtable object whose keys are values that can be returned by Get-PlatformName. The values can be anything. #> param( [Parameter()] [hashtable]$Hash ) $result = $null; [string]$platform = Get-PlatformName; if ($Hash.ContainsKey($platform)) { $result = $Hash[$platform]; } elseif ($Hash.ContainsKey('default')) { $result = $Hash['default']; } return $result; } function Test-IsFileSystemSafe { <# .NAME Test-IsFileSystemSafe .SYNOPSIS Checks the $Value to see if it contains any file-system un-safe characters. .DESCRIPTION Warning, this function is not comprehensive nor platform specific, but it does not intend to be. There are some characters eg /, that are are allowable under mac/linux as part of the filename but are not under windows; in this case they are considered unsafe for all platforms. This approach is taken because of the likely possibility that a file may be copied over from differing file system types. .PARAMETER Value The string value to check. .PARAMETER Value #> [OutputType([boolean])] param( [Parameter()] [string]$Value, [Parameter()] [char[]]$InvalidSet = $Loopz.InvalidCharacterSet ) return ($Value.IndexOfAny($InvalidSet) -eq -1); } function Resolve-Error ($ErrorRecord = $Error[0]) { $ErrorRecord | Format-List * -Force $ErrorRecord.InvocationInfo | Format-List * $Exception = $ErrorRecord.Exception for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException)) { "$i" * 80 $Exception | Format-List * -Force } } function get-Captures { [OutputType([hashtable])] param( [Parameter(Mandatory)] [System.Text.RegularExpressions.Match]$MatchObject ) [hashtable]$captures = @{} [System.Text.RegularExpressions.GroupCollection]$groups = $MatchObject.Groups; foreach ($key in $groups.Keys) { $captures[$key] = $groups[$key]; } return $captures; } function initialize-Signals { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] [OutputType([hashtable])] param( [Parameter()] [hashtable]$Signals = $global:Loopz.DefaultSignals, [Parameter()] [hashtable]$Overrides = $global:Loopz.OverrideSignals ) [hashtable]$result = $Signals.Clone(); [hashtable]$withOverrides = Resolve-ByPlatform -Hash $Overrides; $withOverrides.GetEnumerator() | ForEach-Object { try { $result[$_.Key] = $_.Value; } catch { Write-Error "Skipping override signal: '$($_.Key)'"; } } return $result; } function invoke-PostProcessing { param( [Parameter()] [string]$InputSource, [Parameter()] [PSCustomObject]$Rules, [Parameter()] [hashtable]$signals ) [string]$transformResult = $InputSource; [string[]]$appliedSignals = @(); [array]$iterationRules = $Rules.psobject.Members | where-Object MemberType -like 'NoteProperty'; foreach ($_r in $iterationRules) { $rule = $_r.Value; if ($rule['IsApplicable'].InvokeReturnAsIs($transformResult)) { $transformResult = $rule['Transform'].InvokeReturnAsIs($transformResult); $appliedSignals += $rule['Signal']; } } [PSCustomObject]$result = if ($appliedSignals.Count -gt 0) { [string]$indication = [string]::Empty; [string[]]$labels = @(); foreach ($name in $appliedSignals) { $indication += $signals[$name].Value; $labels += $signals[$name].Key; } $indication = "[{0}]" -f $indication; [PSCustomObject]@{ TransformResult = $transformResult Indication = $indication; Signals = $appliedSignals; Label = 'Post ({0})' -f $($labels -join ', '); Modified = $true; } } else { [PSCustomObject]@{ TransformResult = $InputSource; Modified = $false; } } $result; } function rename-FsItem { [CmdletBinding(SupportsShouldProcess)] param( [Parameter()] [System.IO.FileSystemInfo]$From, [Parameter()] [string]$To, [Parameter()] [AllowNull()] [UndoRename]$UndoOperant ) [boolean]$itemIsDirectory = ($From.Attributes -band [System.IO.FileAttributes]::Directory) -eq [System.IO.FileAttributes]::Directory; [string]$parentPath = $itemIsDirectory ? $From.Parent.FullName : $From.Directory.FullName; [string]$destinationPath = Join-Path -Path $parentPath -ChildPath $To; if (-not($PSBoundParameters.ContainsKey('WhatIf') -and $PSBoundParameters['WhatIf'])) { try { [boolean]$differByCaseOnly = $From.Name.ToLower() -eq $To.ToLower(); if ($differByCaseOnly) { # Just doing a double rename to get around the problem of not being able to rename # an item unless the case is different # [string]$tempName = $From.Name + "_"; Rename-Item -LiteralPath $From.FullName -NewName $tempName -PassThru | ` Rename-Item -NewName $To; } else { Rename-Item -LiteralPath $From.FullName -NewName $To; } if ($UndoOperant) { [PSCustomObject]$operation = [PSCustomObject]@{ Directory = $parentPath; From = $From.Name; To = $To; } Write-Debug "rename-FsItem (Undo Rename) => alert: From: '$($operation.From.Name)', To: '$($operation.To)'"; $UndoOperant.alert($operation); } $result = Get-Item -LiteralPath $destinationPath; } catch [System.IO.IOException] { $result = $null; } } else { $result = $To; } return $result; } # rename-FsItem function select-ResolvedFsItem { [OutputType([boolean])] param( [Parameter(Mandatory)] [string]$FsItem, [Parameter(Mandatory)] [AllowEmptyCollection()] [string[]]$Filter, [Parameter()] [switch]$Case ) [boolean]$liked = $false; [int]$counter = 0; do { $liked = $Case.ToBool() ` ? $FsItem -CLike $Filter[$counter] ` : $FsItem -Like $Filter[$counter]; $counter++; } while (-not($liked) -and ($counter -lt $Filter.Count)); $liked; } function test-ValidPatternArrayParam { [OutputType([boolean])] param( [Parameter(Mandatory)] [array]$Arg, [Parameter()] [switch]$AllowWildCard ) [boolean]$result = $Arg -and ($Arg.Count -gt 0) -and ($Arg.Count -lt 2) -and ` -not([string]::IsNullOrEmpty($Arg[0])) -and (($Arg.Length -eq 1) -or $Arg[1] -ne '*'); if ($result -and $Arg.Count -gt 1 -and $Arg[1] -eq '*') { $result = $AllowWildCard.ToBool(); } $result; } # The only reason why all the controller classes are implemented in the same file is because # there is a deficiency in PSScriptAnalyzer (in VSCode) which reports class references as errors # if they are not defined in the same file from where they are referenced. The only way to circumvent # this problem is to place all class related code into the same file. # enum ControllerType { ForeachCtrl = 0 TraverseCtrl = 1 } class Counter { [int]hidden $_errors = 0; [int]hidden $_value = 0; [int]hidden $_skipped = 0; [int] Increment() { return ++$this._value; } [int] Value() { return $this._value; } [int] IncrementError() { return ++$this._errors; } [int] Errors() { return $this._errors; } [int] IncrementSkipped() { return ++$this._skipped; } [int] Skipped() { return $this._skipped; } } class BaseController { [scriptblock]$_header; [scriptblock]$_summary; [hashtable]hidden $_exchange; [int]hidden $_index = 0; [boolean]$_trigger = $false; [boolean]hidden $_broken = $false; BaseController([hashtable]$exchange, [scriptblock]$header, [scriptblock]$summary) { $this._exchange = $exchange; $this._header = $header; $this._summary = $summary; } [int] RequestIndex() { if ($this._exchange.ContainsKey('LOOPZ.CONTROLLER.STACK')) { $this._exchange['LOOPZ.CONTROLLER.STACK'].Peek().Increment(); } return $this._exchange['LOOPZ.FOREACH.INDEX'] = $this._index++; } [boolean] IsBroken () { return $this._broken; } [boolean] GetTrigger() { return $this._trigger; } # I don't know how to define abstract methods in PowerShell classes, so # throwing an exception is the best thing we can do for now. # [void] SkipItem() { throw [System.Management.Automation.MethodInvocationException]::new( 'Abstract method not implemented (BaseController.SkipItem)'); } [int] Skipped() { throw [System.Management.Automation.MethodInvocationException]::new( 'Abstract method not implemented (BaseController.Skipped)'); } [void] ErrorItem() { throw [System.Management.Automation.MethodInvocationException]::new( 'Abstract method not implemented (BaseController.ErrorItem)'); } [int] Errors() { throw [System.Management.Automation.MethodInvocationException]::new( 'Abstract method not implemented (BaseController.Errors)'); } [void] ForeachBegin () { [System.Collections.Stack]$stack = $this._exchange.ContainsKey('LOOPZ.CONTROLLER.STACK') ` ? ($this._exchange['LOOPZ.CONTROLLER.STACK']) : ([System.Collections.Stack]::new()); $stack.Push([Counter]::new()); $this._exchange['LOOPZ.CONTROLLER.DEPTH'] = $stack.Count; $this._header.InvokeReturnAsIs($this._exchange); } [void] ForeachEnd () { throw [System.Management.Automation.MethodInvocationException]::new( 'Abstract method not implemented (BaseController.ForeachEnd)'); } [void] BeginSession () {} [void] EndSession () {} [void] HandleResult([PSCustomObject]$invokeResult) { # Note, the _index at this point has already been incremented and refers to the # next allocated item. # if ($invokeResult) { if ($invokeResult.psobject.properties.match('Trigger') -and $invokeResult.Trigger) { $this._exchange['LOOPZ.FOREACH.TRIGGER'] = $true; $this._trigger = $true; } if ($invokeResult.psobject.properties.match('Break') -and $invokeResult.Break) { $this._broken = $true; } if ($invokeResult.psobject.properties.match('Skipped') -and $invokeResult.Skipped) { $this.SkipItem(); } if ($invokeResult.psobject.properties.match('ErrorReason') -and ($invokeResult.ErrorReason -is [string])) { $this.ErrorItem(); } } } } class ForeachController : BaseController { [int]hidden $_skipped = 0; [int]hidden $_errors = 0; ForeachController([hashtable]$exchange, [scriptblock]$header, [scriptblock]$summary ): base($exchange, $header, $summary) { } [void] SkipItem() { $this._skipped++; } [int] Skipped() { return $this._skipped; } [void] ErrorItem() { $this._errors++; } [int] Errors() { return $this._errors; } [void] ForeachEnd () { $this._exchange['LOOPZ.FOREACH.TRIGGER'] = $this._trigger; $this._exchange['LOOPZ.FOREACH.COUNT'] = $this._index; $this._summary.InvokeReturnAsIs($this._index, $this._skipped, $this._errors, $this._trigger, $this._exchange); } } class TraverseController : BaseController { [PSCustomObject]$_session = @{ Count = 0; Errors = 0; Skipped = 0; Trigger = $false; Header = $null; Summary = $null; } TraverseController([hashtable]$exchange, [scriptblock]$header, [scriptblock]$summary, [scriptblock]$sessionHeader, [scriptblock]$sessionSummary ): base($exchange, $header, $summary) { $this._session.Header = $sessionHeader; $this._session.Summary = $sessionSummary; } [void] SkipItem() { $this._exchange['LOOPZ.CONTROLLER.STACK'].Peek().IncrementSkipped(); } [int] Skipped() { return $this._session.Skipped; } [void] ErrorItem() { $this._exchange['LOOPZ.CONTROLLER.STACK'].Peek().IncrementError(); } [int] Errors() { return $this._session.Errors; } [void] ForeachEnd () { $this._exchange['LOOPZ.FOREACH.TRIGGER'] = $this._trigger; $this._exchange['LOOPZ.FOREACH.COUNT'] = $this._index; [System.Collections.Stack]$stack = $this._exchange['LOOPZ.CONTROLLER.STACK']; [Counter]$counter = $stack.Pop(); $this._exchange['LOOPZ.CONTROLLER.DEPTH'] = $stack.Count; $this._session.Count += $counter.Value(); $this._session.Errors += $counter.Errors(); $this._session.Skipped += $counter.Skipped(); if ($this._trigger) { $this._session.Trigger = $true; } $this._summary.InvokeReturnAsIs($counter.Value(), $counter.Skipped(), $counter.Errors(), $this._trigger, $this._exchange); } [void] BeginSession () { [System.Collections.Stack]$stack = [System.Collections.Stack]::new(); # The Counter for the session represents the top-level invoke # $stack.Push([Counter]::new()); $this._exchange['LOOPZ.CONTROLLER.STACK'] = $stack; $this._exchange['LOOPZ.CONTROLLER.DEPTH'] = $stack.Count; $this._session.Header.InvokeReturnAsIs($this._exchange); } [void] EndSession () { [System.Collections.Stack]$stack = $this._exchange['LOOPZ.CONTROLLER.STACK']; # This counter value represents the top-level invoke which is not included in # a foreach sequence. # [Counter]$counter = $stack.Pop(); $this._exchange['LOOPZ.CONTROLLER.DEPTH'] = $stack.Count; if ($stack.Count -eq 0) { $this._exchange.Remove('LOOPZ.CONTROLLER.STACK'); } else { Write-Warning "!!!!!! END-SESSION; stack contains $($stack.Count) excess items"; } $this._session.Count += $counter.Value(); $this._session.Summary.InvokeReturnAsIs($this._session.Count, $this._session.Skipped, $this._session.Errors, $this._session.Trigger, $this._exchange ); } } function New-Controller { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Not a state changing function, its a factory')] [CmdletBinding(DefaultParameterSetName = 'Iterating')] [OutputType([BaseController])] param ( [Parameter(ParameterSetName = 'Iterating')] [Parameter(ParameterSetName = 'Traversing')] [ControllerType]$Type, [Parameter(ParameterSetName = 'Iterating')] [Parameter(ParameterSetName = 'Traversing')] [hashtable]$Exchange, [Parameter(ParameterSetName = 'Iterating')] [Parameter(ParameterSetName = 'Traversing')] [scriptblock]$Header, [Parameter(ParameterSetName = 'Iterating')] [Parameter(ParameterSetName = 'Traversing')] [scriptblock]$Summary, [Parameter(ParameterSetName = 'Traversing')] [scriptblock]$SessionHeader, [Parameter(ParameterSetName = 'Traversing')] [scriptblock]$SessionSummary ) $instance = $null; switch ($Type) { ForeachCtrl { $instance = [ForeachController]::new($Exchange, $Header, $Summary); break; } TraverseCtrl { $instance = [TraverseController]::new($Exchange, $Header, $Summary, $SessionHeader, $SessionSummary); break; } } $instance; } class EndAdapter { [System.IO.FileSystemInfo]$_fsInfo; [boolean]$_isDirectory; [string]$_adjustedName; EndAdapter([System.IO.FileSystemInfo]$fsInfo) { $this._fsInfo = $fsInfo; $this._isDirectory = ($fsInfo.Attributes -band [System.IO.FileAttributes]::Directory) -eq [System.IO.FileAttributes]::Directory; $this._adjustedName = $this._isDirectory ? $fsInfo.Name ` : [System.IO.Path]::GetFileNameWithoutExtension($this._fsInfo.Name); } [string] GetAdjustedName() { return $this._adjustedName; } [string] GetNameWithExtension([string]$newName) { [string]$result = ($this._isDirectory) ? $newName ` : ($newName + [System.IO.Path]::GetExtension($this._fsInfo.Name)); return $result; } [string] GetNameWithExtension([string]$newName, [string]$extension) { [string]$result = ($this._isDirectory) ? $newName ` : ($newName + $extension); return $result; } } function New-EndAdapter { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Not a state changing function, its a factory')] param( [System.IO.FileSystemInfo]$fsInfo ) return [EndAdapter]::new($fsInfo); } Export-ModuleMember -Variable LoopzHelpers, LoopzUI, Loopz Export-ModuleMember -Alias remy, greps, esc, moma, ife, Foreach-FsItem, imdt, Mirror-Directory, itd, Traverse-Directory, wife, Decorate-Foreach Export-ModuleMember -Function Rename-Many, Select-Patterns, Show-Signals, Update-CustomSignals, Format-Escape, Get-FormattedSignal, Get-PaddedLabel, Get-Signals, Initialize-ShellOperant, Move-Match, new-RegularExpression, resolve-PatternOccurrence, Select-FsItem, Select-SignalContainer, Split-Match, Update-Match, Invoke-ForeachFsItem, Invoke-MirrorDirectoryTree, Invoke-TraverseDirectory, Format-StructuredLine, Show-Header, Show-Summary, Write-HostFeItemDecorator, edit-RemoveSingleSubString, Get-InverseSubString, Get-IsLocked, get-PlatformName, Get-PsObjectField, invoke-ByPlatform, resolve-ByPlatform, Test-IsFileSystemSafe # Custom Module Initialisation # $Loopz.Signals = $(Initialize-Signals) |