用C#运行Powershell脚本,例外
问题描述:
我想运行一个powershell脚本,我尝试了两种不同的方法,但从两个方面都得到了异常。我需要添加哪些代码或需要更改哪些内容?用C#运行Powershell脚本,例外
脚本内我试图添加一个参数;
Param([string]$MainDoc="not")
首先计算策略与管道()和命令():
System.Management.Automation.Host.HostException: Cannot invoke this function because the current host does not implement it.
at System.Management.Automation.Internal.Host.InternalHostRawUserInterface.ThrowNotInteractive()
at System.Management.Automation.Internal.Host.InternalHostRawUserInterface.get_ForegroundColor()
at Microsoft.PowerShell.Commands.ConsoleColorCmdlet.get_ForegroundColor()
at Microsoft.PowerShell.Commands.WriteHostCommand.PrintObject(Object o)
at Microsoft.PowerShell.Commands.WriteHostCommand.PrintObject(Object o)
at Microsoft.PowerShell.Commands.WriteHostCommand.ProcessRecord()
at System.Management.Automation.Cmdlet.DoProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
与过程第二种方法()::
public static void RunPowerShell(string filePath, string parameterValue, string parameterName)
{
try
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = filePath;
p.StartInfo.Arguments = " -" + parameterName + " " + parameterValue;
p.Start();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.GetBaseException());
}
}
public static void RunPowerShell(string filePath, string parameterValue, string parameterName)
{
try
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
Command command = new Command(filePath);
CommandParameter argParam = new CommandParameter(parameterName, parameterValue);
command.Parameters.Add(argParam);
pipeline.Commands.Add(command);
pipeline.Invoke();
runspace.Close();
}catch(Exception e){
System.Diagnostics.Debug.WriteLine(e.GetBaseException());
}
}
从该代码的异常
此代码给出例外:
System.ComponentModel.Win32Exception (0x80004005): The specified executable is not a valid application for this OS platform.
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
我只是不明白,因为它应该适用于我的操作系统平台。
我错过了什么,应该改变什么?这应该是一个简单的任务,只用一个参数运行一个Powershell。
日Thnx提前
答
答案,帮助用Powershell.exe到它前面加上下面的代码。 filePath包含PowerShell脚本的路径,parameterValue包含PowerShell脚本参数的值。
public static void RunPowerShell(string filePath, string parameterValue)
{
try
{
Process.Start("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Powershell.exe", "" + filePath + " '" + parameterValue + "'");
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.GetBaseException());
}
}
你试过从AnyCPU切换到x86或64位,看它是否运行? – Marco
也许这可以帮助你:https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ – Kage
在第二种方法中'filePath'包含了什么。如果它是脚本名称,请将UseShellExecute设置为true,或者使用PowerShell.exe对其进行前缀。 –