[Windows] PowerShell的執行原則變更

[Windows] PowerShell的執行原則變更

OS Version: Windows 10 Pro 1803

PowerShell Version: 5.1.17763.1

根據微軟官方的說明,PowerShell為了安全預設是不給任何Script程式執行的

The first implication of this philosophy is that PowerShell won’t execute scripts until you explicitly give it permission to do so. PowerShell has four execution policies that govern how it should execute scripts:

  • Restricted:

    PowerShell won’t run any scripts. This is PowerShell’s default execution policy.

  • AllSigned:

    PowerShell will only run scripts that are signed with a digital signature. If you run a script signed by a publisher PowerShell hasn’t seen before, PowerShell will ask whether you trust the script’s publisher.

  • RemoteSigned:

    PowerShell won’t run scripts downloaded from the Internet unless they have a digital signature, but scripts not downloaded from the Internet will run without prompting. If a script has a digital signature, PowerShell will prompt you before it runs a script from a publisher it hasn’t seen before.

  • Unrestricted:

    PowerShell ignores digital signatures but will still prompt you before running a script downloaded from the Internet.

因為如此,一開始不調整的話,你直接跑會出現錯誤

可以利用指令來確認目前的執行原則是哪一種

確認模式後可以在用指令修改成自己想要的(注意,這個指令的執行身分必須要是系統管理員身分開啟的PowerShell模式才能正常執行)

另外,直接在Powershell的指令模式下呼叫.PS1的執行檔,有時候會沒有出現任何訊息,或是出現找不到這個指令的問題

這個問題的原因大致上有兩種,一種是你的.PS1 Script檔案中本身就沒有呼叫(call)函式(function)來使用,也就是說你雖然定義了函式要如何執行和匯出資料,但卻沒有呼叫他,另一種是雖然你呼叫了,但在執行的時候並沒有把.PS1 Script檔案的路徑寫入PowerShell的環境變數內(就是Module的執行路徑),所以會發現雖然執行了卻沒有出現任何反應,解決的方法就看遇到哪一種問題來排除,如果是第二種類型,那解決的方法也有2種,這邊只說明最簡單和最快的方法

以上。

Reference

PowerShell因为在此系统中禁止执行脚本解决方法

Add-member for Powershell V2

Running PowerShell Scripts Is as Easy as 1-2-3

PowerShell function doesn’t produce output

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

Add a Comment