如何使用c#中设置的字符串列表来运行powershell命令?
本文关键字:运行 powershell 命令 列表 字符串 何使用 设置 | 更新日期: 2023-09-27 17:54:03
这个按钮与原始代码一起工作,但我想把命令作为字符串列表(代码的第二部分):
private void button_Click(object sender, RoutedEventArgs e)
{
var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
newProcessInfo.FileName = @"C:'Windows'System32'WindowsPowerShell'v1.0'powershell.exe";
newProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
newProcessInfo.Verb = "runas";
newProcessInfo.Arguments = @"-executionpolicy unrestricted -Command ""C:'Windows'notepad.exe""";
System.Diagnostics.Process.Start(newProcessInfo);
}
下面是我尝试将它作为字符串列表,但由于某些原因它无法工作:
private void button_Click(object sender, RoutedEventArgs e)
{
List<string> strings = new List<string>();
strings.Add("'"C:''Windows''notepad.exe'"");
System.Diagnostics.ProcessStartInfo[] arrayProcessInfo = new System.Diagnostics.ProcessStartInfo[strings.Count()];
for (int i = 0; i < strings.Count(); i++)
{
arrayProcessInfo[i] = new System.Diagnostics.ProcessStartInfo();
arrayProcessInfo[i].FileName = @"C:'Windows'System32'WindowsPowerShell'v1.0'powershell.exe";
//I commented this out to see if it could show me an error
//arrayProcessInfo[i].WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
arrayProcessInfo[i].Verb = "runas";
//I wanted to see the error but not sure if I need to use something other than -noexit in the command line
arrayProcessInfo[i].Arguments += @"-executionpolicy unrestricted -Command -noexit " + strings[i] + "";
System.Diagnostics.Process.Start(arrayProcessInfo[i]);
//MessageBox.Show(strings[i]); //This does show the string output when not commented out
}
}
我确实尝试过这个,它工作,但希望它是一个字符串列表:
private void button_Click(object sender, RoutedEventArgs e)
{
string string1 = "'"C:''Windows''notepad.exe'"";
var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
newProcessInfo.FileName = @"C:'Windows'System32'WindowsPowerShell'v1.0'powershell.exe";
newProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
newProcessInfo.Verb = "runas";
//newProcessInfo.Arguments = @"-executionpolicy unrestricted -Command ""C:'Windows'notepad.exe""";
newProcessInfo.Arguments = @"-executionpolicy unrestricted -Command " + string1 +"";
System.Diagnostics.Process.Start(newProcessInfo);
}
这是经过大量测试后的结果。
string[] strings = new string[1];
strings[0] = "C:''Windows''notepad.exe'"";
System.Diagnostics.ProcessStartInfo[] arrayProcessInfo = new System.Diagnostics.ProcessStartInfo[strings.Count()];
for (int i = 0; i < strings.Count(); i++)
{
arrayProcessInfo[i] = new System.Diagnostics.ProcessStartInfo();
arrayProcessInfo[i].FileName = @"C:'Windows'System32'WindowsPowerShell'v1.0'powershell.exe";
arrayProcessInfo[i].WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
arrayProcessInfo[i].Verb = "runas";
arrayProcessInfo[i].Arguments += @"-executionpolicy unrestricted -Command " + strings[i] + "";
System.Diagnostics.Process.Start(arrayProcessInfo[i]);
}