问题描述:

I'm currently having issues whilst calling Import-Module with Powershell and would be grateful for some advice.

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

File skipped because it was already present from "Microsoft.PowerShell".

The problem is that it will get caught if the import command is within a try / catch statement.

I've read a number of posts regarding this (example PowerShell on SCOM fails to import module) and one did mention to try adding "-ErrorAction SilentlyContinue" to the Import-Module command, but unfortunately this makes no difference.

Below is the code I'm currently using to test the issue which should give you a better understanding of what I am trying to achieve.

Has anyone managed to successfully ignore these warnings on module import whilst wrapped in a try / catch before?

Thanks 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: $_"

}

网友答案:
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
}
相关阅读:
Top