M
M
Morrowind2020-09-21 14:49:42
PowerShell
Morrowind, 2020-09-21 14:49:42

How to pass a function to Invoke-Command?

Hello.
The question is, you need to throw a function in the invoke-command function.
Example:

function a1 { 
$aa1 = 'Name1'
"Code code code...."
return $aa1
}

function b2 {
 invoke-command -computername $Computer -scriptBlock {
''Code code code"
# <------- вот здесь мне необходима функция a1
$exit = 'CODE CODE '

return $exit
}
}

$variable = b2
'Все равно этому значению ' + $variable | out-file C:/Temp/log.txt


The problem is that the function is not passed through Param . Even if you enclose the function beforehand in a variable. There is an error in the report that "name not found" (in general, it does not know such a function with the specified name.)
Option Can I call my function from a script in Invoke-Command? good. But I need to use not just a function, but also a separate code. How to combine both that and another I do not quite understand.

Offer to put everything in 1 function in advance and use 1 common function:
Invoke-Command -ComputerName DC1 -ScriptBlock ${Function:MyFunction}

Not exactly the right solution for me.

Please suggest solutions if there are any.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxKozlov, 2020-09-21
@hekkaaa

Well, since I was magically summoned... :)
The easiest way to call remotely is to call a file, not a script block. and in it to write any functions. Invoke-Command -FilePath ....
But if calling a file does not suit you, but you want to use local functions, then you can use this trick.

function foo {
param($a)
 "I'm a FOO func on $($env:COMPUTERNAME)- $a"
}
function bar {
param($a)
 "I'm a BAR func on $($env:COMPUTERNAME)- $a"
}

# variant 1
$foo = $function:foo
Invoke-Command -ComputerName REMOTE {
   Set-Content function:foo $using:foo
   foo 'aaa'
}
#variant 2
Invoke-Command -ComputerName REMOTE {
  param($bar)
  Set-Content function:bar $bar
  bar 'aaa'
} -ArgumentList $function:bar

Naturally, in this way it is necessary to import all the necessary local functions into the remote session

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question