2016-04-23 13 views
0
public string RunScript(string scriptText) 
{ 
    Runspace runspace = RunspaceFactory.CreateRunspace(); 
    runspace.Open(); 

    Pipeline pipeline = runspace.CreatePipeline(); 
    pipeline.Commands.AddScript(scriptText); 

    pipeline.Commands.Add("Out-String"); 

    Collection<PSObject> results = pipeline.Invoke(); 

    runspace.Close(); 

    StringBuilder stringBuilder = new StringBuilder(); 
    foreach (PSObject obj in results) 
    { 
     stringBuilder.AppendLine(obj.ToString()); 
    } 

    return stringBuilder.ToString(); 
} 

public string LoadScript(string filename) 
{ 
    try 
    { 

     using (StreamReader sr = new StreamReader(filename)) 
     { 

      StringBuilder fileContents = new StringBuilder(); 

      string curLine; 

      while ((curLine = sr.ReadLine()) != null) 
      { 

       fileContents.Append(curLine + "\n"); 
      } 

      return fileContents.ToString(); 
     } 
    } 
    catch (Exception e) 
    { 

     string errorText = "The file could not be read:"; 
     errorText += e.Message + "\n"; 
     return errorText; 
    } 
} 

これは私のクラスライブラリです。最初に私のボタンが押されたときに私のスクリプトはうまく動作しますが、もう一度押すと例外が発生します:WindowsフォームアプリケーションからPowerShellスクリプトを実行する際のエラー

現在のホストはそれを実装していないため、この関数を呼び出せません。

スクリプトの実行中に作成されたログのフォルダを削除した場合、正常に動作します。

マイスクリプト:

rmdir D:\Logs 
mkdir D:\Logs 
Get-EventLog Application |Format-List | Out-File D:\Logs\app.txt 
Get-EventLog System |Format-List | Out-File D:\Logs\app.txt 

答えて

1

rmdirはフォルダが空でない場合は、フォルダを削除する前に確認するためにあなたを必要とします(「Y」と入力してEnterする必要があります)。それで、ユーザー対話がサポートされていないため、例外が発生します。

Remove-Itemコマンドを使用すると、-Recurse -Forceパラメータでサイレントにディレクトリを削除できます。 rmdir/mkdirの代わりに次のコマンドを使用してください。

Remove-Item D:\Logs -Recurse -Force 
New-Item -ItemType directory -Path D:\Logs 
+0

ありがとうございます。それは私にとっては効果的ですが、結果を生成するには時間がかかりすぎます。 – jasmin

+0

私はそれが長い、1つの私のマシンのファイルが約60Mであることが、恐れている、イベントログに多くのエントリがある – kennyzx

+0

ので、より速く解決策がない方法はありますか?ユーザーが指定した場所からiファイルを読み込みたい場合、どうすればよいですか? – jasmin

関連する問題