Search code examples
powershellpowershell-cmdlet

User input in automated powershell scripts


I am writing powershell script which executes several powershell cmdlets sequentially. One of the cmdlets among them asks for a user input like [Y/N]. I want to pass the value as Y always. Is there any way to do this?


Solution

  • Sounds like you need to change the $ConfirmPreference variable.

    From the output of Get-Help about_Preference_variables:

    $ConfirmPreference
    ------------------
    Determines whether Windows PowerShell automatically prompts you for
    confirmation before running a cmdlet or function. 
    
    When the value of the $ConfirmPreference variable (High, Medium, Low) is
    less than or equal to the risk assigned to the cmdlet or function (High,
    Medium, Low), Windows PowerShell automatically prompts you for confirmation          
    before running the cmdlet or function.
    
    If the value of the $ConfirmPreference variable is None, Windows PowerShell
    never automatically prompts you before running a cmdlet or function.
    

    So, in order to suppress those confirmation message, simply do:

    $ConfirmPreference = "None"
    <# script here #>
    

    You can also do it on a per-cmdlet basis, with the -Confirm:$false parameter:

    Set-ADUser -Description $desc -Confirm:$false
    

    Note that this only works if the Cmdlet supports common parameter confirmation. It won't have any impact on homegrown cmdlets with funky self-made confirmation logic