如何检查是否安装了PowerShell模块?

时间:2015-02-26 10:45:07

标签: powershell

要检查模块是否存在,我尝试了以下内容:

try {
    Import-Module SomeModule
    Write-Host "Module exists"
} 
catch {
    Write-Host "Module does not exist"
}

输出结果为:

Import-Module : The specified module 'SomeModule' was not loaded because no valid module file was found in any module directory.
At D:\keytalk\Software\Client\TestProjects\Export\test.ps1:2 char:5
+     Import-Module SomeModule
+     ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (SomeModule:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

Module exists

我确实收到了错误,但没有抛出任何异常,因此我们最终会看到Module exists,但SomeModule不存在。

有没有一种好的方法(最好不会产生错误)来检测系统上是否安装了PowerShell模块?

13 个答案:

答案 0 :(得分:81)

您可以使用ListAvailable的{​​{1}}选项:

Get-Module

答案 1 :(得分:22)

ListAvailable选项对我不起作用。相反,这样做:

if (-not (Get-Module -Name "<moduleNameHere>")) {
    # module is not loaded
}

或者,更简洁:

if (!(Get-Module "<moduleNameHere>")) {
    # module is not loaded
}

答案 2 :(得分:7)

只是重新审视这个,因为它是我刚刚面对的,答案中有一些不正确的东西(尽管在评论中提到过)。

第一件事。原始问题询问如何判断是否安装了PowerShell模块。我们需要谈谈安装这个词!您不安装PowerShell模块(不是以传统的方式安装软件)。

PowerShell模块可用(即它们位于PowerShell模块路径上),或者它们已导入(它们将导入到您的会话中,您可以调用包含的函数)。这是检查模块路径的方法,以防您想知道模块的存储位置:

$env:psmodulepath

我认为使用 C:\ Program Files \ WindowsPowerShell \ Modules; 变得越来越普遍,因为它可供所有用户使用,但如果你想锁定你的模块到您自己的会话,将它们包含在您的个人资料中。 C:\用户\%的用户名%\文件\ WindowsPowerShell \模块;

好的,回到两个州。

该模块是否可用(可用于原始问题中的安装)?

Get-Module -Listavailable -Name <modulename>

这会告诉您模块是否可以导入。

模块是否已导入? (我使用这个作为原始问题中“存在”一词的答案。)

Get-module -Name <modulename>

如果未导入模块,则返回空载空载,如果是,则返回模块的单行描述。与Stack Overflow一样,请在您自己的模块上尝试上述命令。

答案 3 :(得分:7)

一个模块可能处于以下状态:

  • 已导入
  • 在磁盘(或本地网络)上可用
  • 在线画廊中可用

如果您只想在PowerShell会话中使用该死的东西以供使用,则此函数可以执行该操作,或者在无法完成该操作时退出:

this

答案 4 :(得分:4)

Powershell的当前版本具有一个Get-InstalledModule function,非常适合此目的(或者至少在我的情况下如此)。

  

Get-InstalledModule

     

说明

     

Get-InstalledModule cmdlet可以获取安装在计算机上的PowerShell模块。

唯一的问题是,如果所请求的模块不存在,它将引发异常,因此我们需要适当设置ErrorAction来抑制这种情况。

if (Get-InstalledModule `
    -Name "AzureRm.Profile" `
    -MinimumVersion 5.0 ` # Optionally specify minimum version to have
    -ErrorAction SilentlyContinue) -eq $null) {

    # Install it...
}

答案 5 :(得分:3)

您可以使用#Requires语句(支持PowerShell 3.0中的模块)。

  

#Requires语句可阻止脚本运行,除非   PowerShell版本,模块,管理单元以及模块和管理单元版本   满足先决条件。

因此,在脚本顶部,只需添加#Requires -Module <ModuleName>

  

如果所需的模块不在当前会话中,PowerShell将导入它们。

     

如果无法导入模块,PowerShell将引发   终止错误。

答案 6 :(得分:2)

恕我直言,检查模块是否为:

之间存在差异

1)安装,或 2)导入:

检查是否已安装:

选项1:将Get-Module-ListAvailable参数一起使用:

If(Get-Module -ListAvailable -Name "<ModuleName>"){'Module is installed'}
Else{'Module is NOT installed'}

选项2:使用$error对象:

$error.clear()
Import-Module "<ModuleName>" -ErrorAction SilentlyContinue
If($error){Write-Host 'Module is NOT installed'}
Else{Write-Host 'Module is installed'}

检查是否导入:

Get-Module-Name参数一起使用(无论如何都可以省略默认):

if ((Get-Module -Name "<ModuleName>")) {
   Write-Host "Module is already imported (i.e. its cmdlets are available to be used.)"
}
else {
   Write-Warning "Module is NOT imported (must be installed before importing)."
}

答案 7 :(得分:2)

您可以使用Get-InstalledModule

If (-not(Get-InstalledModule SomeModule -ErrorAction silentlycontinue)) {
  Write-Host "Module does not exist"
}
Else {
  Write-Host "Module exists"
}

答案 8 :(得分:0)

  • 首先测试模块是否已加载
  • 然后导入

```

spark-submit  --class com.sundogsoftware.spark.MovieSimilarities1M  /path/to/jar/MovieSimilarities1M-assembly-1.0.jar

```

答案 9 :(得分:0)

try {
    Import-Module SomeModule
    Write-Host "Module exists"
} 
catch {
    Write-Host "Module does not exist"
}

应该指出,您的cmdlet Import-Module没有终止错误,因此不会捕获异常,因此无论您的catch语句如何,都永远不会返回您编写的新语句。

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-6

从上方:

  

“终止错误使语句无法运行。如果PowerShell无法以某种方式处理终止错误,PowerShell还将停止使用当前管道运行函数或脚本。在其他语言中,例如C#,将引用终止错误有关错误的更多信息,请参见about_Errors。“

它应该写为:

Try {
    Import-Module SomeModule -Force -Erroraction stop
    Write-Host "yep"
}
Catch {
    Write-Host "nope"
}

哪个返回:

nope

如果您确实想彻底了解,则应在运行其他功能/ cmdlet之前添加其他建议的cmdlet Get-Module -ListAvailable -NameGet-Module -Name,以便格外谨慎。如果是从psgallery或其他地方安装的,则还可以运行Find-Module cmdlet来查看是否有可用的新版本。

答案 10 :(得分:0)

来自Linux背景。我宁愿使用类似于grep的东西,因此我使用Select-String。因此,即使有人不确定完整的模块名称。他们可以提供缩写,并确定模块是否存在。

$eventsCallbacks[eventType][i](arg1, arg2, arg3) (可以是模块名称的一部分)

答案 11 :(得分:0)

当我在脚本中使用非默认模块时,将调用以下函数。除了模块名称,您还可以提供最低版本。

# See https://www.powershellgallery.com/ for module and version info
Function Install-ModuleIfNotInstalled(
    [string] [Parameter(Mandatory = $true)] $moduleName,
    [string] $minimalVersion
) {
    $module = Get-Module -Name $moduleName -ListAvailable |`
        Where-Object { $null -eq $minimalVersion -or $minimalVersion -ge $_.Version } |`
        Select-Object -Last 1
    if ($null -ne $module) {
         Write-Verbose ('Module {0} (v{1}) is available.' -f $moduleName, $module.Version)
    }
    else {
        Import-Module -Name 'PowershellGet'
        $installedModule = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue
        if ($null -ne $installedModule) {
            Write-Verbose ('Module [{0}] (v {1}) is installed.' -f $moduleName, $installedModule.Version)
        }
        if ($null -eq $installedModule -or ($null -ne $minimalVersion -and $installedModule.Version -lt $minimalVersion)) {
            Write-Verbose ('Module {0} min.vers {1}: not installed; check if nuget v2.8.5.201 or later is installed.' -f $moduleName, $minimalVersion)
            #First check if package provider NuGet is installed. Incase an older version is installed the required version is installed explicitly
            if ((Get-PackageProvider -Name NuGet -Force).Version -lt '2.8.5.201') {
                Write-Warning ('Module {0} min.vers {1}: Install nuget!' -f $moduleName, $minimalVersion)
                Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force
            }        
            $optionalArgs = New-Object -TypeName Hashtable
            if ($null -ne $minimalVersion) {
                $optionalArgs['RequiredVersion'] = $minimalVersion
            }  
            Write-Warning ('Install module {0} (version [{1}]) within scope of the current user.' -f $moduleName, $minimalVersion)
            Install-Module -Name $moduleName @optionalArgs -Scope CurrentUser -Force -Verbose
        } 
    }
}

用法示例:

Install-ModuleIfNotInstalled 'CosmosDB' '2.1.3.528'

请告诉我它是否有用(或无效)

答案 12 :(得分:0)

以下是检查是否安装了AZ模块的代码:

$checkModule = "AZ"

$Installedmodules = Get-InstalledModule

if ($Installedmodules.name -contains $checkModule)
{

    "$checkModule is installed "

}

else {

    "$checkModule is not installed"

}