Skip to content

Instantly share code, notes, and snippets.

@JeffBrownTech
Created March 26, 2020 12:41
Show Gist options
  • Save JeffBrownTech/ec7bb7b469bf3e31927a1fef15c820b4 to your computer and use it in GitHub Desktop.
Save JeffBrownTech/ec7bb7b469bf3e31927a1fef15c820b4 to your computer and use it in GitHub Desktop.
Create a PowerShell prompt using .NET classes
function Remove-MyItem {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 1)]
[string]
$Path
)
$item = Get-Item -Path $Path
# Create prompt body
$title = "Confirm"
$message = "Are you sure you want to perform this action?`nPerforming the operation ""Remove File"" on target $($item.FullName)."
# Create answers
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Continue with only the next step of the operation."
$yesToAll = New-Object System.Management.Automation.Host.ChoiceDescription "Yes to &All","Continue with all the steps of the operation."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Skip this operation and proceed with the next operation."
$noToAll = New-Object System.Management.Automation.Host.ChoiceDescription "No to Al&l", "Skip this operation and all subsequent operations."
$suspend = New-Object System.Management.Automation.Host.ChoiceDescription "&Suspend", "Pause the current pipeline and return to the command prompt. Type ""exit"" to resume the pipeline."
# Create ChoiceDescription with answers
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $yesToAll, $no, $noToAll, $suspend)
# Show prompt and save user's answer to variable
$response = $host.UI.PromptForChoice($title, $message, $options, 0)
# Perform action based on answer
switch ($response) {
0 { Remove-Item -Path $item.FullName; break } # Yes
1 { Remove-Item -Path $item.FullName; break } # Yes to All
2 { return; break } # No
3 { return; break } # No to ALL
4 { return; break } # Suspend
}
}
@Natfan
Copy link

Natfan commented Jun 22, 2022

Hiya,

I've forked this file, and removed the use of New-Object in favour of ::new calls. Also removed System. from the .NET calls as it is implicit.
https://gist.github.com/Natfan/c50fc34624add852192888c4ae33d3fe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment