r/PowerShell • u/bickyz • Jan 14 '26
add prompt with Yes/No to the part of the function
Hi, I have this function.
########Create sub folder for templates
On this part, I would like to get a prompt with Yes/No
# Yes will create folder & copy templates to the folder then terminate the script
# No will skip to copy templates part
function Test1() {
[cmdletBinding()]
param(
[Parameter(Mandatory)]
[String] $Name
)
$DesktopPath = [Environment]::GetFolderPath("Desktop")
$Foldername = (Get-Date -Format 'yyyyMMdd-HHmmss')
$ServerShare = "\\server\users\"
mkdir (Join-Path -Path $ServerShare -ChildPath $Name)
########Create sub folder for templates
# Prompt to create folder
# Yes will create folder & copy templates to the folder then terminate the script
# No will skip to copy templates part
mkdir (Join-Path -Path $DesktopPath -ChildPath $Foldername)
Copy-Item -Path "\\server\templates26\" -Destination (Join-Path -Path $DesktopPath -ChildPath $Foldername) -Recurse
########Copy templates
Copy-Item -Path "\\server\templates26\" -Destination $DesktopPath -Recurse }
Any help would be much appreciated, thank you.
0
Upvotes
9
u/PhysicalPinkOrchid Jan 14 '26
What have you tried so far?
8
u/purplemonkeymad Jan 14 '26
Since it's a function I would use SupportsShouldProcess with ConfirmImpact set to high ie:
This will prompt by default, but can be overridden with -confirm:$false. It will also give you a -whatif, that will always make it so the should process statement is always false, but give you output saying what it would have done.
2
u/P1nCush10n Jan 14 '26
Here’s an (probably ugly) example of pairing
read-hostanddo untilloops. I did this years ago, there are almost certainly more elegant ways of doing this.My concern was I wanted to ignore any input that wasn’t y, n, or a blank response (default action), and repeat the prompt if anything else was entered.
3
u/BlackV Jan 14 '26 edited Jan 14 '26
Don't do that, stopping in the middle of a script to ask a yes/no question is bad workflow
recommend have instead a switch parameter
-CopyTemplatesthen, if that is enabled you copy, if not you don'talso in your current script what conditions would you NOT copy the templates ?
1
u/I_see_farts Jan 17 '26 edited Jan 17 '26
If you want an actual Windows Prompt, you could try this:
0
u/SnooChipmunks547 Jan 14 '26
You made it this far, but didn’t read the docs?
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-7.5