Search code examples
windowspowershellsshportportforwarding

ssh Bad local forwarding specification when passing port as parameter


I created this function in the .ps1 profile for Windows PowerShell:

function sshpc ([int]$port = 8888) {
    ssh -fNL [int]$port:localhost:[int]$port pc
}

However, the port forwading command does not work. It prints the message:

Bad local forwarding specification '[Int][Int]8888'

But running the command ssh -fNL 8888:localhost:8888 pc works fine.
How can I make this work?


What I tried:

I tried using the parameter definitions: ($port), ([int]$port), ($port = 8888) but these also fail.
This function works fine:

function sshpc {
    ssh -fNL 8888:localhost:8888 pc
}

Solution

  • [int]$port:localhost:[int]$port

    You cannot use casts this way, and they're also not necessary, given that you can only ever pass strings as arguments to external programs (aside from that, $port already is of type [int]).

    Instead, use an (implicit) expandable string to compose your argument:

    ssh -fNL ${port}:localhost:${port}
    
    • ${port}:localhost:${port} is implicitly treated as if it were enclosed in "...", i.e. as an expandable (interpolating) string .

      • In other words: "${port}:localhost:${port}" works too, and you may prefer it for conceptual clarity and to avoid cases where unquoted arguments aren't implicitly treated as expandable strings.

        • E.g., Write-Output "$baseName.txt" appends literal .txt to the value of $baseName, whereas Write-Output $baseName.txt tries to access a (nonexistent) .txt property on the object stored in $baseName; see this answer for background information.
    • Note the need to enclose the variable name, port, in {...} so as to delimit it; without it, the : would be considered part of the variable reference, making $port the a scope or namespace prefix of the following variable reference, which expands to the empty string due to non-existence: $port:localhost.

      • This delimiting isn't strictly necessary in the second ${port} reference, but was chosen for symmetry here.
      • See this answer for background information.