0

How can I invoke a powershell script from within another script? This is not working:

$param1 = "C:/Users/My Folder/file1"
$param2 = "C:/Users/My Folder/file2"
$command = "C:/Users/My Folder/second.ps1"

Invoke-expression $command -File1 $param1 -File2 $param2

... Second.ps1:

param(
[string]File1, [string]File2)...
3
  • 1
    & $command -File1 $param1 -File2 $param2 Commented Aug 27, 2015 at 18:56
  • Thank you!!! It worked Commented Aug 27, 2015 at 20:00
  • 1
    As a general Powershell tip : use functions instead of seperate script files for these actions : blogs.technet.com/b/heyscriptingguy/archive/2011/06/26/… Commented Aug 28, 2015 at 12:25

2 Answers 2

0

If there are no spaces:

Invoke-expression "$command $param1 $param2"

If you know where the spaces are:

Invoke-expression "$command `$param1HasSpaces` $param2"    

NB: If your execution policy is restricted (check with get-executionpolicy use:

Invoke-Expression "powershell -executionpolicy bypass -command `"$command $param1 $param2`""
Sign up to request clarification or add additional context in comments.

1 Comment

That gives me: "Invoke-Expression: A positional parameter cannot be found that accepts: 'C:/Users/My Folder/second.ps1 ...
0

You can do it like this if you slightly change your approach. Basically create the command string you want to execute, then create a scriptblock object from that and then use Invoke-Command instead of Invoke-Expression.

$param1 = "C:/Users/My Folder/file1"
$param2 = "C:/Users/My Folder/file2"
$command = "C:/Users/My Folder/second.ps1"

$str = '{0} -File1 "{1}" -File2 "{2}"' -f ($command, $param1, $param2)
$sb  =  [scriptblock]::Create($str)

Invoke-Command -ScriptBlock $sb

Comments

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.