win_shell: |
Get-disk
Initialize-Disk -Number 2 -PartitionStyle MBR
clear-disk -number 2 -removedata -Confirm:$false
Initialize-Disk -Number 2 -PartitionStyle MBR
new-partition -disknumber 2 -usemaximumsize | format-volume -filesystem NTFS -
newfilesystemlabel Data -Force
get-partition -disknumber 2 | set-partition -newdriveletter G
In the above code getting "Windows PowerShell is in NonInteractive mode. Read and Prompt." I am executing the above code using ansible playbook. Manually it is getting executed but when executed through the ansible getting error. Please help!
The error message implies that your PowerShell code triggered an interactive confirmation prompt, which, when PowerShell is running in non-interactive mode (CLI parameter -NonInteractive
) fails by design.[1]
For some of the commands you're already trying to suppress these prompts, with -Force
and -Confirm:$false
, but seemingly at least one of your commands still tries to prompt.
To categorically suppress all confirmation prompts[2] in a given script, you can use the $PSDefaultParameterValues
preference variable as follows:
-Force
has semantics that are unrelated to confirmation prompts, such as including hidden items when used with Get-ChildItem
or Get-Item
.-WhatIf
parameter to preview what a command would otherwise do.# !! SEE WARNING ABOVE.
$PSDefaultParameterValues = @{ '*:Force' = $true; '*:Confirm' = $false }
# ... Commands that normally prompt for confirmation.
Note:
The above deliberately assigns a new hashtable (@{ ... }
) to an implicitly local $PSDefaultParameterValues
variable, so as to limit the settings to the current scope (and its descendants). While simply adding to / modifying the preexisting $PSDefaultParameterValues
dictionary defined in the global scope (e.g. $PSDefaultParameterValues['*:Force'] = $true
) is technically possible, the changes would then take effect globally and may affect unrelated scripts run later in the same session. (That said, in the context of deployment tools such as Ansible, where a given PowerShell process runs a specific piece of code only, this problem won't arise).
In the rare event that you want to preserve existing values from the global dictionary, you can create a local clone of it first and then add to / modify that: $PSDefaultParameterValues = $PSDefaultParameterValues.Clone() $PSDefaultParameterValues['*:Force'] = $true $PSDefaultParameterValues['*:Confirm'] = $false
[1] Try powershell -NonInteractive -Command 'Read-Host'
, for instance, to provoke the error.
[2] At least for those commands that use only the two standard mechanisms for allowing prompts to be suppressed, -Confirm:$false
and -Force
. A notable exception is Remove-ChildItem
, which, when a nonempty directory is targeted, requires -Recurse
in order to avoid a confirmation prompt - see this answer.