1

I have a PoSH script that I can't figure out is not running..

function Connect-AD
{
    Param($mod,$cmd)
    Write-Host "$mod $cmd"
    Write-Host "`tConnecting to AD: $DC`n"
    $ADSession = New-PSsession -ComputerName $DC -Credential $MyCredential
    Invoke-Command -Command {Import-Module ('$mod') -Cmdlet ('$cmd')} -Session $ADSession
    Import-PSSession -Session $ADSession -Module ('$mod') -Prefix r | Out-Null
}

I then try to call this with..

Connect-AD -mod 'ActiveDirectory' -cmd 'Get-ADUser,New-ADUser'

But no mater what I do I keep getting..

The specified module '$mod' was not loaded because no valid module file was found in any module directory.

The Write-Host inside the function outputs the parameters correctly, so it is getting that far. However it is not being passed into the Invoke-Command or Import-PSSession?

I've tried different ways to escape the parameters, etc.. but no luck.

What am I not doing correctly? Anyone able to help me out? Thanks.

0

1 Answer 1

7

Single quoted strings don't interpolate variables, '$mod' is a literal string "dollar m o d".

And you probably need to read all the similar questions on passing parameters to Invoke-Command, because the command {} is running on another computer - how will it know what the variable $mod is on your computer?

Passing string $variable to invoke-command scriptblock parameter -name

Powershell: How to pass parameter with invoke-command and -filepath remotely?

Something like

Invoke-Command -Command {param($mod, $cmd) Import-Module $mod -Cmdlet $cmd} -Session $ADSession -ArgumentList $mod,$cmd

Help Links (if available):

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.