How to run an interactive PowerShell command non-interactively?

Denis Rutten 40 Reputation points
2023-02-03T11:45:03.7233333+00:00

How can I run a PowerShell command that is normally interactive non-interactively, i.e. supplying parameters directly in a PowerShell script instead of letting the user supply them?

What I have in mind is something like "piping" in bash. I'm not sure if anything that's similar to that exists in PowerShell.

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,606 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 34,511 Reputation points
    2023-02-03T13:13:50.48+00:00
    0 comments No comments

  2. Plamen Peev 90 Reputation points
    2024-04-29T20:12:53.4733333+00:00

    Hi @Denis Rutten ,

    You can create a script block within your PowerShell script that accepts parameters:

    $MyProgram = "powershell.exe"
    $MyArguments = "notepad; Start-Sleep 5"
    
    # Create script block with parameters
    $ScriptBlock = {
        param(
            [string]$Program,
            [string]$Arguments
        )
        Start-Process $Program -ArgumentList $Arguments
    }
    # Run the script block
    & $ScriptBlock $MyAppName $MyArguments
    

    You can also use function if more complex solution is required.

    As far as piping goes, it is actually a core functionality of PowerShell, here is an example:

    # Get-Process gives you all currently running processes
    # Piping the output to Where-Object and filtering to processes with the name "Explorer"
    # Piping the output to Select-Object and selects given property
    
    Get-Process | Where-Object {$_.Name -EQ "Explorer"} | Select-Object CPU
    

    Another example:

    $Names = "John", "Kelly", "Steven"
    $Names | ForEach-Object {"Hello $_!"}
    

    I hope this helps.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.