1
votes

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

3 Answers

4
votes

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.

0
votes

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

-1
votes

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

Invoke-Expression [-Command] [ ]