2013-05-09 119 views
70

我運行此代碼從一個asp.net應用程序執行電源外殼:.ps1無法加載,因爲在此係統上禁用了腳本的執行?

System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); 
runspace.Open(); 
System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline(); 
pipeline.Commands.AddScript(@"\\servername\path"); 

pipeline.Commands.Add("Out-String"); 

Collection<PSObject> results = pipeline.Invoke(); 

runspace.Close(); 

但我得到的錯誤:

.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.

相同的代碼運行在命令提示符下或Windows罰款(winform)應用程序。

回答

84

由於execution policy,您的腳本被阻止執行。

您需要在客戶端PC上將其設置爲Unrestricted。你可以通過調用Invoke來做到這一點

Set-ExecutionPolicy Unrestricted 
+3

這不適合我。嗯,實際上如果你把它設置爲32位和64位,它確實能工作。 – 2016-02-12 08:45:28

18

問題是,執行策略是在每個用戶的基礎上設置的。你需要在你的應用程序每次運行時運行以下命令它,使其能夠工作:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned 

有可能是設置此爲ASP.NET用戶還有一種方式,但這種方式意味着你不打開你的整個系統,只是你的應用程序。

Source

+0

這對我來說是完美的答案。而不是始終啓用它,只是啓用它爲您想要的功能,然後它重置。 – Tschallacka 2016-12-15 07:18:55

6

你需要運行設置executionpolicy:

Set-ExecutionPolicy Unrestricted <-- Will allow unsigned powershell scripts to run. 

Set-ExecutionPolicy Restricted <-- Will not allow unsigned powershell scripts to run. 

Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed powershell scripts to run. 

希望這有助於!

51

在某些情況下,您可以按照其他答案中建議的步驟操作,驗證執行策略設置是否正確,並且腳本仍然失敗。如果發生這種情況,那麼您可能位於一臺裝有32位和64位版本的PowerShell的64位計算機上,並且在沒有執行策略集的版本上發生故障。 該設置不適用於兩個版本,因此您必須將其明確設置兩次。

在您的Windows目錄中查找System32和SysWOW64。

重複這些步驟爲每個目錄:

  1. 導航到WindowsPowerShell \ v1.0和推出powershell.exe
  2. 檢查ExecutionPolicy當前設置:

    Get-ExecutionPolicy -List

  3. 設置你想要的級別和範圍的ExecutionPolicy,例如:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

請注意,您可能需要運行PowerShell中的因您要設置策略的範圍管理員。

你可以閱讀了很多在這裏:Running Windows PowerShell Scripts

+3

這是最好的答案 – 2016-02-12 08:49:26

+2

** Set-ExecutionPolicy -Scope Process Unrestricted **適用於我 – daniel 2016-03-16 09:22:56

+3

Set-ExecutionPolicy -Scope CurrentUser無限制爲我工作 – Jignesh 2016-04-13 08:53:39

1

我也有類似的問題,並指出Windows Server 2012中的默認CMD正在運行的64位之一。

對於Windows 7,Windows 8中,Windows Server 2008的R2或Windows Server 2012,運行下面的命令作爲管理員:

打開C:\的Windows \ Syswow64資料\ cmd.exe的 運行命令:PowerShell的SET-ExecutionPolicy RemoteSigned就是

打開C:\ WINDOWS \ SYSTEM32 \ cmd.exe的 運行命令的PowerShell設置ExecutionPolicy RemoteSigned就是

可以使用

在CMD檢查模式:回聲%PROCESSOR_ARCHITECTURE% 在PowerShell中:[環境] :: Is64BitProcess

我希望這可以幫助您。

相關問題