【问题标题】:Is there a way to find every single modules which will be needed in script?有没有办法找到脚本中需要的每个模块?
【发布时间】:2021-02-22 20:04:31
【问题描述】:

我想使用一种分析器,它会在我在远程机器上运行它之前通过脚本安装/导入所有需要的模块(它无法拥有它)......

有什么想法吗?

编辑

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

在我将脚本发送到远程 PC 之前,我想要在“开始”部分写下正确的导入;为了确保它能够完美运行,你跟着?...

是否有某种第三方应用程序可以扫描我的脚本并为我提供所有需要的模块?

【问题讨论】:

  • 您应该已经知道脚本需要哪些模块并内置检查
  • 我所知道的是,我的脚本在远程 PC 上完美运行...谢谢您的建设性意见
  • 不客气。也感谢您提出的好问题!
  • 所以我的意思是,当您编写脚本/模块时,您应该提前知道还需要哪些其他模块。然后,您可以使用#Requires 标志等标记您的脚本/模块。 docs.microsoft.com/en-us/powershell/module/…
  • 我理解你的意思,但是,尽管听起来很愚蠢,如果我的问题不是那么好,那真的是在指出我的需求......

标签: powershell scripting powershell-module


【解决方案1】:

您可以这样做来帮助查找使用的命令及其源/模块名称。很粗糙,只是想给出一个想法。

$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

【讨论】:

  • 我知道它被要求避免这种评论......但它有效!实际上很好!!!..你太棒了!谢谢!!!
【解决方案2】:

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2011-12-12
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    相关资源
    最近更新 更多