Set hardcoded input for next Read-Host call

Viewed 168

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?

1 Answers

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
Related