I am trying to use InitialSessionState.ImportPSModule
in order to import a Powershell module.
I am interested in knowing if importing of the module failed due to any reason (e.g file not found etc.). Putting such code in the try block does not raise an exception in the case of failure and the function seems to fail silently and continue if it is not able to import the module.
Is there a way to be alerted in the code if the import fails?
I am trying to do something like the following. In the code below, the module "TestModule1234" does not exist. The catch block does not catch an exception.
Note: This is just prototype test code, so please ignore any production code related irregularities.
try
{
//Initializing the PowerShell runspace
InitialSessionState psSessionInitialState = InitialSessionState.CreateDefault();
LogFile.Log("Importing Module TestModule1234");
psSessionInitialState.ImportPSModule(new[] { "TestModule1234" });
LogFile.Log("Creating Powershell Runspace");
m_PoshRunspace = RunspaceFactory.CreateRunspace(psSessionInitialState);
}
catch (System.Exception ex)
{
LogFile.Log("Failed to create a Powershell Runspace");
LogFile.Log(ex.ToString());
throw;
}
import-module xyz
I getImport-Module : The specified module 'xyz' was not loaded because no valid module file was found in any module directory.
. Can you show us how you try to import the module ? – Medin