Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

powershell - Set hardcoded input for next Read-Host call

I have a PowerShell script (which I cannot change) with the following function inside it:

function Foo ([string] param1) {
    [...]
    $var1 = Read-Host "Test"
    $var2 = Read-Host "Test2"
    [...]
}

I want to call the function from my PowerShell script and want to prevent that the user has to input any values, instead I want to prepare hardcoded values.

I tried the following:

@("Var1Value", "Var2Value") | Foo "Param1Value"

But it still prompts the user. Any ideas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

During command discovery, functions take precedence over binary cmdlets, so you can "hide" Read-Host behind a fake Read-Host function:

# define local Read-Host function
function Read-Host {
  param([string]$Prompt)

  return @{Test = 'Var1Value'; Test2 = 'Var2Value'}[$Prompt]
}

# call foo
foo 

# remove fake `Read-Host` function again
Remove-Item function:Read-Host -Force

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...