Invoke-Command with local nested functions

Hi
I’m trying to run invoke-command with nested function, but nested function is not recognized as a function.

function Get-Dir
{
[CmdletBinding()]
[OutputType([PSObject])]
param
(
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
$path
)

dir $path

}

function Get-Dir2
{
[CmdletBinding()]
[OutputType([PSObject])]
param
(
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
$path2
)

Get-Dir -path $path2

}

$Credential = Get-Credential
$so = New-PsSessionOption –SkipCACheck -SkipCNCheck -SkipRevocationCheck
$con = New-PSSession -ComputerName computername -Credential $Credential -Authentication Credssp -UseSSL -SessionOption $so
Invoke-Command -Session $con -ScriptBlock ${function:Get-Dir2} -ArgumentList “c:”

you should define you function inside scriptblock or use functions from module available on target computer

there is a method for redefining external function inside scriptblock, but it is not easy to implement

+1 to Max.

The problem is that you haven’t nested the functions; you’ve defined them on your local computer. The remote computer’s FUNCTION: drive doesn’t share the same memory space as your local computer, and so the functions don’t exist there.

It would probably be easier to define the functions, and whatever commands you want to run that use those functions, in a .ps1 file on your local computer. Then use -FilePath of Invoke-Command instead of -ScriptBlock, which will transmit the entire script file to the remote machine and then run that script there.

Thx for the answer.
Do you have a link for ‘a method for redefining external function inside scriptblock’. I’ve search for that, but don’t seem to get a hit that tells me how.

Thx for the reply.
I’ve tested it now with -FilePath and that seems to work. That could be a solution to my problem.

Oh yeah, it’s way easier than you’re thinking. The function definition itself has to be inside the script block. Like, all the code for the function.

What you’re doing with -FilePath (below) is much “cleaner.”