Friday, July 26, 2013

how to run ps1 file from powershell

There are two ways to run a PowerShell script.
Before running any scripts on a new PowerShell installation, you must first set an appropriate Execution Policy, e.g. Set-ExecutionPolicy RemoteSigned
A PowerShell script is the equivalent of a Windows CMD or MS-DOS batch file, the file should be saved with a .ps1 extension, e.g. MyScript.ps1
The most common (default) way to run a script is by calling it:
PS C:\> & "C:\Belfry\My first Script.ps1"
If the path does not contain any spaces, then you can omit the quotes and the '&' operator
PS C:\> C:\Belfry\Myscript.ps1
If the script is in the current directory, you must indicate this using .\ (or ./ will also work)
PS C:\> .\Myscript.ps1
When you invoke a script using the syntax above, variables and functions defined in the script will disappear when the script ends.1

Dot Sourcing

When you dot source a script, all variables and functions defined in the script will persist even when the script ends.
Run a script by dot-sourcing it:
PS C:\> . "C:\Belfry\My first Script.ps1"
Dot-sourcing a script in the current directory:
PS C:\> . .\Myscript.ps1"

Run a CMD batch file

Run a batch script from PowerShell:
PS C:\> ./demo.cmd

If the batch script contains any internal commands then it must be run by calling the CMD.exe shell and passing the batch file:
PS C:\> C:\windows\system32\cmd /c c:\batch\demo.cmd
Note, this works for .cmd but not .bat files.

Run a VBScript file

Run a vb script from PowerShell:
PS C:\> cscript c:\batch\demo.vbs

The System Path

If you run a script (or even just enter a command) without specifying the fully qualified path name, PowerShell will search for it as follows:
Firstly it will look at currently defined aliases, then currently defined functions and lastly commands located in the system path.
1unless they are explicitly defined as globals: Function SCOPE:GLOBAL or Filter SCOPE:GLOBAL or Set-Variable -scope "Global"

1 comment:

  1. How to run a script.ps1 file in Visual WebPart directly ?
    i am a C# developer and new to share point ,

    please explain me all the steps to do it..

    Like process.start etc...


    Thanks in advance,
    Vaidhya.P

    ReplyDelete