0% found this document useful (0 votes)
13 views6 pages

WWW Sharepointdiary Com 2021 10 Prompt For Input in Powershell HTML

The document discusses various ways to prompt for user input in PowerShell scripts. It covers reasons for prompting input like authentication, script logic, validating values. It also covers benefits like making scripts interactive and flexible by prompting for runtime parameters instead of hardcoded values.

Uploaded by

koxafi2648
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

WWW Sharepointdiary Com 2021 10 Prompt For Input in Powershell HTML

The document discusses various ways to prompt for user input in PowerShell scripts. It covers reasons for prompting input like authentication, script logic, validating values. It also covers benefits like making scripts interactive and flexible by prompting for runtime parameters instead of hardcoded values.

Uploaded by

koxafi2648
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

   

SharePoint Diary
Salaudeen Rajack's SharePoint Experiences!

 SHAREPOINT SERVER  SHAREPOINT ONLINE  POWERSHELL  ADMINISTRATION  CUSTOMIZATION  OFFICE 365   

SharePoint Diary » PowerShell » How to Prompt for Input in PowerShell?

PowerShell PowerShell Tutorials


About Me
How to Prompt for Input in PowerShell?
 April 27, 2024  Salaudeen Rajack

Salaudeen Rajack is a globally recognized IT


Expert – Specialized in SharePoint, PowerShell,
Office 365 and related Microsoft technologies.

Recent Popular Tags

How to Create a Document


Library Template in SharePoint
Online?

SharePoint Online: Remove


“Everyone except external
users” from All Sites

Colored Folders in SharePoint


PowerShell provides various ways to prompt user input to perform different actions. This allows you to Online and OneDrive

create flexible, customizable, and interactive scripts that can accept dynamic runtime configuration,
parameters, and options instead of hard-coding values. In this comprehensive guide, we will explore the
How to Run a PowerShell
various methods available in PowerShell for prompting user input. Whether reading input from the Script? A Comprehensive
Guide!
command line, displaying GUI popups, offering menu choices, or validating values, PowerShell provides
robust options to create user-friendly input experiences. How to use the “Request Files”
feature in SharePoint Online?

Introduction to PowerShell Prompt for User Input


SharePoint Permissions – A
Prompting for user input allows you to create flexible PowerShell scripts that can accept parameters, Comprehensive Guide!
options, and other values from users at runtime. Some common reasons to prompt for input include:

Asking users to enter credentials for authentication PowerShell String


Manipulation: A
Getting choices from users to determine script flow and logic Comprehensive Guide

Accepting filenames, paths, and other input values to use in the script Install the PnP PowerShell
Module for SharePoint
Validating input by prompting users to confirm values Online

Creating interactive menus to provide options for users


SharePoint Admin Center: A
PowerShell provides cmdlets, read-host, parameters and arguments, input boxes, and other techniques Comprehensive Guide

to prompt the user appropriately. With the PowerShell prompt for user input, you can prompt users for
information such as file paths, usernames, passwords, and other parameters required for the script to Mastering PowerShell
Loops: An Essential Guide
execute successfully.

Mastering SharePoint
Benefits of Using PowerShell Prompt for User Input Document Library: A
Comprehensive Guide

Site Collection
Administrator in SharePoint
Online – A Comprehensive
Guide!

How to Connect to
SharePoint Online using
CSOM PowerShell?

How to Connect to
SharePoint Online from
PowerShell?

PowerShell Basics: Your


Quick Reference Guide!

Access Request Active Directory


Administration Admin Reports
One of the main benefits of using the PowerShell prompt for user input is that it makes your scripts Alerts Anonymous Access App Catalog App
more interactive. You can prompt users for input and then use that input to perform certain tasks within Pool Apps Architecture / Planning
the script. This can make your scripts more flexible and easier to use. Additionally, a PowerShell prompt Attachment Audit Azure Azure AD
for user input can help you to automate certain tasks that would otherwise require manual intervention. (Microsoft Entra) Backup/Restore BCS
This can save you time and increase efficiency within your organization. Best Practices Branding C# Calculated
Column CAML Central Administration
Using the Read-Host cmdlet to Prompt for User Input in PowerShell Classic Site Client Side Object
The easiest way to get input from the user in PowerShell is via the Read-Host cmdlet. This cmdlet Model (CSOM) Column
prompts the user for input and waits for the user to type a response. It can be used to collect various Communication Site Compliance
types of input, such as strings, numbers, and secure strings. Configuration Content Database
Content Editor Web Part Content Type
The basic syntax for the PowerShell prompt for user input is as follows:
CSS CSV Custom Action

Read-Host [-Prompt] <String> [-AsSecureString] [-MaskInput] Customizations Dataview Webpart

[<CommonParameters>] Deployment Guides Display Template

Distribution List Document Library


-Prompt: Specifies the text prompt displayed to the user. This parameter is positional and can be Email Errors and Solutions Event
used without explicitly naming it. For example, Read-Host “Enter your name”. The output of the
Log Event Receivers Excel Services Exchange
Read-Host cmdlet is a string object.
Online External Sharing External User
-AsSecureString: Indicates that the input should be treated as a secure string. This is useful for
FAQs Farm Features File File Explorer
passwords or other sensitive information, as the input is masked and stored in a
Folder Fusion Charts Governance Groups
System.Security.SecureString object.
Health Analyzer Host-named Site Collection Hub Site
MaskInput: This parameter indicates that the input should be masked, similar to password fields
IIS InfoPath Installation Integration
in GUI applications. It is available starting from PowerShell 7.2.
Javascript jQuery JSON Library List
Here is an example of how to get input using the Read-Host cmdlet.
List Forms List Item List Settings List
Template List View List View Web Part

# Prompt for a string input


Lookup Managed Metadata Managed
$name = Read-Host -Prompt "Enter your name"
Path Master Page Microsoft 365 Admin
#Get the input and store it in $Age variable name - without Prompt parameter Center Microsoft Forms Microsoft Graph
$Age = Read-Host "Please enter your age"
Microsoft Teams Migration/Upgrade

Write-Host "Hello $Name, welcome to my script!" Modern Site Monitoring My Site


Navigation Nintex Nintex Workflow

This script prompts the user with a message and then assigns the user input to a variable. The input will Object Model Office 365 Office 365
be displayed as a personalized message. Group Office Web Apps OneDrive for
Business Page Page Layouts Patching

PDF People Picker Performance Optimization

Permission Permission Level

Permission Report PnP


PowerShell PnP Provisioning Power

Automate Power BI PowerShell


PowerShell Tutorials Presentations

Product Review Quick Launch Quotas and

Locks Recycle Bin Reference REST

Ribbon Sandboxed solutions Search


Security Service Application Service

Packs SharePoint
When the user enters a value and presses the “Enter” key in the Windows PowerShell console, the
entered value is stored as a plaintext string object in the variable $name. PowerShell will append a colon SharePoint 2007 SharePoint
to the end of the prompt string.
2010 SharePoint 2013
Some useful parameters for Read-Host include: SharePoint 2016 SharePoint 2019

Prompt – Specifies the prompt text to display to the user. If the string includes spaces, enclose it SharePoint Admin Center SharePoint

in quotation marks. Basics SharePoint Database SharePoint

AsSecureString – The AsSecureString parameter Masks user input, like for passwords Designer SharePoint Designer 2013
SharePoint Development SharePoint
MaskInput – Masks each character as a * as it’s entered
Foundation SharePoint Framework (SPFx)

For example, to prompt for a password:


SharePoint Online
SharePoint Online Management
# Prompt for a secure string input (password)
$Password = Read-Host -Prompt "Enter your password" -AsSecureString Shell SharePoint Products Configuration

Wizard SharePoint Server


This example prompts the user for their password. When input is entered, asterisks (*) are displayed in
Shortcuts Site Collection Site
the place of characters on the console instead of the actual input.
Collection Administrator Site Columns
Site Settings Site Template SQL Server
SSL Certificate SSRS Step By Step Guide STSADM

Subsite Survey Team Site Tenant Term Set

Term Store Themes Timer Job Tips and


Tricks Tools & Utilities
Troubleshooting ULS Log User Control

User Profile Users Users and


Groups Validation Version History Visual
Studio web.config Web Application Web
Parts Web Services Windows Server

Workflows WSP Solution XML XSL

Getting Confirmation from the User

You can also use Read-Host to prompt users to confirm an action. For example:

$Confirm = Read-Host -Prompt "Are you sure you want to delete the file (Y/N)"
if ($confirm -eq 'y') {
# Delete file
} else {
Write-Host "Deletion cancelled"
}

This displays a prompt asking for confirmation before deleting a file. This validates the input, and the
appropriate code block is executed. Please note that Read-Host can only accept 8190 characters as
input from a user.

Prompting for User Input with Parameters in Scripts


For more complex input, you can accept parameters and arguments when running your PowerShell
scripts. Parameters allow you to input values in a named way, like -Name or -Path.

For example, we can define a PowerShell script called install-script.ps1 that accepts parameters:

param(
[string]$Name,
[string]$Path
)

Write-Output "Installing $Name to path $Path"

We can then run this and pass input values:

.\install-script.ps1 -Name MyApp -Path C:\Apps

For prompting options, you can use parameter sets to accept different combinations of parameter input.
You can also accept argument input for positional values. So, combining parameters and arguments
allows robust input prompts. More here: PowerShell function Parameters

Waiting for User Input


In some scenarios, you may need to wait for continuous user input. You can achieve this by using a
Read-Host loop, allowing users to provide input multiple times until they choose to exit.

# Initialize a flag to control the loop


$continue = $true

# Start the loop


while ($continue) {
$input = Read-Host "Enter some input or type 'Q' to quit"

if ($input -eq "q") {


# If the user enters 'exit', set the flag to false to exit the loop
$continue = $false
} else {
# Process the user's input (in this example, we just display it)
Write-Host "You entered: $input"
}
}

Write-Host "User chose to exit. Script completed."

You can modify the script to include more complex logic or actions based on the user’s input or specific
requirements.

Validate User Input


You can validate the user input to match a specific condition or criteria. Let’s see how to use input
validation using a loop. For example, you want to get the user’s age parameter.

# Promp for user input with validation


Do {
$Age = Read-Host -Prompt "Please enter your age"
} While ($Age -notmatch '^\d+$')

# Output the entered age


Write-Host "You entered age: $Age"

This will prompt you to enter a valid number.

Similarly, you can use the IF condition to validate and take action based on the user input.

$userInput = Read-Host "Enter a number between 1 and 10"


if ($userInput -ge 1 -and $userInput -le 10) {
Write-Host "Valid input: $userInput"
} else {
Write-Host "Invalid input. Please enter a number between 1 and 10."
}

If you are using function parameters, You can validate the user input with attributes: ValidateSet,
ValidateRange, ValidatePattern, etc. More here: Validating function parameters in PowerShell

Implementing a Menu to Prompt User Input


To provide interactive menu options, you can use Read-Host inside a loop to display options and get
menu choices. For example, create a simple menu that allows the user to perform basic system tasks
such as checking system information, listing files in a directory, and shutting down the computer:

# Define a function to display the system operations menu


function Show-SystemMenu {
Clear-Host # Clear the console to keep it clean
Write-Host "=== System Operations Menu ==="
Write-Host "1. Display System Information"
Write-Host "2. List Files in a Directory"
Write-Host "3. Shut Down Computer"
Write-Host "4. Exit"
}

# Display the system operations menu initially


Show-SystemMenu

# Start the menu loop


while ($true) {
$choice = Read-Host "Select an operation (1-4):"

# Validate user input


if ($choice -match '^[1-4]$') {
switch ($choice) {
1 {
# Display system information
Write-Host "System Information:"
Get-ComputerInfo | Format-Table -AutoSize
Read-Host "Press any key to continue..."
}
2 {
# List files in a directory
$directory = Read-Host "Enter the directory path:"
Get-ChildItem -Path $directory
Read-Host "Press any key to continue..."
}
3 {
# Shut down the computer
Write-Host "Shutting down the computer..."
#Stop-Computer -Force
}
4 { exit } # Exit the loop when 'Exit' is selected
}
}
else {
Write-Host "Invalid input. Please select a valid option (1-4)."
Start-Sleep -Seconds 2 # Pause for 2 seconds to display the message
}

# Redisplay the system operations menu


Show-SystemMenu
}

This displays a menu, prompts for choices, and executes different code blocks based on the menu
option chosen with a switch statement.

Creating Confirmation Pop-Ups and Input Box Prompts


If you need a more user-friendly and interactive way to prompt for input, you can create pop-up input
boxes using the System.Windows.Forms namespace. This approach enables you to design graphical
user interfaces (GUIs) for your scripts.

Add-Type -AssemblyName System.Windows.Forms


$InputBox = [System.Windows.Forms.MessageBox]::Show("Do you want to
continue?", "Confirmation", [System.Windows.Forms.MessageBoxButtons]::YesNo)
$InputBox

Here is another one with Icon:

Add-Type -AssemblyName System.Windows.Forms


[System.Windows.Forms.Application]::EnableVisualStyles()
$UserInput = [System.Windows.Forms.MessageBox]::Show("Do you want to proceed
execution?","Continue script execution" , "YesNo", "Question")

Creating a graphical input box can significantly enhance the user experience, especially for non-
technical users.

You can also use the Windows Script Host object to display a popup prompt:

$Prompt = New-Object -ComObject wscript.shell


$UserInput = $Prompt.popup("Do you want to proceed execution?",0,"Continue
script execution",4+32)
If($UserInput -eq 6)
{
Write-host -f Green "Script Execution Continued..."
}
Else
{
Write-host -f Yellow "Script Execution Aborted!"
}

Prompt for Input using Input Boxes

To provide an interactive prompt for input, you can create an input box. For example:

# Prompt the user for input using InputBox


$input = [Microsoft.VisualBasic.Interaction]::InputBox("Please enter your
name:", "User Input", "")

# Check if the user provided input


if ([string]::IsNullOrWhiteSpace($input)) {
Write-Host "User canceled input."
} else {
Write-Host "You entered: $input"
}

This displays an input popup to the user. You can check the input and continue script execution based
on it.

Get User Input with PowerShell GUI


While the PowerShell prompt for user input is a powerful feature, there are alternatives that you can use
depending on your needs. One such alternative is PowerShell popup input. This feature allows you to
create a graphical user interface (GUI) that prompts users for input. Here is an example:

# Load the System.Windows.Forms assembly


Add-Type -AssemblyName System.Windows.Forms
# Create a form object
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Enter the value"
$Form.Size = New-Object System.Drawing.Size(300,200)
$Form.StartPosition = "CenterScreen"

# Create a label to display instructions


$label = New-Object Windows.Forms.Label
$label.Text = "Enter your input:"
$label.Location = New-Object Drawing.Point(20, 20)
$form.Controls.Add($label)

# Create an OK button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Point(100,75)
$Button.Size = New-Object System.Drawing.Size(100,30)
$Button.DialogResult = [Windows.Forms.DialogResult]::OK
$Button.Text = "OK"
$Form.Controls.Add($Button)

# Create a text box for user input


$InputBox = New-Object System.Windows.Forms.TextBox
$InputBox.Location = New-Object System.Drawing.Point(50,50)
$InputBox.Size = New-Object System.Drawing.Size(200,20)
$Form.Controls.Add($InputBox)

# Show the form as a dialog box


$Result = $Form.ShowDialog()

# Check if the OK button was clicked


if ($Result -eq [Windows.Forms.DialogResult]::OK) {
$userInput = $InputBox.Text
Write-Host "You entered: $userInput"
}

# Dispose of the form


$form.Dispose()

This example creates a GUI that prompts the user for input and then displays the input in the console.

There are several resources available to help you master the PowerShell prompt for user input. Here’s
the Official documentation on the Read-Host prompt for user input: Read-Host Cmdlet Microsoft Docs

Summary
In this comprehensive guide, we’ve covered basic console input, getting confirmation from users, GUI
input boxes, parameterized scripts, and menus for continuous user interaction. By mastering these
concepts and real-world examples, you’re well-equipped to create interactive and user-friendly
PowerShell scripts:

Read-Host cmdlet to prompt for input

Accepting parameters and arguments

Input boxes via WinForms

Menus using Read-Host in a loop

Using these prompting techniques allows the creation of scripts that can accept runtime configuration
and input from users in a friendly way. This provides more flexibility than hard-coding values and
improves automation. By following the methods outlined in this article, you can become proficient in
using this feature and create more efficient and flexible scripts.

← Hash Tables in PowerShell: A Comprehensive Guide

How to Delete Files from the Preservation Hold Library in SharePoint Online? →

Salaudeen Rajack
Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on
experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products.
He has held various positions including SharePoint Architect, Administrator, Developer
and consultant, has helped many organizations to implement and optimize SharePoint
solutions. Known for his deep technical expertise, He's passionate about sharing the
knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *
Comment *

Name
Email

Notify me of follow-up comments by email.


Notify me of new posts by email.
Post Comment

Disclaimer Frequently Asked Questions: Subscribe to Updates via Email

This is my personal blog. Articles written on this blog are  Enter your email address:
from my experience for my own reference and to help
others. Email Address Subscribe

Do not reproduce my content anywhere, in any form


without my permission. If any article written on this blog
violates copyright, please contact me! If you have a more
elegant solution on any of the topics discussed – please Blog Awards
post a comment, I’ll be happy to hear!

Copyright © 2024 SharePoint Diary. All rights reserved. Support this site Privacy Policy Contact Us

You might also like