none
Run PowerShell code inside C#

    Question

  • Hey guys,

    I have a PowerShell Script that I run to insert some data into SQL Server.  However, I want to be able to execute it inside a C# application.  I know for sure, I have to add the following references using system.managemet.automation and system.management.automation.runspaces.  My PowerShell Script is the following:

    Import-Module SQLPS -DisableNameChecking
    
    $TruncateQuery = "Truncate Table TestTable"
    
    #Truncate Query
    Invoke-Sqlcmd -Query $TruncateQuery -ServerInstance "local" -Database "TestDatabase"
    
    $InsertStatement = "Insert INTO TestTable (ID, Message) Values (1, 'Test Message')"
    
    Invoke-Sqlcmd -Query $InsertStatement -ServerInstance "local" -Database "TestDatabase"

    Monday, April 24, 2017 6:59 PM

All replies

  • bump
    Wednesday, April 26, 2017 5:33 PM
  • Hi Diango,

    Don't just "bump" to bump your post.

    Please post the C# code what you have done so far so that we can identify where you are going wrong.


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Thursday, April 27, 2017 1:06 PM
    Moderator
  • So I've been trying to execute the simple PS code below in C#. Everything looks good, but it just won't insert into my table.

    PowerShell ps = PowerShell.Create();

    var Query = "Insert INTO SimpleTest Values (2, 'This is a Test!')";
    

    ps.AddScript("Import-Module SQLPS -DisableNameChecking"); ps.AddScript("get-module SQLPS"); ps.AddScript("Invoke-Sqlcmd -ServerInstance localhost -Database TestDB -Query " + Query); ps.Invoke();



    • Edited by Diango Sunday, April 30, 2017 8:47 PM
    Sunday, April 30, 2017 8:47 PM