powershellscriptingpowershell-module

Is there a way to find every single modules which will be needed in script?


I'd like to use a kinda analyzer which will install/import all the needed modules by the script before I run it on distant machine (which could not have it) ......

any idea ?

EDIT

Here's the case : I'm on my dev machine, I'ved already installed lots of modules of all kind (dhcp, ntfs, remoting, register, etc.) When I finally got my script (which is a function) to work, I can't be sure of what modules are used....

What I want is to write down, in the 'begin' section, the correct imports before I send my script on remote PCs; to be sure it's gonna run perfectly, you follow ?...

Is there a kinda a third party appplication which can scan my script and give me all needed modules ?


Solution

  • You could do something like this to get help in finding commands used and their source/module names. It's very unpolished, just trying to give the idea.

    $scriptblock = {
        Write-Host "Nothing here"
        $files = Get-ChildItem c:\temp
        Get-ADUser someuser
        Test-NetConnection www.google.com
    }
    
    # Uncomment following lines and enter the path to your script file
    # $scriptFile = "Path\to\some\scriptfile"
    # $scriptblock = [scriptblock]::Create((Get-Content -raw -Path $scriptFile))
    
    $ast = $scriptblock.Ast
    
    $commands = $ast.FindAll( { $args[0] -is [System.Management.Automation.Language.CommandAst] }, $true)
    $commandText = foreach ($command in $commands) {
        $command.CommandElements[0].Extent.Text
    }
    
    $commandText | 
        Select-Object -Unique | 
        Sort-Object |
        Select-Object @{
            Label      = "CommandName"
            Expression = { $_ } 
        },   
        @{
            Label      = "Source"
            Expression = { 
                (Get-Command $_).Source
            } 
        }
    

    Output

    CommandName        Source
    -----------        ------
    Get-ADUser         ActiveDirectory
    Get-ChildItem      Microsoft.PowerShell.Management
    Test-NetConnection NetTCPIP
    Write-Host         Microsoft.PowerShell.Utility