powershellpowershell-7.0

Parameter values empty in Powershell function


All my parameter values are being received as empty in this seemingly straightforward function:

function Get-SSH-Command {
    param (
        [string]$private_key_path,
        [string]$user,
        [string]$domain
    )
    Write-Output "Function called with parameters:"
    Write-Output "PPP: $private_key_path"
    Write-Output "User: $user"
    Write-Output "Domain: $domain"

    return "ssh " +
        "-i '$private_key_path' " +
        "-o StrictHostKeyChecking=no " +
        "-o UserKnownHostsFile=known_hosts " +
        "${user}@${domain}"
}

$env:PRIVATE_KEY_PATH = "C:\Users\MC\key_pair.pem"
$env:EC2_USER = "ubuntu"
$env:EC2_TEST_DOMAIN = "contoso.com"

Write-Output "1: $env:PRIVATE_KEY_PATH"
Write-Output "2: $env:EC2_USER"
Write-Output "3: $env:EC2_TEST_DOMAIN"

$ssh_cmd = Get-SSH-Command `
    -private_key_path=$env:PRIVATE_KEY_PATH `
    -user=$env:EC2_USER `
    -domain=$env:EC2_TEST_DOMAIN

Write-Output $ssh_cmd

The output is:

1: C:\Users\MC\key_pair.pem
2: ubuntu
3: contoso.com
Function called with parameters:
PPP:
User:
Domain:
ssh -i '' -o StrictHostKeyChecking=no -o UserKnownHostsFile=known_hosts @

Why??


Solution

  • Sadly, PowerShell just failed silently so it took me an embarrassingly long amount of time to discover that I made a simple syntax error.

    I should not have added these = signs in the function call:

    Get-SSH-Command `
        -private_key_path=$env:PRIVATE_KEY_PATH `
        -user=$env:EC2_USER `
        -domain=$env:EC2_TEST_DOMAIN
    

    should be

    Get-SSH-Command `
        -private_key_path $env:PRIVATE_KEY_PATH `
        -user $env:EC2_USER `
        -domain $env:EC2_TEST_DOMAIN