Last active
August 19, 2024 19:17
-
-
Save JustinGrote/780d38d60671a522ab0bd7e0b521d677 to your computer and use it in GitHub Desktop.
Find the module names for all commands used in a script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#requires -version 7 | |
using namespace System.Management.Automation.Language | |
using namespace Collections.Generic.Queue | |
function Get-ScriptModules { | |
<# | |
.SCRIPTBLOCK | |
Given a script, returns a list of all the modules it uses. | |
#> | |
[CmdletBinding()] | |
param( | |
#The script that you wish to analyze for modules. | |
[ScriptBlock]$ScriptBlock | |
) | |
$commands = $ScriptBlock.Ast.FindAll( | |
<# predicate #> {$args[0] -is [CommandAst]}, | |
<# searchNestedScriptBlocks #> $true | |
) | |
if ($commands.count -eq 0) { | |
Write-Error "No commands found in script." | |
return | |
} | |
$commands | |
| ForEach-Object {$PSItem.CommandElements[0].ToString()} | |
| Select-Object -Unique | |
| ForEach-Object -Parallel { | |
$commandName = $PSItem | |
$foundCommands = Get-Command -Name $commandName -ErrorAction Stop | |
$foundCommands ??= Find-Command -Name $commandName -ErrorAction Stop | |
if ($foundCommands.count -eq 0) { | |
Write-Error "$commandName`: Could not a find module for command. Check spelling and try again." | |
return | |
} | |
if ($foundCommands.count -gt 1) { | |
Write-Warning "$commandName`: Ambiguity - Found multiple modules - $($foundCommands.ModuleName -join ', ')" | |
} | |
[PSCustomObject]@{ | |
CommandName = $commandName | |
Module = $foundCommands.ModuleName | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment