运行 一个文件,位于 PowerShell 的 Program Files (x86) 中

Run a File, located in Program Files (x86) from PowerShell

我 运行 来自 C# 的脚本:代码如下所示:

r.Open();
                using (PowerShell ps = PowerShell.Create().AddScript(_scriptPath))
                {
                    ps.Runspace = r;
                    ps.Invoke();
                    if (ps.HadErrors)
                    {
                        List<string> _items = new List<string>();
                        var errorMessage = new StringBuilder();
                        foreach (ErrorRecord err in ps.Streams.Error)
                        {
                            errorMessage.AppendLine(err.ToString());
                        }

                        _items.Add(errorMessage.ToString());
                    
                        foreach (var i in _items)
                        {
                            MessageBox.Show(i);
                        }
                    }                       
                }

在脚本中我尝试 运行 复制项目,为此我需要一个路径 :

脚本路径是这样的:

$ScriptPath = Split-Path $Script:MyInvocation.MyCommand.Path 

通过 Write-Host 我得到了路径,如下所示:

C:\Program Files (x86)\some\random\Folder\File.ps1

使用 Ps.Streams.Error(在我的 C# 代码中),我收到以下错误消息。

The term "x86" was not recognized as the name of a cmdlet, function, script file, or executable program. program. Check the spelling of the name, or that the path is correct (if included), and then repeat the procedure.

我需要如何编写我的代码,以便 Powershell 理解我的路径?

所以我找到了解决方案,或者更好的解决方案:)

我的 Powershell 脚本没问题,没有错误。 但是当 运行 来自 Path 的文件中有空格时,它需要特殊的 Formation。 就像@iRon 写的那样。

但不在脚本中,在 C# 代码中调用 PS 脚本时需要它。

我的路径是这样的:

C:\Program Files (x86)\some\random\Folder\File.ps1

但是应该看起来像这样执行:

& 'C:\Program Files (x86)\some\random\Folder\File.ps1'

在代码中添加了“&'脚本'”:

private void executeScripts()
{
        string _dirPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        string _sPath = Path.GetDirectoryName(_dirPath) + @"\ExecuteScripts\DistributeFiles.ps1";
        string _scriptPath = "& '" + _sPath + "'";   //  <- This is where i added the Formation

        Trace.TraceWarning(_scriptPath);

        using (PowerShellProcessInstance pspi = new PowerShellProcessInstance())
        {
          //rest of the Code in my Post
        }        
}

愚蠢的错误让我安静了几个小时-.-

但我很高兴我找到了它。谢谢