[powershell] 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 모듈이 시스템에 설치되어 있는지 감지하는 좋은 방법 (가급적이면 오류를 생성하지 않음)이 있습니까?



답변

다음 ListAvailable옵션을 사용할 수 있습니다 Get-Module.

if (Get-Module -ListAvailable -Name SomeModule) {
    Write-Host "Module exists"
}
else {
    Write-Host "Module does not exist"
}


답변

ListAvailable 옵션이 작동하지 않습니다. 대신 다음을 수행합니다.

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

또는 더 간결하게 :

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


답변

모듈의 상태는 다음과 같습니다.

  • 수입
  • 디스크 (또는 로컬 네트워크)에서 사용 가능
  • 온라인 갤러리에서 사용 가능

PowerShell 세션에서 사용할 수있는 기능을 사용하려면 다음과 같은 기능을 사용하거나 수행 할 수없는 경우 종료합니다.

function Load-Module ($m) {

    # If module is imported say that and do nothing
    if (Get-Module | Where-Object {$_.Name -eq $m}) {
        write-host "Module $m is already imported."
    }
    else {

        # If module is not imported, but available on disk then import
        if (Get-Module -ListAvailable | Where-Object {$_.Name -eq $m}) {
            Import-Module $m -Verbose
        }
        else {

            # If module is not imported, not available on disk, but is in online gallery then install and import
            if (Find-Module -Name $m | Where-Object {$_.Name -eq $m}) {
                Install-Module -Name $m -Force -Verbose -Scope CurrentUser
                Import-Module $m -Verbose
            }
            else {

                # If module is not imported, not available and not in online gallery then abort
                write-host "Module $m not imported, not available and not in online gallery, exiting."
                EXIT 1
            }
        }
    }
}

Load-Module "ModuleName" # Use "PoshRSJob" to test it out


답변

현재 버전의 Powershell에는 이 목적에 잘 맞는 Get-InstalledModule기능 이 있습니다 (또는 적어도 제 경우에는 그랬습니다).

Get-InstalledModule

기술

Get-InstalledModulecmdlet은 컴퓨터에 설치되어 PowerShell을 모듈을 가져옵니다.

유일한 문제는 요청 된 모듈이 존재하지 않으면 예외가 발생한다는 것입니다. 따라서이 경우 ErrorAction를 억제하도록 적절하게 설정해야합니다 .

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

    # Install it...
}


답변

방금 만난 일이고 답변에 잘못된 내용이 있기 때문에 이것을 다시 방문하십시오 (주석에 언급되었지만).

그래도 먼저. 원래 질문은 PowerShell 모듈이 설치되었는지 확인하는 방법을 묻습니다. 설치된 단어에 대해 이야기해야합니다! PowerShell 모듈을 설치하지 않습니다 (어쨌든 소프트웨어를 설치하는 기존 방식이 아님).

PowerShell 모듈은 사용 가능하거나 (즉, PowerShell 모듈 경로에 있음) 가져 오거나 (세션으로 가져 와서 포함 된 함수를 호출 할 수 있음). 모듈을 저장할 위치를 알고 싶은 경우 모듈 경로를 확인하는 방법입니다.

$env:psmodulepath

C : \ Program Files \ WindowsPowerShell \ Modules 를 사용하는 것이 보편화되고 있다고 생각합니다 . 모든 사용자가 사용할 수 있기 때문에 더 자주 사용되지만 모듈을 자신의 세션에 잠 그려면 프로필에 포함하십시오. C : \ Users \ % username % \ Documents \ WindowsPowerShell \ Modules;

좋습니다. 두 주로 돌아갑니다.

모듈을 사용할 수 있습니까 (원래 질문에서 설치됨을 의미하는 사용 가능)?

Get-Module -Listavailable -Name <modulename>

이는 모듈을 가져올 수 있는지 여부를 알려줍니다.

모듈을 가져 왔습니까? (원래 질문에서 ‘존재한다’라는 단어에 대한 답으로 이것을 사용하고 있습니다.)

Get-module -Name <modulename>

이는 모듈을 가져 오지 않은 경우 아무것도없는 빈로드를 반환하고있는 경우 모듈에 대한 한 줄 설명을 반환합니다. Stack Overflow에서와 마찬가지로 자신의 모듈에서 위의 명령을 시도하십시오.


답변

스크립트에서 기본이 아닌 모듈을 사용할 때 아래 함수를 호출합니다. 모듈 이름 옆에 최소 버전을 제공 할 수 있습니다.

# 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'

유용한 지 (아니면) 알려주세요


답변

#Requires문을 사용할 수 있습니다 (PowerShell 3.0의 모듈 지원).

#Requires 문은 PowerShell 버전, 모듈, 스냅인, 모듈 및 스냅인 버전 필수 구성 요소가 충족되지 않는 한 스크립트가 실행되지 않도록합니다.

따라서 스크립트 상단에 #Requires -Module <ModuleName>

필요한 모듈이 현재 세션에없는 경우 PowerShell은 해당 모듈을 가져옵니다.

모듈을 가져올 수없는 경우 PowerShell에서 종료 오류가 발생합니다.