简体   繁体   中英

Trying to pass variable to a PowerShell function which is then run as a Start-Job

I am trying to pass the values of a variable (or more but for testing just the one right now) from a function to a Powershell Start-Job.

This works if using the invoke-expression but I have to get rid of the | out-string if passing to the start-job.

Works:

$thecomp = "127.0.0.1"

$func = {$compr = $thecomp; function TestConnection {Test-Connection -ComputerName $compr}  }  | Out-String

invoke-expression $func 

TestConnection

This does not work and notice the difference in the $func line:

$thecomp = "127.0.0.1"

$func = {$compr = $thecomp; function TestConnection {Test-Connection -ComputerName $compr}  } 

Start-Job -Name testjob -InitializationScript $func -ScriptBlock {TestConnection} -ArgumentList $compr,$thecomp | Out-Null

Wait-Job -Name testjob | Out-Null

Receive-Job -Name testjob  

Remove-Job *


I get the same error whether this is the local machine or a remote machine:

Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. + CategoryInfo : InvalidData: (:) [Test-Connection], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand + PSComputerName : localhost


I've tried a number of different things including using -ArgumentList and other things. I'm really at a loss as to what I am missing. If I request the variables $compr and $thecomp in the ISE after running the above, I get the IP but it is not passing to the function that's within the Start-Job.

I got it working using a different method. This is what I am doing that works.

$system = '127.0.0.1'

$func = {
          param ([string]$system)
          Process {Test-Connection -ComputerName $system } 
        }

Start-Job -Name testjob -ScriptBlock $func -ArgumentList $system | Out-Null

Wait-Job -Name testjob | Out-Null
Receive-Job -Name testjob 
Remove-Job *


It seems that the function is no longer explicitly named but is rather called or used with the variable defining it.


This also works and coincides better with what i was originally trying to do.

$system = '127.0.0.1'
$func = {function TestConnection ($system) {Test-Connection -ComputerName $system } } # | Out-String
Start-Job -Name testjob -InitializationScript $func -ScriptBlock {TestConnection $args} -ArgumentList $system  | Out-Null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM