PipelineBinding.psm1
|
function Find-PipelineBindingType { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)] $Cmdlet1, [Parameter(Mandatory=$true)] $Cmdlet2 ) foreach ($Cmdlet in @($Cmdlet1,$Cmdlet2)) { Write-Verbose "$Cmdlet1, $Cmdlet2, $Cmdlet" $CmdletTest = Test-Cmdlet -Cmdlet $Cmdlet if ($CmdletTest.Exists -eq $false) { throw "The cmdlet $Cmdlet does not exist" } } $CmdletParams = Get-CmdletParam -Cmdlet $Cmdlet2 $CmdletObject = Get-CmdletOutputType -Cmdlet $Cmdlet1 $CmdletProperties = Get-CmdletOutputProperty -Cmdlet $Cmdlet1 $TestPipeByVal = Test-PipelineByVal -Cmdlet1 $Cmdlet1 -Cmdlet2 $Cmdlet2 if ($TestPipeByVal.ByValPipe -eq $true) { Show-PipelineByVal -TestResultByVal $TestPipeByVal } else { $TestPipeByPN = Test-PipelineByPN -Cmdlet1 $Cmdlet1 -Cmdlet2 $Cmdlet2 if ($TestPipeByPN.ByPNPipe -eq $true) { Show-PipelineByPN -TestResultByPN $TestPipeByPN } else { throw 'No Pipeline Binding is possible' } } } function Test-Cmdlet { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)] [string]$Cmdlet ) $FunctionOutputHash = [ordered]@{ # Assume the Cmdlet exists Cmdlet = $Cmdlet Exists = $true } $ExtractedCmdlet = ($Cmdlet -split ' ')[0] try {Get-command -Name $ExtractedCmdlet -ErrorAction stop *> $null} catch {$FunctionOutputHash.Exists = $false} # If Cmdlet does not exist change assumed state to false return [PSCustomObject]$FunctionOutputHash } function Get-CmdletParam { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)] [string]$Cmdlet ) $Params=(Get-Command $Cmdlet).Parameters -as [hashtable] [string[]]$Keys = $Params.Keys foreach ($Key in $Params.Keys) { $Value = $Params[$key] $FunctionOutputHash = [ordered]@{ Name = $Value.Name FullTypeName = ($Value.ParameterType -replace '\[|\]','') -as [string] Type = ($Value.ParameterType.Name -replace '\[|\]','') -as [string] ByValue = $Value.Attributes.ValueFromPipeLine ByPropertyName = $Value.Attributes.ValueFromPipeLineByPropertyName ShowParamType = '-' + $($Value.Name) + ' [' + $($Value.ParameterType.Name -replace '\[|\]','') + ']' } if ($FunctionOutputHash.ByValue -eq $true -or $FunctionOutputHash.ByPropertyName -eq $true) { [PSCustomObject]$FunctionOutputHash # Only return a result if the param accepts pipeline input } } } function Get-CmdletOutputType { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)] [string]$Cmdlet ) $ResultTypes = Invoke-Expression $Cmdlet | Get-Member | Select-Object -Property TypeName -Unique foreach ($ResultType in $ResultTypes) { $FunctionOutputHash = @{ Cmdlet = $Cmdlet CmdletOutputFullType = $ResultType.TypeName -as [string] CmdletOutputType = (($ResultType.TypeName -Split'\.')[-1]) -as [string] } [PSCustomObject]$FunctionOutputHash } } function Get-CmdletOutputProperty { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)] [string]$Cmdlet ) $ResultTypes = Invoke-Expression $Cmdlet | Get-Member | Select-Object -Property TypeName -Unique foreach ($ResultType in $ResultTypes) { $CmdletProps = Invoke-Expression $Cmdlet | Get-Member -MemberType Properties $CmdletProps | Select-Object -Property Name, @{n='ObjectType'; e={$ResultType.TypeName}}, @{ n='PropertyType' e={ if ($_.MemberType -ne 'AliasProperty') { $FullPropName = ($_.Definition -split ' ')[0] -replace '\[|\]','' } else { $AliasName = ($_.Definition -split ' ')[-1] -replace '\[|\]','' $FullPropName = (($CmdletProps | Where-Object {$_.name -eq $AliasName}) -split ' ')[0] -replace '\[|\]','' } (($FullPropName -split '\.')[-1] -replace '[^a-z]','') -as [string] } } | select-object -Property *,@{ n='ShowPropType' e={$TypeName = ($_.PropertyType -split '\.')[-1] -replace '[^a-z]','' ;'[' + $TypeName + ']' + $_.Name} } } # foreach loop end } function Test-PipelineByVal { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)] $Cmdlet1, [Parameter(Mandatory=$true)] $Cmdlet2 ) $CmdletOutputTypes = Get-CmdletOutputType -Cmdlet $Cmdlet1 $CmdletParams = Get-CmdletParam -Cmdlet $Cmdlet2 | Where-Object {$_.ByValue -eq $true} foreach ($CmdletOutputType in $CmdletOutputTypes) { $ByValParamMatch = $CmdletParams | Where-Object {$_.FullTypeName -eq $CmdletOutputType.CmdletOutputFullType} if ($ByValParamMatch) { $HashTab = [ordered]@{ ByValPipe = $true Cmdlet1 = $Cmdlet1 Cmdlet2 = $Cmdlet2 ParamMatch = $ByValParamMatch AllByValParams = $CmdletParams OutputType = $CmdletOutputType } } else { $HashTab = [ordered]@{ ByValPipe = $false Cmdlet1 = $Cmdlet1 Cmdlet2 = $Cmdlet2 ParamMatch = $null AllByValParams = $CmdletParams OutputType = $CmdletOutputType } } [PSCustomObject]$HashTab } } function Test-PipelineByPN { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)] $Cmdlet1, [Parameter(Mandatory=$true)] $Cmdlet2 ) $CmdletProps = Get-CmdletOutputProperty -Cmdlet $Cmdlet1 $CmdletParams = Get-CmdletParam -Cmdlet $Cmdlet2 | Where-Object {$_.ByPropertyName -eq $true} foreach ($ByPNParam in $CmdletParams) { $MatchingProp = $CmdletProps | Where-Object { $_.Name -eq $ByPNParam.Name -and $_.PropertyType -eq $ByPNParam.Type } if ($MatchingProp) { $HashTab = [ordered]@{ Cmdlet1 = $Cmdlet1 Cmdlet2 = $Cmdlet2 ByPNPipe = $true PropMatch = $MatchingProp ParamMatch = $ByPNParam AllProperties = $CmdletProps } } else { $HashTab = [ordered]@{ Cmdlet1 = $Cmdlet1 Cmdlet2 = $Cmdlet2 ByPNPipe = $false PropMatch = $MatchingProp ParamMatch = $null AllProperties = $CmdletProps } } [PSCustomObject]$HashTab } } function Show-PipelineByVal { [cmdletbinding()] Param ( $TestResultByVal ) $keyGap = 50 $Cmdlet1Length = $TestResultByVal.Cmdlet1.Length $Cmdlet2Length = $TestResultByVal.Cmdlet2.Length $OutputTypeLength = $TestResultByVal.OutputType.CmdletOutputType.Length $CommandGap = ' ' * $keyGap $GuideGap = ' ' * ($Cmdlet1Length + $keyGap - 1) $MappingGap = '-' * ($keyGap - $OutputTypeLength - 5 ) + '>' $HeaderGap = ' ' * [int]((($keyGap + $Cmdlet1Length) / 2) - 4) Clear-Host Write-Host Write-Host -ForegroundColor Cyan "Pipeline ByValue" Write-Host -ForegroundColor Cyan "----------------" Write-Host -ForegroundColor Green -NoNewline "$($TestResultByVal.Cmdlet1) " Write-Host -NoNewline "$CommandGap" Write-Host -ForegroundColor Green " $($TestResultByVal.Cmdlet2)" write-host " | $GuideGap ^" write-host " | $GuideGap |" write-host " V $GuideGap |" foreach ($Param in $TestResultByVal.AllByValParams) { $BadMapping = $false Write-Host -NoNewline " Object Type: " Write-Host -ForegroundColor Yellow -NoNewline "$($TestResultByVal.OutputType.CmdletOutputType) " if ($TestResultByVal.OutputType.CmdletOutputType -eq $Param.Type) { Write-Host -NoNewline $MappingGap } else { Write-Host -NoNewline -ForegroundColor Red ($MappingGap -replace '->','>X') $BadMapping = $true } if ($BadMapping -eq $true) {$ParamColor = 'Red'} else {$ParamColor = 'Yellow'} Write-Host -ForegroundColor $ParamColor " $($Param.ShowParamType)" } Write-Host Write-Host } function Show-PipelineByPN { [cmdletbinding()] Param ( $TestResultByPN ) $KeyGap = 50 $Cmdlet1Length = $TestResultByPN.Cmdlet1.Length $Cmdlet2Length = $TestResultByPN.Cmdlet2.Length $CommandGapLength = $KeyGap - $Cmdlet1Length + 5 $CommandGap = ' ' * $CommandGapLength $GuideGap = ' ' * ($CommandGapLength + 10) $MappingGap = ('-' * ($CommandGapLength - $Cmdlet1Length - 12 )) + '>' $Cmdlet1 = $TestResultByPN.Cmdlet1 | Select-Object -Unique $Cmdlet2 = $TestResultByPN.Cmdlet2 | Select-Object -Unique Clear-Host Write-Host Write-Host -ForegroundColor Cyan "Pipeline ByPropertyName" Write-Host -ForegroundColor Cyan "-----------------------" Write-Host -ForegroundColor Green -NoNewline "$Cmdlet1 " Write-Host -NoNewline "$CommandGap" Write-Host -ForegroundColor Green " $Cmdlet2" write-host " | $GuideGap ^" write-host " | $GuideGap |" write-host " V $GuideGap |" foreach ($PropToParamMatch in $TestResultByPN) { if ($TestResultByPN.ByPNPipe -eq $true -and $PropToParamMatch.PropMatch.ShowPropType) { $MapGuide = ('-' * ($CommandGapLength - $($TestResultByPN.ParamMatch.ShowParamType.length))) + '>' Write-Host -NoNewline ' Property: ' Write-Host -ForegroundColor Yellow -NoNewline "$($PropToParamMatch.PropMatch.ShowPropType) " Write-Host -NoNewline "$MapGuide" Write-Host -ForegroundColor Yellow " $($TestResultByPN.ParamMatch.ShowParamType)" } } Write-Debug -Message 'non props' foreach ($NonMatchingPropery in ($TestResultByPN.AllProperties | Where-Object {$_.Name -notin $TestResultByPN.PropMatch.Name})) { Write-Host -NoNewline ' Property: ' Write-Host -ForegroundColor Yellow -NoNewline "$($NonMatchingPropery.ShowPropType) " $NonMapGuide = ('-' * ($CommandGapLength - $($NonMatchingPropery.ShowPropType.length) - 3)) + '>X' #('-' * ($KeyGap - $($NonMatchingPropery.ShowPropType.length))) + '>X' Write-Host -NoNewline -ForegroundColor Red "$NonMapGuide" Write-Host -ForegroundColor Red " No-Matching-Parameter" } Write-Host Write-Host } function Get-CommandParameterPipeline { [CmdletBinding()] Param( [Parameter(Mandatory=$true, Position=0)] [string]$CommandName ) try { # Retrieve the command metadata $CmdInfo = Get-Command -Name $CommandName -ErrorAction Stop } Catch { Write-Warning "The Command $CommandName is not a valid PowerShell cmdlet" return } # Iterate through the Values of the Parameters dictionary foreach ($CmdParam in $CmdInfo.Parameters.Values) { $ByValue = $false $ByPropertyName = $false # Inspect the attributes of each parameter foreach ($Attribute in $CmdParam.Attributes) { # We only care about the ParameterAttribute class if ($Attribute -is [System.Management.Automation.ParameterAttribute]) { if ($Attribute.ValueFromPipeline) { $byValue = $true } if ($Attribute.ValueFromPipelineByPropertyName) { $ByPropertyName = $true } } } # Output a custom object only if at least one pipeline method is supported if ($ByValue -or $ByPropertyName) { [PSCustomObject][ordered]@{ Cmdlet = $CommandName ParameterName = $CmdParam.Name ParameterType = $CmdParam.ParameterType.Name ByValue = $ByValue ByPropertyName = $ByPropertyName } } } } function Show-PipelineAnalysis { [CmdletBinding()] param( [string]$Command1 = '', [string]$Command2 = '' ) Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing # Create Main Form $form = New-Object System.Windows.Forms.Form $form.Text = "PowerShell Pipeline Analyser" $form.Size = New-Object System.Drawing.Size(860, 720) $form.StartPosition = "CenterScreen" $form.FormBorderStyle = 'FixedDialog' $form.MaximizeBox = $false $form.TopMost = $true # Increased Font settings $standardFont = New-Object System.Drawing.Font("Segoe UI", 11) $monoFont = New-Object System.Drawing.Font("Consolas", 11) $boldMonoFont = New-Object System.Drawing.Font("Consolas", 11, [System.Drawing.FontStyle]::Bold) # Label 1 $lblCmd1 = New-Object System.Windows.Forms.Label $lblCmd1.Text = "Command 1 (e.g. Get-Service):" $lblCmd1.Location = New-Object System.Drawing.Point(20, 20) $lblCmd1.Size = New-Object System.Drawing.Size(320, 25) $lblCmd1.Font = $standardFont $form.Controls.Add($lblCmd1) # TextBox 1 $txtCmd1 = New-Object System.Windows.Forms.TextBox $txtCmd1.Location = New-Object System.Drawing.Point(20, 45) $txtCmd1.Size = New-Object System.Drawing.Size(320, 25) $txtCmd1.Font = $monoFont $txtCmd1.Text = $Command1 $form.Controls.Add($txtCmd1) # Label Pipeline Pipe $lblPipe = New-Object System.Windows.Forms.Label $lblPipe.Text = "|" $lblPipe.Location = New-Object System.Drawing.Point(350, 45) $lblPipe.Size = New-Object System.Drawing.Size(20, 25) $lblPipe.Font = New-Object System.Drawing.Font("Consolas", 14, [System.Drawing.FontStyle]::Bold) $form.Controls.Add($lblPipe) # Label 2 $lblCmd2 = New-Object System.Windows.Forms.Label $lblCmd2.Text = "Command 2 (e.g. Stop-Service):" $lblCmd2.Location = New-Object System.Drawing.Point(380, 20) $lblCmd2.Size = New-Object System.Drawing.Size(320, 25) $lblCmd2.Font = $standardFont $form.Controls.Add($lblCmd2) # TextBox 2 $txtCmd2 = New-Object System.Windows.Forms.TextBox $txtCmd2.Location = New-Object System.Drawing.Point(380, 45) $txtCmd2.Size = New-Object System.Drawing.Size(320, 25) $txtCmd2.Font = $monoFont $txtCmd2.Text = $Command2 $form.Controls.Add($txtCmd2) # Analyse Button $btnAnalyse = New-Object System.Windows.Forms.Button $btnAnalyse.Text = "Analyse" $btnAnalyse.Location = New-Object System.Drawing.Point(715, 43) $btnAnalyse.Size = New-Object System.Drawing.Size(115, 30) $btnAnalyse.Font = $standardFont $form.Controls.Add($btnAnalyse) # Output RichTextBox $rtbOutput = New-Object System.Windows.Forms.RichTextBox $rtbOutput.Location = New-Object System.Drawing.Point(20, 90) $rtbOutput.Size = New-Object System.Drawing.Size(810, 560) $rtbOutput.Font = $boldMonoFont $rtbOutput.ReadOnly = $true $rtbOutput.BackColor = [System.Drawing.Color]::White $form.Controls.Add($rtbOutput) # Core Logic Function $btnAnalyse.Add_Click({ $rtbOutput.Clear() # Helper to write coloured text and background to the RichTextBox $WriteColor = { param( [string]$Text, [System.Drawing.Color]$Color, [System.Drawing.Color]$BgColor = [System.Drawing.Color]::White ) $rtbOutput.SelectionStart = $rtbOutput.TextLength $rtbOutput.SelectionLength = 0 $rtbOutput.SelectionColor = $Color $rtbOutput.SelectionBackColor = $BgColor $rtbOutput.AppendText($Text) $rtbOutput.SelectionColor = [System.Drawing.Color]::Black # Reset to default $rtbOutput.SelectionBackColor = [System.Drawing.Color]::White # Reset to default } # Extract base command names (ignoring arguments if typed) $cmd1Name = ($txtCmd1.Text.Trim() -split '\s+')[0] $cmd2Name = ($txtCmd2.Text.Trim() -split '\s+')[0] if ([string]::IsNullOrWhiteSpace($cmd1Name) -or [string]::IsNullOrWhiteSpace($cmd2Name)) { &$WriteColor "Please enter two valid PowerShell commands.`n" ([System.Drawing.Color]::Red) return } $rtbOutput.AppendText("Analysing Pipeline: $cmd1Name | $cmd2Name`n") $rtbOutput.AppendText("==============================================================`n`n") $cmd1 = Get-Command $cmd1Name -ErrorAction SilentlyContinue $cmd2 = Get-Command $cmd2Name -ErrorAction SilentlyContinue if (-not $cmd1) { &$WriteColor "Error: Could not find command '$cmd1Name'.`n" ([System.Drawing.Color]::Red); return } if (-not $cmd2) { &$WriteColor "Error: Could not find command '$cmd2Name'.`n" ([System.Drawing.Color]::Red); return } # 1. Determine Output Types of Command 1 $outTypes = @() if ($cmd1.OutputType) { $outTypes = $cmd1.OutputType | Select-Object -ExpandProperty Name } if ($outTypes.Count -eq 0) { $outTypes = @("System.Object (Unknown)") } $rtbOutput.AppendText("[$($cmd1.Name)] Output Types:`n") foreach ($type in $outTypes) { $rtbOutput.AppendText(" - $type`n") } $rtbOutput.AppendText("`n") # 2. Extract Pipeline Parameters of Command 2 (Fixed Duplicate Issue) $pipeValueParams = @() $pipePropParams = @() foreach ($param in $cmd2.Parameters.Values) { $addedValue = $false $addedProp = $false foreach ($attr in $param.Attributes) { if ($attr.TypeId.Name -eq 'ParameterAttribute') { if ($attr.ValueFromPipeline -and -not $addedValue) { $pipeValueParams += $param $addedValue = $true } if ($attr.ValueFromPipelineByPropertyName -and -not $addedProp) { $pipePropParams += $param $addedProp = $true } } } } $byValueSuccess = $false # 3. Analyse ByValue Binding &$WriteColor "--- PHASE 1: ByValue Binding Candidates ---`n" ([System.Drawing.Color]::Black) ([System.Drawing.Color]::Yellow) if ($pipeValueParams.Count -eq 0) { $rtbOutput.AppendText("No parameters in $($cmd2.Name) accept pipeline input ByValue.`n") } else { foreach ($p in $pipeValueParams) { $expectedFullType = $p.ParameterType.FullName if (-not $expectedFullType) { $expectedFullType = $p.ParameterType.Name } # Strip array brackets to match the unrolled objects in the pipeline $expectedBaseType = $expectedFullType -replace '\[\]$', '' $rtbOutput.AppendText("`nCmd 2 Parameter: -$($p.Name) ") &$WriteColor "[Accepts Type: $expectedFullType]`n" ([System.Drawing.Color]::Black) ([System.Drawing.Color]::Cyan) $matched = $false foreach ($ot in $outTypes) { $outBaseType = $ot -replace '\[\]$', '' # Compare short names to account for namespace variations $outShortName = ($outBaseType -split '\.')[-1] $expectedShortName = ($expectedBaseType -split '\.')[-1] if ($outBaseType -eq $expectedBaseType -or $outShortName -eq $expectedShortName -or $expectedBaseType -eq 'System.Object' -or $expectedBaseType -eq 'System.Management.Automation.PSObject') { &$WriteColor " -> MATCH with Output Type: $ot`n" ([System.Drawing.Color]::Black) ([System.Drawing.Color]::LightGreen) $matched = $true $byValueSuccess = $true } } if (-not $matched) { &$WriteColor " -> No direct type match found.`n" ([System.Drawing.Color]::Red) } } } $rtbOutput.AppendText("`n") # 4. Analyse ByPropertyName Binding &$WriteColor "--- PHASE 2: ByPropertyName Binding Candidates ---`n" ([System.Drawing.Color]::Black) ([System.Drawing.Color]::Yellow) if ($byValueSuccess) { $rtbOutput.AppendText("SKIPPED: A successful ByValue match was found in Phase 1.`n") $rtbOutput.AppendText("PowerShell satisfies the pipeline binding ByValue first and will stop evaluating ByPropertyName for this object.`n") } elseif ($pipePropParams.Count -eq 0) { $rtbOutput.AppendText("No parameters in $($cmd2.Name) accept pipeline input ByPropertyName.`n") } else { # Reflect properties from Command 1's unrolled output types (combining .NET and ETS into a Hashtable for type tracking) $cmd1Props = @{} foreach ($ot in $outTypes) { if ($ot -ne "System.Object (Unknown)") { $cleanOutType = $ot -replace '\[\]$', '' # 4a. Get Native .NET Properties and their types $typeObj = $null try { $typeObj = [type]$cleanOutType } catch { # Fallback: attempt to dynamically load standard PS assemblies if missing $parts = $cleanOutType.Split('.') if ($parts.Count -gt 1) { $ns = $parts[0..($parts.Count-2)] -join '.' [System.Reflection.Assembly]::LoadWithPartialName($ns) | Out-Null try { $typeObj = [type]$cleanOutType } catch { } } } if ($typeObj) { try { $typeObj.GetProperties() | ForEach-Object { if (-not $cmd1Props.ContainsKey($_.Name)) { $cmd1Props[$_.Name] = $_.PropertyType.Name } } } catch { } } # 4b. Get PowerShell ETS Properties (AliasProperty, NoteProperty, etc.) try { $typeDataList = @(Get-TypeData -TypeName $cleanOutType -ErrorAction SilentlyContinue) if (-not $typeDataList) { $typeDataList = @(Get-TypeData | Where-Object { $_.TypeName -ieq $cleanOutType }) } foreach ($typeData in $typeDataList) { if ($typeData.Members) { foreach ($memberName in $typeData.Members.Keys) { if (-not $cmd1Props.ContainsKey($memberName)) { $member = $typeData.Members[$memberName] $memTypeName = $member.GetType().Name if ($memTypeName -eq 'AliasPropertyData') { $refName = $member.ReferencedMemberName if ($cmd1Props.ContainsKey($refName)) { $cmd1Props[$memberName] = $cmd1Props[$refName] } else { $cmd1Props[$memberName] = "AliasProperty" } } else { # Strip "Data" from the end (e.g. NotePropertyData -> NoteProperty) $cmd1Props[$memberName] = $memTypeName -replace 'Data$','' } } } } } } catch { } } } foreach ($p in $pipePropParams) { $expectedType = $p.ParameterType.Name $aliases = if ($p.Aliases) { $p.Aliases -join ', ' } else { "None" } $rtbOutput.AppendText("`nCmd 2 Parameter: -$($p.Name) ") &$WriteColor "[Type: $expectedType] (Aliases: $aliases)`n" ([System.Drawing.Color]::Black) ([System.Drawing.Color]::Cyan) $matchedProps = @() foreach ($propName in $cmd1Props.Keys) { if ($propName -eq $p.Name -or $p.Aliases -contains $propName) { $propType = $cmd1Props[$propName] $matchedProps += "$propName [$propType]" } } if ($matchedProps) { &$WriteColor " -> MATCHED Cmd1 Properties: $($matchedProps -join ', ')`n" ([System.Drawing.Color]::Black) ([System.Drawing.Color]::LightGreen) } else { if ($cmd1Props.Count -gt 0) { &$WriteColor " -> No matching properties found in declared Output Types.`n" ([System.Drawing.Color]::Red) } else { &$WriteColor " -> Output type properties unknown. Will bind if the incoming object contains a property named '$($p.Name)' or an alias.`n" ([System.Drawing.Color]::Red) } } } } }) # Show the form $form.ShowDialog() | Out-Null $form.Dispose() } |