Skip to content

Instantly share code, notes, and snippets.

@HeyItsGilbert
Created December 12, 2024 03:55
Show Gist options
  • Save HeyItsGilbert/c832cdab8eeee2ae385df12ce5e68dda to your computer and use it in GitHub Desktop.
Save HeyItsGilbert/c832cdab8eeee2ae385df12ce5e68dda to your computer and use it in GitHub Desktop.
Demo used during PowerShell Podecast
# Make a scriptblock
$scriptBlock = {
Write-Host "Hello World"
Get-Fighter -Chill -Name 'Jill'
Get-Fighter -Chill -Name 'Gilbert'
Get-Fighter -Name 'Andrew'
Write-Host "Fighter ready."
}
# Surprise! It's all scriptblocks!
# Look at the AST
$scriptBlock.Ast
# Walk around the block
$scriptBlock.Ast.EndBlock
# Take some statements
$scriptBlock.Ast.EndBlock.Statements
# First statement
$scriptBlock.Ast.EndBlock.Statements[0]
# Look at the elements
$scriptBlock.Ast.EndBlock.Statements[0].PipelineElements
# Command Elements
$scriptBlock.Ast.EndBlock.Statements[0].PipelineElements.CommandElements
# Find all the Commands!
$scriptBlock.Ast.FindAll(
{ "$_ -is [System.Management.Automation.Language.CommandAst]" },
$false
)
# I just want the fighters
$fighters = $scriptBlock.Ast.FindAll(
{
param($Ast)
$Ast -is [System.Management.Automation.Language.CommandAst] -and
$Ast.GetCommandName() -eq 'Get-Fighter'
},
$false
)
# Only Chill
$fighters | Where-Object {
$_.CommandElements.Extent.Text -eq '-Chill'
}
# Talk about Extent
#
$fighters | Where-Object {
$_.CommandElements.Extent.Text -eq '-Chill'
}
$actualChill = @('Jill')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment