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 with both parameters "SolutionPath" and "WebApp":
.\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
Run the script that we just developed with parameter "SolutionPath" only:
.\NamedParameters.ps1
-SolutionPath "D:\Ironworks.SharePoint2010.Features.Core.wsp"
Output:
Solution Path: D:\Ironworks.SharePoint2010.Features.Core.wsp
Web App:
Run the script that we just developed with parameter "WebApp" only:
.\NamedParameters.ps1
-WebApp "http://ironworksdev.com"
Output:
Solution Path:
Web App: http://ironworksdev.com
Hope that this helps someone.
ICF Ironworks is always on the lookout for experienced professionals who believe in hard work, having fun, and great client service.
All things are difficult before they are easy.
Posted by: Gucci Outlet | 05/19/2011 at 10:09 PM
Thanks for sharing your ideas. Keep on blogging because we will benefit from your articles. thx a lot!
Posted by: Burberry Bags Outlet | 08/17/2011 at 11:38 PM
Lately I came to your website and have been reading along. I thought I would leave my initial comment. Keep writing, because your posts are impressive!
Posted by: Smart Home | 12/09/2011 at 11:06 AM