1

I need to execute powershell file, test.ps1, from test1.ps1. I am using start-job feature of powershell. In my test1.ps1, I have

$pathToFile = (Join-Path -Path $PSSCriptRoot -ChildPath "test.ps1")
$ar = $a, $b # all these variables have values assigned 
Start-Job -Name job2 -ScriptBlock{& $pathToFile -fName $args[0] -lName $args[1]} -ArgumentList $ar

In my test.ps1, I have fName and lName as parameters like:

param([string]fName, [string]lName]

I keep getting the following error:

The expression after '&' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object.

The problem is here Start-Job -Name job2 -ScriptBlock{& $pathToFile -fName $args[0] -lName $args[1]} -ArgumentList $ar

But I don't seem to find the solution to resolve this issue.And Yes, I verified that $pathToFile contains exact path to test.ps1 => C:\foo\test.ps1 Thanks for any help or suggestion.

3 Answers 3

4

After a few hours of research, I finally made it work.

The solution is to use $using:pathToFile.

So, instead of using

Start-Job -Name job2 -ScriptBlock{& $pathToFile -fName $args[0] -lName $args[1]} -ArgumentList $ar

the solution is to use this:

Start-Job -Name job2 -ScriptBlock{& $using:pathToFile -fName $args[0] -lName $args[1]} -ArgumentList $ar

I hope this will help other folks.

Sign up to request clarification or add additional context in comments.

Comments

0

it should also work like this:

$pathToFile = (Join-Path -Path $PSSCriptRoot -ChildPath "test.ps1")
$ar = $a, $b, $pathToFile  # all these variables have values assigned 
Start-Job -Name job2 -ScriptBlock{& $args[2] -fName $args[0] -lName $args[1]} -ArgumentList $ar

so you must pass the absolute path into the arguments variable

Comments

-1

Have you tried the invoke-expression cmdlet? This is what I usually use.

Invoke-Expression [-Command] [ ]

1 Comment

This has little to do with the OP's question, which boils down to a local variable not being defined when run in the context of a job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.