Passing Script Module to "Invoke-Command"

Hi,

I created a script module which will run the provided script block as another user. Its interface looks like:

The Script Module

function Start-AsElevated {
    Param(
        $username,   <- Who to run as
        $password,    <- Their password
        $scriptblock)  <- The script to run as the impersonated user
}

Inside here I use Invoke-Command to call the provided script block and run it as the provided user.

This all works great until I want to use one of my other script modules inside the script block that is passed. The problem is that Invoke-Command makes the script run in a different shell and as such the modules are not loaded at that point. They are of course available in the “step” that calls “Start-AsElevated” but since the script block is not executed in that shell they are no use to me there in this situation.

Is there a way for me to get access to my other script modules in this situation?

I notice that there are some Octopus parameters that refer to the script modules but they seem to be null. I was hoping to use this parameter to call Import-Module in the passed script block.

The script used in the step itself would look something like the following:

The Script STEP

Start-AsElevated `
    -username $LocalAdminUserName `
    -password $LocalAdminPassword `
    -scriptblock {
         # .... do something
        MyScriptModule         <- All these 3 lines would be executed in another shell and so "CallMyScriptModuleHere" is not known
         # .... do something
    }

I would ideally just like to call something like

Import-Module $OctopusParameters['Octopus.Script.Module[MyScriptModule]']

in the script block but the parameter does not seem to be populated.

Does anyone have any ideas?

Thanks

Andy

Hi Andy,

Thanks for getting in touch and sorry for the late reply. I’ll review this and get back to you tomorrow.

Thanks!

Dalmiro

Hello again Andy,

I tried to find an easy approach, but unfortunately i had no luck. The easiest way i could think for this is the deploy your script module to your server as part of your regular deployment, and then use import-module on it on the scriptblock of your Start-AsElevated function.

Sorry its not better news :frowning:

Dalmiro