【问题标题】:Run a File, located in Program Files (x86) from PowerShell从 PowerShell 运行位于 Program Files (x86) 中的文件
【发布时间】:2021-11-08 17:03:31
【问题描述】:

我从 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# 代码中)我收到以下错误消息。

术语“x86”未被识别为 cmdlet、函数、脚本文件或可执行程序的名称。 程序。检查名称的拼写,或者路径是否正确(如果包含),然后 重复这个过程。

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

【问题讨论】:

  • @vonPryz 编辑了我的帖子并提供了更多信息
  • @vonPryz 更新我的代码
  • AddScript 需要脚本的内容,而不是脚本的路径。
  • $ScriptPath = "&amp; '$ScriptPath'"?
  • @iRon 你的回答。我发现,从 C# 调用脚本时会发生错误。脚本很好,它只是 Powershell,找不到“程序文件(x86)”路径。意味着脚本根本没有被执行,因为 Powershell 找不到它。

标签: c# powershell path script


【解决方案1】:

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

我的 Powershell 脚本很好,没有错误。 但是当从路径运行文件时,其中有空格,它需要特殊的格式。 就像@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
        }        
}

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多