0

I've faced up with a problem to execute powershell class methods inside a scriptblock passed to invoke-command. Let's start with some examples

FooClass.psm1

class Foo {
    static [string]Func() {
        return "bar"
    }
}

FooToScriptblock.ps1

using module .\FooClass.psm1
Function FooToScriptBlock {
    $m = [Foo]::new()
    write-host "from func:" $m.Func()

    $sb1 = {$m = [Foo]::new(); $m.Func()}
    $sb2 = {param($foo)$foo.Func()}
    $sb3 = [scriptblock]::Create('$m.Foo()')

    $s = New-PSSession  -ComputerName "computer" -Credential "someuser"
    $r1 = Invoke-Command -Session $s -ScriptBlock $sb1 
    write-host $r1
    $r2 = Invoke-Command -Session $s -ScriptBlock $sb2 -ArgumentList $m
    write-host $r2
    $r3 = Invoke-Command -Session $s -ScriptBlock $sb3 
    write-host $r3
}

FooToScriptBlock

After executing I'm getting output like this

PS <scripts> $> .\FooToScriptblock.ps1
from func: bar
Unable to find type [Foo].
    + CategoryInfo          : InvalidOperation: (Foo:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound
    + PSComputerName        : 

You cannot call a method on a null-valued expression.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
    + PSComputerName        : 

Method invocation failed because [Deserialized.Foo] does not contain a method named 'Func'.
    + CategoryInfo          : InvalidOperation: (Func:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
    + PSComputerName        : 

You cannot call a method on a null-valued expression.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
    + PSComputerName        : 

So now the question. Is it possible to execute PowerShell classes inside a script block on another computer?

1 Answers1

1

The easiest solution is to specify the 'Using' statement in the PSSession by adding something like the following.

$sb = {using module UNC_Path_to_Module\FooClass.psm1}
$r = Invoke-Command -Session $s -ScriptBlock $sb

It should be noted that since PSSessions do not pass credentials to remote session by default and will not allow access to network resources requiring authentication. In order to authenticate to network resources you will need to specify the authentication method as CredSSP. This carries a security risk if the remote system is compromised.

New-PSSession -Authentication CredSSP