【问题标题】:How to add a script.ps1 in C# proiect如何在 C# 项目中添加 script.ps1
【发布时间】:2015-10-21 19:20:01
【问题描述】:

我在我的项目资源中添加了 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

【问题讨论】:

    标签: c# powershell dll process resources


    【解决方案1】:

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

    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
        }
    };
    

    【讨论】:

    • 第一个示例工作正常,但我不想在磁盘上创建文件。我有一个多行脚本,所以我不能使用第二个示例。
    猜你喜欢
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多