如何在C#proiect中添加script.ps1

时间:2015-07-30 12:22:32

标签: c# powershell dll process resources

我在我的项目资源中添加了script3.ps1文件。 我构建了dll文件。

我想用script.ps1启动一个PowerShell进程。 我试过了

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "powershell.exe",
        Arguments = "-ExecutionPolicy ByPass -Command \".'"+MyProject.Properties.Resources.script3+"'",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

我收到了错误:

the term 'system.byte[]' is not recognized as the name of a cmdlet, 
function, script file or operable program. check the spelling of the name, or if
a path was included, verify that path is correct and try again. at line : 1 char

1 个答案:

答案 0 :(得分:3)

首先将资源内容保存到文件中:

File.WriteAllBytes("file3.ps", MyProject.Properties.Resources.script3);
var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "powershell.exe",
        Arguments = "-ExecutionPolicy ByPass -Command \".\\file3.ps\"",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

或者如果它的单行只转换为字符串:

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "powershell.exe",
        Arguments = "-ExecutionPolicy ByPass -Command \""+Encoding.Default.GetString(MyProject.Properties.Resources.script3)+"\"",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};