Search code examples
powershellinvokeinvoke-command

Powershell Invoke-Expression A parameter cannot be found that matches parameter name = ""


Im trying to invoke a Ps script from antoher script. The scripts are both in the same path. Also the script I'm trying to invoke takes 4 parameters.

Whem i execute that file from powershell with the parameters, then it works without errors.

But invoking it with the Invoke-Expression Command does not work. Keep getting the error :

'A parameter cannot be found that matches parameter name'

Script with the Paramters :

        param ([Parameter(Mandatory = $true)]
        [string] $Samname,
        [string] $Fullname,
        [string] $Password,
        [string] $Groups
    )    

$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force

New-localuser -name $Samname -FullName $Fullname -password $securePassword -PasswordNeverExpires -UserMayNotChangePassword

#Add the User to the Groups

$localGroups = Get-LocalGroup
[string[]]$GroupArray = $Groups.Split(' ')
    foreach ($localgroup in $localGroups){

        foreach ($group in $GroupArray){

            $group = $group.Replace(';', '') 
 
        if ($group.toString().Equals($localgroup.toString())){
            Add-LocalGroupMember -Group $localgroup -Member $samname
        }
    }
}

Script with Invoke-Expression command :

$XmlDocument = 'C:\SomeFile\toPs\TmpUser.config'
[XML]$XmlFile = Get-Content $XmlDocument

[string] $Samname = $XmlFile.User.Username
[string] $Fullname = $XmlFile.User.Fullname
[string] $Password = $XmlFile.User.Password
[string] $Groups = $XmlFile.User.Groups 

$script = ".\CreateUser.ps1" 

Invoke-Expression $script "-Samname $Samname -Fullname $Fullname -Password $Password -Groups $Groups"

I'm not that sure if I'm using the params the right way, when I invoke the script.

Thanks for your help :)


Solution

  • It's hard to tell exactly what's tripping up Invoke-Expression without the full extent of the error message, but the good news is that you don't need Invoke-Expression at all!

    Use the invocation operator (also known as the "call operator", &) instead, it natively supports parameter binding:

    $XmlDocument = 'C:\SomeFile\toPs\TmpUser.config'
    [XML]$XmlFile = Get-Content $XmlDocument
    
    [string] $Samname = $XmlFile.User.Username
    [string] $Fullname = $XmlFile.User.Fullname
    [string] $Password = $XmlFile.User.Password
    [string] $Groups = $XmlFile.User.Groups 
    
    $script = ".\CreateUser.ps1" 
    
    & $script -Samname $Samname -Fullname $Fullname -Password $Password -Groups $Groups