Powershell: How do I execute a script in a new Powershell instance?

The great thing about PS is that is caches its objects for reuse. The bad thing about PS is that is caches its objects for reuse. Sometimes, scripts need to be executed in their own PS instances in order to avoid any changed data.

Here is a simple example of a wrapper script (wrapper.ps1) that executes another script (test.ps1) in the same folder. The test script open notepad with the SchemaXml of a document library.

Wrapper.ps1:
function Get-ScriptDirectory 
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value 
 Split-Path $Invocation.MyCommand.Path 

$dir = Get-ScriptDirectory
cd "$dir"

powershell.exe "& `"$dir\test.ps1`" "

Test.ps1:
function AddSharePointSnapin([bool] $addSnapin)
{
    $sharePointSnapinName = "Microsoft.SharePoint.PowerShell"
    If ($addSnapin)
    {
        Write-Host "Adding $sharePointSnapinName Snapin ..."
        Add-PSSnapin $sharePointSnapinName -ErrorAction SilentlyContinue
    }
    Else
    {
        Write-Host "Removing $sharePointSnapinName Snapin ..."
        Remove-PSSnapin $sharePointSnapinName -ErrorAction SilentlyContinue
    }
}

AddSharePointSnapin $true

$fileName = "doclib.txt"
$web = Get-SPWeb "http://docreval.in.telstra.com.au"
$list = $web.Lists["Documents"]
$list.SchemaXml > $fileName 
Start-Process notepad  -ArgumentList $fileName

Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

How can I call a JIRA api through Powershell?