Passing multiple values for the same parameter using -ArgumentList

I want to use Invoke-Command to run a Function on remote servers. The Function has 2 parameters, I want to pass a value to one of the parameters. How do I specify which parameter the value is for when I use Argumentlist ?

The command I’m using is:

Invoke-Command -ComputerName $Servers -ScriptBlock ${function:Set-MsxEncryption} -ArgumentList

The Function I’m calling is:

Function Set-MsxEncryption
{
param(
[string]$MachineName=$env:computername,
[string]$MsxValue="1"
)
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $MachineName)
$regKey = $reg.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL" )
$regkey.GetValueNames() | ForEach-Object {
$inst=$regKey.GetValue($_)
$path="SOFTWARE\\Microsoft\\Microsoft SQL Server\\"+$inst+"\\SqlServerAgent\\";
$MsxEncryption=$reg.OpenSubKey($path).GetValue("MsxEncryptChannelOptions");
if($MsxEncryption-ne$MsxValue){
"it's $MsxEncryption needs set to $MsxValue"
$Msx=$reg.OpenSubKey($path,$true)
$Msx.SetValue("MsxEncryptChannelOptions",$MsxValue,[Microsoft.Win32.RegistryValueKind]::DWORD)
}else{"Is already set to $MsxValue"}
}
}
 

You can pass it positionally, the function will bind it positionally.

$MachineName=$env:computername
$MsxValue=1
Invoke-Command -ComputerName $Servers -ScriptBlock ${function:Set-MsxEncryption} -ArgumentList $MachineName,$MsxValue

There is another approach as well by using $using:
It’s important to know that when you Invoke-Command the script block doesn’t know about your variables unless you have 3.0 or higher (or was this a 4.0 feature?) where we got the new USING variable scope which let us grab information from the calling script. If you use $using:MachineName & $using:MsxValue, you don’t need to pass MachineName & MsxValue in the argument list, too.

Example

Function Set-MsxEncryption {
    [string]$MachineName = $using:MachineName
    [string]$MsxValue = $using:MsxValue

    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $MachineName)
    $regKey = $reg.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL" )
    $regkey.GetValueNames() | ForEach-Object {
        $inst = $regKey.GetValue($_)
        $path = "SOFTWARE\\Microsoft\\Microsoft SQL Server\\" + $inst + "\\SqlServerAgent\\";
        $MsxEncryption = $reg.OpenSubKey($path).GetValue("MsxEncryptChannelOptions");
        if ($MsxEncryption -ne $MsxValue) {
            "it's $MsxEncryption needs set to $MsxValue"
            $Msx = $reg.OpenSubKey($path, $true)
            $Msx.SetValue("MsxEncryptChannelOptions", $MsxValue, [Microsoft.Win32.RegistryValueKind]::DWORD)
        }
        else {"Is already set to $MsxValue"}}

}

$MachineName=$env:computername
$MsxValue=1
Invoke-Command -ComputerName $Servers -ScriptBlock ${function:Set-MsxEncryption}