0

I know, this has been asked a few times but I cannot seem to get it working. Basically, I am using multiple ps1 files so I don't have to have a very large script, in this case, its two files (so far):

Migration-Main.ps1

Migration-Companies.ps1

I want to call Migration-Companies.ps1 from Migration-Main.ps1 using invoke expression but this seems to only work if there is only one parameter in the target script, in my case there are two:

param (
    [parameter(mandatory=$false )]
    [datetime]$CompanyDateCull,  
    [parameter(mandatory=$false )]
    [string]$CompanyManagerCull
)

Write-Output $CompanyDateCull

So if I try to call the script like so:

Invoke-Expression "$Script_Companies -CompanyDateCull $CompanyDateCull -CompanyManagerCull "Fred""

I will get the following result:

Invoke-Expression : A positional parameter cannot be found that accepts argument 'Fred'.
At C:\Users\user\OneDrive\Scripts\Migrations\Imports\FastTrack-Migration-Main.ps1:282 char:1
+ Invoke-Expression "$Script_Companies -CompanyDateCull $CompanyDateCul ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Expression], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand

But if i remove the second parameter

Invoke-Expression "$Script_Companies -CompanyDateCull $CompanyDateCull"

it works:

Saturday, 21 September 2013 12:00:00 AM

I have tried running the file with other commands as well, such as simply calling PowerShell.exe:

PowerShell.exe -file $Script_Companies -CompanyDateCull $CompanyDateCull -CompanyManagerCull $CompanyManagerCull

But this stops any of my dot sourced functions from being accessible to the script being called, which is a requirement.

Any help would be much appreciated.

1
  • Why do you use Invoke-Expression at all? Commented Sep 21, 2018 at 7:34

1 Answer 1

1

For the first query you need escape the double quotes with backtick(`) :

Invoke-Expression "$Script_Companies -CompanyDateCull $CompanyDateCull -CompanyManagerCull `"Fred`""
Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou this works: Invoke-Expression "$Script_Companies -CompanyDateCull '$CompanyDateCull' -CompanyManagerCull '$CompanyManagerCull'"

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.