2

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
}
1
  • You don't need type casting, just remove it. Commented Dec 13, 2023 at 14:11

1 Answer 1

2

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

Comments

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.