2016-09-19 49 views
1

我正在使用C#運行PowerShell腳本。構建不能確定腳本中寫入的不同文件路徑,但如果我從命令行運行腳本,它工作正常。PowerShell腳本無法確定從c#代碼啓動時的文件路徑

這裏是我的運行腳本代碼:

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; 
     } 

讓我們說,我想導入調用的腳本另一個腳本,它只是未能獲得路徑。示例導入include.ps1build.ps1只是不工作,還Get-Location挑選IIS服務器位置的位置。

. build\include.ps1 

回答

0

使用$MyInvocation變量來確定當前的腳本目錄,並使用Join-Path cmdlet的結合路徑:

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

謝謝@馬丁......搞到現在工作:) –

相關問題