如果从 C# 代码启动,PowerShell 脚本无法确定文件路径

PowerShell Script not able to determine file paths if launched from c# code

我正在 运行使用 C# 创建 PowerShell 脚本。构建无法确定脚本中写入的不同文件路径,但如果我从命令行使用 运行 脚本,它工作正常。

这是我的 运行ning 脚本代码:

 private const string ScriptPath = "F:\";
 private const string SubPath = "build\Build.ps1";

 public Collection<PSObject> ExecuteBuildScript(BuildParams buildParams)
        {
            string executablePath = String.Empty;
            string[] subdirectories = Directory.GetDirectories(ScriptPath);
            Collection<PSObject> psOutput = null;

            //Get path of appropriate branch
            foreach (var subdirectory in subdirectories)
            {
                if (subdirectory.Contains(buildParams.Branch))
                {
                    executablePath = subdirectory;
                    break;
                }
            }


            if (!String.IsNullOrEmpty(executablePath))
            {
                using (PowerShell ps = PowerShell.Create())
                {
                    //Enable the powershell execution on the system
                    Runspace runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();
                    RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
                    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

                    ps.AddScript(Path.Combine(executablePath, SubPath));
                    ps.AddParameter("kit", !string.IsNullOrEmpty(buildParams.Kit) ? buildParams.Kit : "3CLogic");
                    ps.AddParameter("config", !string.IsNullOrEmpty(buildParams.Config) ? buildParams.Config : "Release");
                    ps.AddParameter("version", !string.IsNullOrEmpty(buildParams.ClientVersion) ? buildParams.ClientVersion : "latest");
                    ps.AddParameter("revision", !string.IsNullOrEmpty(buildParams.ClientRevision) ? buildParams.ClientRevision : "latest");
                    ps.AddParameter("serviceversion", !string.IsNullOrEmpty(buildParams.ServiceVersion) ? buildParams.ServiceVersion : "latest");
                    psOutput = ps.Invoke();

                    // check the other output streams (for example, the error stream)
                    if (ps.Streams.Error.Count > 0)
                    {
                        Console.WriteLine(ps.Streams.Error[0]);
                        // error records were written to the error stream.
                        // do something with the items found.
                    }

                }
            }
            return psOutput;
        }

假设我想从被调用的脚本中导入另一个脚本,它只是无法获取路径。从 build.ps1 导入 include.ps1 的示例只是不起作用,而且 Get-Location 选择 IIS 服务器位置的位置。

. build\include.ps1

使用 $MyInvocation 变量确定当前脚本目录并使用 Join-Path cmdlet 组合路径:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
. (Join-Path $scriptPath 'build\include.ps1')