Thursday, 3 October 2013

Executing scripts / files using powershell

Note: PS refers to PowerShell

Powershell has 2 main ways I have tested how to execute scripts.
  1.        Start-Process
  2.        Invoke-Command


       After research, and using in example i have found it is ill-suited to run commands with arguments, unless you construct everything in one command and then execute. You can get only one set of results and you need to add additional logic in order to pass messages to parent window.


$ScriptPath = "D:\Scripts\script.ps1"
$WebSiteName = 'MyWebSite'
$PathToDirectory ="D:\site"

#Definition of AllArguments (keep in mind the quotes) 
$AllArgument = '-ExecutionPolicy Unrestricted -file "' + $ScriptPath + '" 
-IsRunAsAdmin -args ' + "$WebSiteName, $PathToDirectory" 

$AdminProcess = Start-Process "$PsHome\PowerShell.exe" -WindowStyle Maximized  -Verb RunAs -ArgumentList $AllArgument -PassThru 
# Access the process by ID and wait for its end
Wait-Process $AdminProcess.Id 


       Is used mosty of running command as part of a script where there is no need for user interaction. All output is directed into one window unless specified otherwise.
$ScriptPath = "D:\Scripts\script.ps1"
$WebSiteName = 'MyWebSite'
$PathToDirectory ="D:\site\"

Executing option script 1

$script = [scriptblock]::create( @"
&{ $(Get-Content $ScriptPath -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args $PathToDirectory,$WebSiteName, $false

Executing option script 2

icm { 
    D:\Scripts\script.ps1 @PSBoundParameters
} -ArgumentList $PathToDirectory,$WebSiteName, $false
NOTE: icm is same as Invoke-Command

Executing option script 3

Invoke-Command { 
    &$ScriptPath @PSBoundParameters
} -ArgumentList $PathToDirectory,$WebSiteName, $false