2016-12-15 16 views
0

C#のSQLスクリプトを実行するpowershellスクリプトを実行しようとしています。SQLスクリプトを実行するためにC#からpowershellを呼び出す

私はPowerShellのコマンドからのPowerShellスクリプトを実行した場合、私はここではC#

からそれを実行しようとすると、それは動作しますが、それは動作しません促し、私はPowerShellのスクリプト

public static void RunPowershell(string fileName, string functionName, Dictionary<string, string> parameters) 
    { 
     string fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName); 
     string script = File.ReadAllText(fullPath); 

     try 
     { 
      using (Runspace runspace = RunspaceFactory.CreateRunspace()) 
      { 
       runspace.Open(); 
       PowerShell instance = PowerShell.Create(); 
       instance.Runspace = runspace; 

       instance.AddScript(script); 

       instance.Invoke(); 

       instance.Commands.Clear(); 
       var command = instance.AddCommand(functionName); 
       if (null != parameters) 
       { 
        foreach (var parameter in parameters) 
        { 
         command.AddParameter(parameter.Key, parameter.Value); 
        } 
       } 
       var result = instance.Invoke(); 
      } 
     } 
     catch(Exception e) 
     { 
      MessageBox.Show(e.Message); 
     } 
    } 
を実行するために使用しています機能です

function RunScript(){ 
    Import-Module "SQLPS" -DisableNameChecking 
    Invoke-Sqlcmd -inputfile ".\TestSQL.sql" -ServerInstance . -Verbose 
} 

function ShowMessage(){ 
    [System.Windows.Forms.MessageBox]::Show("Hi from Powershell !") 
} 

TestSQL.sqlは次のようになります。

と私のPowerShellスクリプトは、(Test2.ps1)であります

USE TEST 
GO 
INSERT INTO Employee VALUES('1', 'abc') 

それは私がしようとすると、メッセージボックスを表示します:

PowershellHelper.RunPowershell("Test2.ps1", "ShowMessage", null); 

しかし、私はしようとすると、テーブルに挿入されていません。

PowershellHelper.RunPowershell("Test2.ps1", "RunScript", null); 

答えて

0

あなたはprobalby TestSQLスクリプトを持っていないためですあなたの現在のディレクトリに。フルパスを指定するか、現在のディレクトリを切り替える必要があります。

Invoke-Sqlcmd -inputfile "C:\FolderWhereYouhavetheSQL\TestSQL.sql" -ServerInstance . -Verbose 

又は

cd "C:\FolderWhereYouhavetheSQL" 
Invoke-Sqlcmd -inputfile ".\TestSQL.sql" -ServerInstance . -Verbose 
+0

TestSQL.sqlはTest2.ps1と同じディレクトリにあります。私はフルパスで試しましたが、うまくいきませんでした。 –

+0

Test2.ps1をpowershellから別々に実行したときの出力は? –

+0

powershellコマンドプロンプトからTest2.ps1を実行すると、スクリプトが正しく実行され、値がテーブルに追加されているのがわかります。 –

関連する問題