My question is to powershell 7.2 switch [L] Not to all
I found information about -confirm but not a help how I can set automatic [L] 'Not to all' into a function. I will that not a user make a input. -Confirm:$false, ConfirmPreference = "None" or 'Set-ExecutionPolicy Unrestricted' is not a help. The query comes every time. Do you have an idea / example how to set [L] to automatic?
PowerShell's confirmation prompts aren't designed to be responded to programmatically; instead:
Either: The user should decide, interactively.
Or: The prompt should be suppressed altogether (implying a [A] Yes to All
response), which situationally requires:
-Confirm:$false
, for cmdlets that define a confirm impact (a rating of the potential destructiveness / risk associated with the cmdlet's operation) that can be controlled with the common -Confirm
parameter or the $ConfirmPreference
preference variable, such as Remove-Item
-Force
, for cmdlets that would otherwise unconditionally present a confirmation prompt, such as Set-ExecutionPolicy
.
-Force
often has unrelated meanings in the context of other cmdlets, including in Get-ChildItem
and Remove-Item
, where it is used to include hidden items in the enumeration / deletion.In the case of Remove-Item
, specifically - in addition to the confirm-impact mechanism - you need -Recurse
to signal the explicit intent to delete a directory and all its contents.
In your particular case, the equivalent of defaulting to [L] No to All
would be to not invoke Remove-Item
at all if the target directory is non-empty:
# Assume $dir contains the literal directory path of interest.
# Note that -Force in the case of Get-ChildItem causes inclusion of hidden items.
if (Get-ChildItem -Force -LiteralPath $dir | Select-Object -First 1) {
Write-Error "Cannot remove directory $dir, because it is not empty."
}
else {
Remove-Item -LiteralPath $dir
}
Conversely, as stated, Remove-Item -Recurse -Confirm:$false -Force -LiteralPath $dir
would suppress the confirmation prompt, but quietly go ahead with the deletion ([A] Yes to All
is implied).