在 C# 中运行脚本,可以采用 .NET 提供的 .NET Core 运行时 (runtime) 和其他相关技术和工具来实现。
using System;
using System.IO;
static void Main(string[] args)
{
Stream scriptStream = File.OpenWrite("script.sh");
using (StreamWriter writer = new StreamWriter(scriptStream))
{
writer.WriteLine("#!/bin/sh");
writer.WriteLine("echo 'Hello, world!'");
}
}
~ -> ls
-rwxr-xr-x 1 root root 12396 May 23 21:24 script.sh
-rwxr-xr-x 1 root root 2837986 May 23 21:24 Runner.dll
将需要执行的脚本转换为可在 PowerShell 命令行中运行的格式 (例如:将脚本放在脚本文件中),接着调用 PowerShell 命令行(cmd.exe)执行脚本。具体可以参考以下步骤:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"path/to/script.ps1";
using (StreamReader reader = new StreamReader(System.IO.StreamReader(path)))
{
string command = reader.ReadLine();
while (command != null)
{
Console.WriteLine(command);
command = reader.ReadLine();
}
}
}
static void Main()
{
string path = @"path/to/script1.ps1";
using (StreamReader reader = new StreamReader(System.IO.StreamReader(path)))
{
string command = reader.ReadLine();
while (command != null)
{
Console.WriteLine(command);
command = reader.ReadLine();
}
}
string path = @"path/to/script2.ps1";
using (StreamReader reader = new StreamReader(System.IO.StreamReader(path)))
{
string command = reader.ReadLine();
while (command != null)
{
Console.WriteLine(command);
command = reader.ReadLine();
}
}
}
}
以上两种方法实现了在 C# 中运行脚本。在编写代码时,需要注意脚本的可读性和安全性等问题。
领取专属 10元无门槛券
手把手带您无忧上云