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}