有没有办法找到脚本中需要的每个模块?

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

我想使用一种分析器,它会 install/import 在我 运行 远程机器(没有它)之前通过脚本 install/import 所有需要的模块.... ..

有什么想法吗?

编辑

情况如下: 我在我的开发机器上,我已经安装了很多各种模块(dhcp、ntfs、远程处理、注册等) 当我终于让我的脚本(这是一个函数)开始工作时,我无法确定使用了哪些模块....

我想要的是在 'begin' 部分写下我在远程 PC 上发送脚本之前的正确导入;为了确保它 运行 完美,你遵循 ?...

有没有第三方应用程序可以扫描我的脚本并给我所有需要的模块?

是的,例如,您可以通过尝试按如下方式导入模块来测试该模块是否存在于该特定机器上

Try {
   Import-Module dbaclone -ErrorAction stop
   #ErrorAction required as failing to import is not a terminating action
} Catch {
   Write-Verbose -Verbose "Failed to find dbaclone module - installing"
   Install-Module dbaclone -AllowClobber -Force 
   Write-Verbose -Verbose "Installed!"
   Import-Module dbaclone
}

您可以执行类似的操作来帮助查找使用的命令及其 source/module 名称。很粗糙,只是想表达一下想法。

$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
        } 
    }

输出

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