運行PowerShell腳本有兩種方式.
在運行任何腳本文件之前, 你都必須首先設置一個恰當的Execution Policy.
PowerShell腳本跟Windows CMD一樣, 和MS-DOS批處理一樣, 文件需要被保存為.ps1后綴名, 比如說myscript.ps1
最通常的運行腳本的方法是調用它:
PS C:\> & "C:\Belfry\My first Script.ps1"
注意: 這里的"&"操作符能允許你調用一個命令, 腳本, 或函數. 比如:
PS C:\> & "C:\Program files\mycommand.exe"
PS C:\> $runMyProg = "C:\Program files\mycommand.exe"
PS C:\> & $runMyProgPS C:\> $myPing = Get-Command -commandType Application Ping
PS C:\> & $myPing
如果路徑不包含任何的空格, 那么你就可以忽略引號和'&'操作符.
PS C:\> C:\Belfry\Myscript.ps1
如果腳本就在當前路徑下, 你必須使用符號".\"來告訴PowerShell該腳本就在當前路徑下.
PS C:\> .\Myscript.ps1
Dot Sourcing
=====================
當使用上面的語法執行腳本的時候, 腳本中定義的變量和函數會在腳本運行結束后消失.
但, 如果你使用dot sourcing來運行腳本的時候, 所有腳本中定義的變量和函數會在腳本運行結束后依然存在.
舉例運行dot-sourcing腳本.
PS C:\> . "C:\Belfry\My first Script.ps1"
舉例運行dot-sourcing在當前路徑下的腳本.
PS C:\> . .\Myscript.ps1"
參考資料
=====================
Run a PowerShell script
http://ss64.com/ps/syntax-run.html
Using the Set-ExecutionPolicy Cmdlet