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

Start-Process

       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.

Example:

$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 

Invoke-Command

       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.
Example
$ScriptPath = "D:\Scripts\script.ps1"
$WebSiteName = 'MyWebSite'
$PathToDirectory ="D:\site\"

Executing option script 1

$script = [scriptblock]::create( @"
param(`$PathToDirectory,`$WebSiteName,`$Debug=`$False)
&{ $(Get-Content $ScriptPath -delimiter ([char]0)) } @PSBoundParameters
"@ )

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

Executing option script 2

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

Executing option script 3

Invoke-Command { 
    param($PathToDirectory,$WebSiteName,$Debug=$False)
    &$ScriptPath @PSBoundParameters
} -ArgumentList $PathToDirectory,$WebSiteName, $false 

No comments:

Post a Comment