Sunday, March 27, 2011

PowerShell - How to use named optional parameters in PowerShell?

Scenario:
How to use named optional parameters in PowerShell?

Explanation:
I always wondered whether it is possible to use named optional parameters in PowerShell scripts.
The below script explains how to accomplish it.

Solution:
param([string]$SolutionPath = "", [string]$WebApp = "")
The above line tells PowerShell to extract values from parameters "SolutionPath" and "WebApp".
These values will be used in PowerShell with the same names ($SolutionPath and $WebApp)

Lets save the below code into a ps1 file and name it "NamedParameters.ps1"
#IMPORTANT - The below line should be the first line. There should be nothing before the below line.
param([string]$SolutionPath = "", [string]$WebApp = "")

Write-Host "Solution Path: $SolutionPath"
Write-Host "Web App: $WebApp"
Run the script that we just developed:
.\NamedParameters.ps1 -SolutionPath "D:\Ironworks.SharePoint2010.Features.Core.wsp" -WebApp "http://ironworksdev.com" 
Output:
Solution Path: D:\Ironworks.SharePoint2010.Features.Core.wsp
Web App: http://ironworksdev.com
.\NamedParameters.ps1 -SolutionPath "D:\Ironworks.SharePoint2010.Features.Core.wsp" 
Output:
Solution Path: D:\Ironworks.SharePoint2010.Features.Core.wsp
Web App:
.\NamedParameters.ps1 -WebApp "http://ironworksdev.com" 
Output:
Solution Path:
Web App: http://ironworksdev.com

Hope that this helps someone.

No comments:

Post a Comment