Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Last active February 16, 2024 15:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinGrote/780d38d60671a522ab0bd7e0b521d677 to your computer and use it in GitHub Desktop.
Save JustinGrote/780d38d60671a522ab0bd7e0b521d677 to your computer and use it in GitHub Desktop.
Find the module names for all commands used in a script
#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