Chris
Chris

Reputation: 131

Powershell use Read-Host variables in command

I have a very simple .ps1-script:

$prename = Read-Host 'What is your prename?'
$lastname = Read-Host 'What is your lastname?'
.\migration.exe -name=$prename -password=$lastname

Regardless of what the user enters, $prename and $lastname don't get passed to migration.exe - they are empty!

What am I doing wrong?

Upvotes: 1

Views: 937

Answers (2)

mklement0
mklement0

Reputation: 438153

$prename and $lastname don't get passed to migration.exe - they are empty!

These variable references are not empty; they're - unexpectedly - not expanded (interpolated), as of PowerShell 7.1; that is, external program .\migration unexpectedly receives the following arguments verbatim: -name=$prename and -password=$lastname.

This should be considered a bug - see GitHub issue #14587.

The workaround is to use explicit string interpolation ("..."):

.\migration.exe -name="$prename" -password="$lastname"

Note: On Windows, the partial quoting is not guaranteed to be passed through as-is to the target program; instead, PowerShell performs its own parsing first and then performs ("-based) re-quoting on demand behind the scenes, depending on whether the resulting argument contains whitespace. For instance, if $prename's value is foo,
verbatim -name=foo is passed to migration.exe; if the value is foo bar,
verbatim "-name=foo bar" is passed - which the target program may or may not process properly; if not, you'll have to use --%, the stop-parsing symbol operator - see this answer.

Upvotes: 2

Aaron
Aaron

Reputation: 573

You are passing the objects $prename and $lastname. You need expand the variables so you pass the value in the variables.

.\migration.exe -name=$($prename) -password=$($lastname)

Upvotes: 0

Related Questions