0
私はpowershellスクリプトを実行しようとしていますが、私は2つの異なる方法を試しましたが、両方から例外があります。どのコードを追加する必要がありますか、何を変更する必要がありますか?PowershellスクリプトをC#で実行する例外、例外
スクリプト内でパラメータを追加しようとしています。
パイプライン(とParam([string]$MainDoc="not")
まずapproch)およびコマンド():このコードから
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.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());
}
}
このコードは例外を示します:
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()
これは私のOSプラットフォームで有効であるため、わかりません。
何が欠けていますか、何を変更する必要がありますか?これは簡単な作業で、1つの引数で1つのPowershellを実行するだけです。
事前
AnyCPUからx86または64bitに切り替えてみましたか? – Marco
これはおそらくあなたを助けることができます:https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ – Kage
第2のアプローチでは 'filePath'に何が含まれていますか?スクリプト名の場合は、 'UseShellExecute'をtrueに設定するか、PowerShell.exeを前に付けます。 –