0

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??

1
  • 1
    As an aside: even if fixed wrong = (U+003D, Equals Sign) in the function call, all Write-Outputs in the function body become a part of the output so that $ssh_cmd is now an array, and $ssh_cmd.Count is 5 Commented Jul 10, 2024 at 9:45

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

3 Comments

p.s. I did about 5 rounds with Mr. GPT on this before I noticed the = signs and he was no help at all. Humans are not obsolete quite yet..
yeah, GPT are good for ideas, not actual code. Also: you aren't assigning the result of the function to $ssh_cms. On a side note: it's common practice to NOT use hyphens(-) in cmdlets and functions except to separate Verb and Noun. So: Get-SshCommand is preferred
Specify return is actually superfluous in this instance. It doesn't hurt tho'

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.