2017-06-02 82 views
4

我已經使用以下代碼來獲取執行策略併成功檢索它。如何從C#獲取ExecutionPolicy?

碼塊1:

using (var powerShellInstance = PowerShell.Create()) 
{ 
    powerShellInstance.AddCommand("Get-ExecutionPolicy"); 
    Collection<PSObject> obj = powerShellInstance.Invoke(); 
} 

問題是,當我從PowerShell的改變ExecutionPolicy,它不反映在C#。

但是,如果我從C#更改ExecutionPolicy,那麼它被反映。我已經使用下面的代碼來更改ExecutionPolicy。

碼塊2:使用代碼塊1
從改變了ExecutionPolicy爲旁路

檢索的ExecutionPolicy如C#無限制

using (var powerShellInstance = PowerShell.Create()) 
{ 
    powerShellInstance.AddCommand("Set-ExecutionPolicy").AddArgument("ByPass"); 
    powerShellInstance.Invoke(); 
} 

例如,考慮以下情形PowerShell窗口並使用代碼塊1在C#中進行了測試,它將檢索ExecutionPolicy作爲無限制
Change ExecutionPolicy as Bypass using the C#code block 2 and using in C#using the code block 1,it retrieve ExecutionPolicy as Bypass

+0

的設置存儲在HKLM下的註冊表| HKCU \ SOFTWARE \ Microsoft \ PowerShell \ 1 \ ShellIds \ Microsoft.PowerShell –

回答

1

範圍

Set-ExecutionPolicy -Scope CurrentUser 
Set-ExecutionPolicy -Scope LocalMachine 
Set-ExecutionPolicy -Scope MachinePolicy 
Set-ExecutionPolicy -Scope Process 
Set-ExecutionPolicy -Scope UserPolicy 

相信默認範圍是Process(因此您的問題)

+0

這應該是真的。然而,對於Set-ExecutionPolicy的幫助表示默認值不同('LocalMachine'),但我真的懷疑這一點 - 默認情況下使用機器拋出set-executionpolicy的風險足夠高。也可能無法設置本地計算機策略cmdlet將範圍更改爲處理範圍。 – Vesper

+0

太好了,我已將範圍更改爲CurrentUser,然後進行測試,工作正常。 –