2

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?

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • Mathias' answer is a clever workaround, assuming the prompt strings are known and static; if function `Foo` happens to be inside a _module_, you'd have to temporarily create a _global_ `Read-Host` function (`function global:Read-Host { ... }`). – mklement0 Jan 07 '21 at 16:15
  • 1
    Generally speaking: _Inside_ a PowerShell session, [`Read-Host`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/read-host) only ever reads from the _host_ (typically, the terminal), interactively. However, when stdin input is provided from _outside_ a session, via the [PowerShell CLI](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh), `Read-Host` does read from it - see [this answer](https://stackoverflow.com/a/53330818/45375). – mklement0 Jan 07 '21 at 16:16

1 Answers1

4

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206