Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 54 additions & 10 deletions src/functions/public/Core/Get-AstScript.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@

Parses the provided PowerShell script string and returns its Ast, tokens, and any parsing errors.

.EXAMPLE
Get-AstScript -Path "C:\\Scripts" -Recurse

Parses all PowerShell script files in the "C:\\Scripts" directory and its subdirectories.

.EXAMPLE
Get-AstScript -Path @("C:\\Scripts\\example.ps1", "C:\\Scripts\\example2.ps1")

Parses multiple PowerShell script files and returns their Asts.

.OUTPUTS
PSCustomObject

Expand All @@ -47,16 +57,24 @@
[outputType([System.Management.Automation.Language.ScriptBlockAst])]
[CmdletBinding()]
param (
# The path to the PowerShell script file to be parsed.
# Validate using Test-Path
# The path(s) to PowerShell script file(s) or folder(s) to be parsed.
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Path'
)]
[ValidateScript({ Test-Path -Path $_ })]
[string] $Path,
[ValidateScript({
foreach ($p in $_) {
if (-not (Test-Path -Path $p)) { return $false }
}
return $true
})]
[string[]] $Path,

# Process directories recursively
[Parameter(ParameterSetName = 'Path')]
[switch] $Recurse,

# The PowerShell script to be parsed.
[Parameter(
Expand All @@ -73,19 +91,45 @@
process {
$tokens = $null
$errors = $null

switch ($PSCmdlet.ParameterSetName) {
'Path' {
$ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$tokens, [ref]$errors)
foreach ($p in $Path) {
# Check if the path is a directory
if (Test-Path -Path $p -PathType Container) {
# Get all .ps1 files in the directory
$files = Get-ChildItem -Path $p -Filter '*.ps1' -File -Recurse:$Recurse

foreach ($file in $files) {
$ast = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$tokens, [ref]$errors)
[pscustomobject]@{
Path = $file.FullName
Ast = $ast
Tokens = $tokens
Errors = $errors
}
}
} else {
# Path is a file
$ast = [System.Management.Automation.Language.Parser]::ParseFile($p, [ref]$tokens, [ref]$errors)
[pscustomobject]@{
Path = $p
Ast = $ast
Tokens = $tokens
Errors = $errors
}
}
}
}
'Script' {
$ast = [System.Management.Automation.Language.Parser]::ParseInput($Script, [ref]$tokens, [ref]$errors)
[pscustomobject]@{
Ast = $ast
Tokens = $tokens
Errors = $errors
}
}
}
[pscustomobject]@{
Ast = $ast
Tokens = $tokens
Errors = $errors
}
}

end {}
Expand Down
131 changes: 0 additions & 131 deletions tests/AST.Tests.ps1

This file was deleted.

Loading