3

I have a problem with using a functions from file in a scriptblock. Function file name: functions.ps1.

I'm prefering using functions in a file and normally it's works. But in a scriptblock which I'm using for jobs I have errors. Can you help me with using functions in a scriptblock?

. .\functions.ps1
$ip = "10.0.0.24"
$scriptblock = { get-ostype -ip $args[0] }
Start-Job -name "name" -ScriptBlock $scriptblock -ArgumentList $ip

Error from a job:

The term 'get-ostype' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
    + CategoryInfo          : ObjectNotFound: (get-ostype:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : localhost
mklement0
  • 382,024
  • 64
  • 607
  • 775
mino
  • 125
  • 2
  • 11
  • 3
    Just load the file in your script block. `$scriptblock={. \functions.ps1; get-ostype -ip $args[0] }`. The job scope does not inherit the functions loaded in your current scope. – AdminOfThings Nov 15 '19 at 12:40

1 Answers1

3

The created job has its own scope that does not inherit the functions defined in your local scope. You can either load the functions in your job script block or use the -InitializationScript parameter.

# Option 1:
$ip="10.0.0.24"
$scriptblock = {get-ostype -ip $args[0]}
$initializationscript = {. c:\path\functions.ps1}

Start-Job -InitializationScript $initializationscript -ScriptBlock $scriptblock -ArgumentList $ip

# Option 2:
$ip="10.0.0.24"
$scriptblock = {. c:\path\functions.ps1; get-ostype -ip $args[0]}

Start-Job -ScriptBlock $scriptblock -ArgumentList $ip
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27