riviera990
riviera990

Reputation: 33

How to call a powershell script to another powershell script with arguments?

I just need to call another script and pass the parameters to it.

I tried doing invoke-expression to access it, i tried using &, and nothing worked

I tried doing the following:

 $hostfile = "C:\Users\username\Desktop\csvfile_test.csv"
 $outFile = ".\testerFile.xlsx"
 &  '.\organizer.ps1' "-csvFile $hostfile -outputPath $outFile "

Invoke-Expression 'C:\Users\username\Desktop\organizer.ps1' "$hostfile $outFile"

I receive the following errors:.

with ampersand (&):

PS C:\Users\username\Desktop> C:\Users\username\Desktop\scanner.ps1
Exception calling "ReadLines" with "1" argument(s): "The given path's format is not supported."
At C:\Users\username\Desktop\scanner.ps1:48 char:1
+ [System.IO.File]::ReadLines("$csvFile") | ForEach-Object {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException

with invoke-expression:

Exception calling "ReadLines" with "1" argument(s): "The given path's format is not supported."
At C:\Users\username\Desktop\scanner.ps1:48 char:1
+ [System.IO.File]::ReadLines("$csvFile") | ForEach-Object {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException

Invoke-Expression : A positional parameter cannot be found that accepts argument 'C:\Users\username\Desktop\csvfile_test.csv .\testerFile.xlsx'.
At C:\Users\username\Desktop\scanner.ps1:69 char:1
+ Invoke-Expression 'C:\Users\username\Desktop\organizer.ps1' "$host ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Expression], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand

Upvotes: 0

Views: 1961

Answers (1)

Bill_Stewart
Bill_Stewart

Reputation: 24515

When you write this:

& '.\organizer.ps1' "-csvFile $hostfile -outputPath $outFile "

you are passing a single parameter to the script (one quoted string). That's not what you want.

This is what you need:

$hostfile = "C:\Users\username\Desktop\csvfile_test.csv"
$outFile = ".\testerFile.xlsx"
.\organizer.ps1 -csvFile $hostfile -outputPath $outFile

First, you don't need the & (invocation) operator because your command name (the organizer.ps1 script in the current location, in this example) doesn't contain spaces. (You can add it if you want, but it's unnecessary in this scenario.)

Second, the -csvFile and -outputPath parameters each require a string.

Upvotes: 2

Related Questions