Powershell New-Item: How to Accept Confirmation Au

2020-07-02 11:53发布

问题:

I'm trying to create a new directory on a network drive using a powershell script but it keeps prompting me

"Confirm: Are you sure you want to perform this action ...."

Is there a way to override this so it doesn't ask me since I'm running this script from a web interface.

Here is my call:

New-Item $rollbackDirectory -type Directory -Force

It does the same thing, with or without the -Force parameter

I've also tried this format with no luck

New-Item -name $rollbackName -itemtype directory -path $rollbackdrive -Debug -Force

回答1:

-confirm need only be specified when you want the cmdlet to prompt you for confirmation. Whether the cmdlet by itself would prompt for confirmation or not depends on the developer of the cmdlet who can set a high, medium, low for the cmdlet based on its effect. Based on the value of $ConfirmPreference you will get the confirmation automatically for a cmdlet. The default value for $ConfirmPreference is high and the level set for New-Item is medium. So if the New-Item is prompting for confirmation, the $ConfirmPreference value must have been changed to medium or low.

Change it using $ConfirmPreference="high" or even $ConfirmPreference="none" to make New-Item not prompt, or your solution of -confirm:$false works as well by overriding the $ConfirmPreference.

Explained perfectly here: http://blogs.msdn.com/b/powershell/archive/2006/12/15/confirmpreference.aspx

Hope this clears it up.



回答2:

I ended up trying this (even though I read on another SO post that it is not correct):

New-Item $rollbackDirectory -type Directory -Force -Confirm:$false

And it worked! Hope this helps others with the same issue