Thursday, 17 April 2014

How to call and pass parameter from one PowerShell script file to another?

I came across a scenario where I have to call another PowerShell script file and pass the current PowerShell script file input parameter to this second file.

PowerShell as the name says is very powerful and I was able to achieve my requirement with a simple expression called as "Invoke-Expression" in PowerShell.

Just to explain you how I have achieved my above requirement, I have created two demo PowerShell files called First.ps1 and Second.ps1. I am gonna show you how I have called First.ps1 and invoke the Second.ps1and pass the First.ps1 input parameter to the Second.ps1 with "Invoke-Expression".

clear-Host
$snapin = Get-PSSnapin | Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" }
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin..."
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
Write-Host "First!!"
$name = $(Read-Host -Prompt "Enter your Name:")
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
Invoke-Expression "$PSScriptRoot\Second.ps1 $name"
view raw First.ps1 hosted with ❤ by GitHub

param
(
[string]$name
)
if($name)
{
Write-Host "Welcome $name from second file"
}
else
{
Write-Host "Nothing!!"
}
view raw Second.ps1 hosted with ❤ by GitHub

Hope this is helpful.
Cheers!!
Isha Jain