从C#代码触发PS1文件。C#代码必须包装在exe中
我有一个powershell脚本,我想从EXE中触发它 已尝试或无法执行的操作:从C#代码触发PS1文件。C#代码必须包装在exe中,c#,powershell,exe,C#,Powershell,Exe,我有一个powershell脚本,我想从EXE中触发它 已尝试或无法执行的操作: 无法直接运行powershell,因为运行它的进程需要exe而不是powershell Powershell脚本相当复杂,因此将其移植到C#并不简单,而且非常耗时 PS2EXE可以工作,但由于安全策略而无法使用 试图在google上搜索如何为ps1文件创建exe,但找不到任何解决方案(ps2exe除外)。所以我决定尝试使用C#执行ps1,然后创建一个exe。然后将exe和powershell包装在同一msi中
- 无法直接运行powershell,因为运行它的进程需要exe而不是powershell李>
- Powershell脚本相当复杂,因此将其移植到C#并不简单,而且非常耗时
- PS2EXE可以工作,但由于安全策略而无法使用
- 试图在google上搜索如何为ps1文件创建exe,但找不到任何解决方案(ps2exe除外)。所以我决定尝试使用C#执行ps1,然后创建一个exe。然后将exe和powershell包装在同一msi中
Process p = new Process();
p.StartInfo = new ProcessStartInfo("powershell.exe");
p.StartInfo.Arguments = @"-Executionpolicy unrestricted C:\script\ms.ps1";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
上面的代码正在工作,但是它正在闪烁一个黑色的cmd窗口大约一毫秒
已从源代码中尝试以下代码:
与上述问题相同,黑色窗口闪烁几秒钟
回答以下任何问题都可以解决我的问题
您是否尝试过?在调用PowerShell时将-windowstyle添加到参数中。什么样的安全策略允许您运行home brewn C#应用程序,但不是Ps2Exe应用程序?那么它闪烁窗口的唯一问题是什么?您是否尝试过在调用PowerShell时将?Add-windowstyle隐藏到参数中。什么样的安全策略允许运行home brewn C#应用程序,而不是Ps2Exe应用程序?那么它闪烁窗口的唯一问题是什么?
string scriptText = System.IO.File.ReadAllText(@"C:\script\ms.ps1");
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
pipeline.Invoke();
runspace.Close();
string MyCommand = "-Command &{ if (!(Test-Path 'c:\\test')) {md 'c:\\test'; get-process | Out-File c:\\test\\MyFile.txt}}";
ProcessStartInfo MyProcInfo = new ProcessStartInfo();
MyProcInfo.FileName = "powershell.exe";
MyProcInfo.Arguments = MyCommand;
Process MyProcess = new Process();
MyProcess.StartInfo = MyProcInfo;
MyProcess.Start();
MyProcess.WaitForExit();