Components/PS.Util.AST/Public/Get-PSUtilAST.ps1
|
function Get-PSUtilAST { [CmdletBinding( DefaultParameterSetName = 'File' )] Param( [Parameter( ParameterSetName = 'File', Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName )] [Alias('FullName')] [String] $FilePath, [Parameter( ParameterSetName = 'Code', Mandatory, ValueFromPipeline )] [string] $Code, [Parameter(ParameterSetName = 'Code')] [ArgumentCompleter({ Param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) $collection = [PSObject].Assembly.GetTypes().Where{$_.Name.EndsWith('Ast')}.Name | Sort-Object | Where-Object { $_ -like "$wordToComplete*" } $collection | Foreach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, "ParameterValue", $_) } })] $AstType = '*', [Switch] $NoRecursion ) BEGIN { $predicate = { param($astObject) $astObject.GetType().Name -like $AstType } } PROCESS { $errors = $null $ast = switch ($PSCmdlet.ParameterSetName) { 'File' { [System.Management.Automation.Language.Parser]::ParseFile( $FilePath, [ref]$null, [ref]$errors) } 'Code' { [System.Management.Automation.Language.Parser]::ParseInput($Code, [ref]$null, [ref]$errors) } } if ($errors) { throw [System.InvalidCastException]::new("Submitted text could not be converted to PowerShell because it contains syntax errors: $($errors | Out-String)") } $ast.FindAll($predicate, !$NoRecursion) | Add-Member -MemberType ScriptProperty -Name Type -Value { $this.GetType().Name } -PassThru -Force } } |