2014-09-21 5 views
3

나는 runspace에서 매개 변수를 사용하여 Powershell 파일을 실행하려고 C#으로 시도하고 있습니다. 불행히도 나는 다음과 같은 결과를 얻는다 :C# Runspace Powershell (대화 형)

A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows. 

나는 무엇을 할 수 있을까?

현재 C# 코드. 이 명령은 PS 파일에 있고 json 문자열을 리턴해야하는 명령을 실행해야합니다.

public string ExecuteCommandDirect(int psId, string psMaster, string psFile) 
{ 
    String FullPsFilePath = @"C:\CloudPS\" + psFile + ".ps1"; 

    String PsParameters = FullPsFilePath + " -psId " + psId + " -psMaster " + psMaster + " -NonInteractive"; 

    // Create Powershell Runspace 
    Runspace runspace = RunspaceFactory.CreateRunspace(); 

    runspace.Open(); 

    // Create pipeline and add commands 
    Pipeline pipeline = runspace.CreatePipeline(); 
    pipeline.Commands.AddScript(PsParameters); 

    // Execute Script 
    Collection<PSObject> results = new Collection<PSObject>(); 
    try 
    { 
     results = pipeline.Invoke(); 
    } 
    catch (Exception ex) 
    { 
     results.Add(new PSObject((object)ex.Message)); 
    } 

    // Close runspace 
    runspace.Close(); 

    //Script results to string 
    StringBuilder stringBuilder = new StringBuilder(); 
    foreach (PSObject obj in results) 
    { 
     Debug.WriteLine(obj); 
     stringBuilder.AppendLine(obj.ToString()); 
    } 

    return stringBuilder.ToString(); 

} 

PS 코드 : 당신이 제몫을 pshost의 존재를 필요로 쓰기 호스트와 같은 중요하지 않은 cmdlet을 사용하는 스크립트를 실행해야하는 경우

param([int]$psId = 0, [string]$psMaster = 'localhost'); 

$date = Get-Date -Format 'h:m:s' | ConvertTo-Json; 

Write-Host $date; 

exit; 
+0

당신이 사용하고있는 코드를 게시 할 수 :

원래 cmdlet을 사용해야 할 경우, 이것을 사용? – DanM7

+1

안녕하세요, 코드를 추가했습니다. – user2702653

+0

'Write-Host'를 제거하려고하면'$ date' 만 남겨 두십시오. 'exit'도 필요하지 않습니다. –

답변

5

사용 Write-Output 대신 Write-Host

+0

내가 봤 거든, 내가 클릭, 나는이 대답을 스크롤하고 보았다. -Host에서 -Output으로 전환하고 OP가 게시 한 오류 메시지가 표시되지 않습니다. 이 대답은 정확할뿐만 아니라 간결하고 도움이됩니다. – Benrobot

+0

완벽하게 작동했습니다. – Anand

1

이 두 가지 cmdlet을 재정 의하여 Read-Host 및 Write-Host에 대해이 문제를 직접 해결했습니다. 필자의 솔루션에서는 Write-Host로 보낸 모든 것을 자동으로 삭제하지만 Read-Host를 구현해야합니다. 이것은 새로운 powershell 프로세스를 시작하고 그 결과를 되돌립니다.

 string readHostOverride = @" 
      function Read-Host { 
       param(
        [string]$Prompt 
       ) 



       $StartInfo = New-Object System.Diagnostics.ProcessStartInfo 
       #$StartInfo.CreateNoWindow = $true 
       $StartInfo.UseShellExecute = $false 
       $StartInfo.RedirectStandardOutput = $true 
       $StartInfo.RedirectStandardError = $true 
       $StartInfo.FileName = 'powershell.exe' 
       $StartInfo.Arguments = @(""-Command"", ""Read-Host"", ""-Prompt"", ""'$Prompt'"") 
       $Process = New-Object System.Diagnostics.Process 
       $Process.StartInfo = $StartInfo 
       [void]$Process.Start() 
       $Output = $Process.StandardOutput.ReadToEnd() 
       $Process.WaitForExit() 
       return $Output.TrimEnd() 
      } 
     "; 

     string writeHostOverride = @" 
      function Write-Host { 
      } 
     "; 

     Run(readHostOverride); 
     Run(writeHostOverride); 

Run()은 놀라운 방법으로 powershell을 실행하는 방법입니다.

Write-Host를 구현하기 위해 이것을 쉽게 확장 할 수 있습니다. 어려움이 있으면 알려주세요.

의견 작성자가 Write-Host 대신 Write-Output (쓰기 - 출력)으로 전환하라는 제안을하는 경우 많은 유스 케이스의 해결책이 아닙니다. 예를 들어, 출력 스트림에 사용자 알림을 보내지 않을 수도 있습니다.

Microsoft.PowerShell.Utility\Read-Host -Prompt "Enter your input"