【发布时间】:2016-07-31 14:00:04
【问题描述】:
由于目前没有可用的 PSFiddle,我想知道是否可以通过将 PS 代码包装在 C# 中来使用 DotNetFiddle。
我使用了以下代码:
using System;
using System.Collections.ObjectModel;
using System.Management.Automation; //if run on your machine, first ensure Windows SDK is installed (https://www.microsoft.com/en-us/download/details.aspx?id=11310)
public class Program
{
public static void Main()
{
string script = @"
param([string]$name)
""hello $name"" #NB:Double quotes have to be escaped; otherwise all's good
";
RunPSScript(script);
}
private static void RunPSScript(string script) {
using (PowerShell ps = PowerShell.Create())
{
ps.AddScript(script);
ps.AddParameter("name", "Player One");
Collection<PSObject> psOutput = ps.Invoke();
foreach(PSObject item in psOutput) {
if(item != null) {
Console.WriteLine(item.BaseObject.ToString());
}
}
}
}
}
在 DotNetFiddle 中运行时会引发 System.Security.SecurityException 错误。
可以在这里找到:https://dotnetfiddle.net/B4JLU0
代码在我的本地机器上运行时有效,所以我认为问题是由于 DotNetFiddle 上的安全问题。
问题
是否有解决方法来允许/避免异常;或者这根本不可能?
【问题讨论】:
-
在选择
RunspaceFactory类型初始化程序后,我可以说由于 P/Invoke 调用而发生异常,这会在SecurityPermission(SecurityPermissionFlag.UnmanagedCode)权限上生成完整的Demand。由于它是非常敏感的权限,因此不太可能授予沙箱,该服务用于调用您的代码。
标签: c# powershell securityexception .net-fiddle