How to correctly ignore Import-Module errors in PowerShell

I am currently having problems calling Import-Module with Powershell and I will be grateful for some advice.

According to previous questions and answers, the following error received while trying to import a module using PowerShell can be ignored:

File skipped because it was already present in Microsoft.PowerShell.

The problem is that it will be caught if the import command is in the try / catch statement.

I read a few posts about this (the PowerShell example on SCOM could not import the module ), and one mentioned to try adding “-ErrorAction SilentlyContinue” to the Import-Module command, but unfortunately it does not matter.

Below is the code I'm currently using to test for a problem that should give you a better idea of ​​what I'm trying to achieve.

Has anyone been able to successfully ignore these warnings when importing a module while they were wrapped in try / catch?

Thank you for your time,

Andrew

function load_module($name) { if (-not(Get-Module -Name $name)) { if (Get-Module -ListAvailable | Where-Object { $_.name -eq $name }) { Import-Module $name return $true } else { return $false } } else { return $true } } $moduleName = "ActiveDirectory" try { if (load_module $moduleName) { Write-Host "Loaded $moduleName" } else { Write-Host "Failed to load $moduleName" } } catch { Write-Host "Exception caught: $_" } 
+6
source share
1 answer
 function Load-Module { param ( [parameter(Mandatory = $true)][string] $name ) $retVal = $true if (!(Get-Module -Name $name)) { $retVal = Get-Module -ListAvailable | where { $_.Name -eq $name } if ($retVal) { try { Import-Module $name -ErrorAction SilentlyContinue } catch { $retVal = $false } } } return $retVal } 
+5
source

Source: https://habr.com/ru/post/915192/


All Articles