Execute the Powershell script using Stored procedure/TSQL.

Rakesh Dhar 96 Reputation points
2021-03-01T08:38:46.077+00:00

Hello all,

Please tell , how can i execute the Powershell script using Stored procedure.

i need to execute it .. with one parameter as file name

please tell..

Developer technologies Transact-SQL
SQL Server Other
{count} votes

3 answers

Sort by: Most helpful
  1. Guoxiong 8,206 Reputation points
    2021-03-01T15:38:27.177+00:00

    Something like this:

    DECLARE @fileName varchar(128);
    DECLARE @sql varchar(max);
    SET @sql = 'powershell.exe -c "get-service | C:\myPowershell.ps1 -' + @fileName + '"';
    EXEC xp_cmdshell @sql;
    
    1 person found this answer helpful.
    0 comments No comments

  2. EchoLiu-MSFT 14,621 Reputation points
    2021-03-02T07:12:55.317+00:00

    Hi @Rakesh Dhar ,

    Welcome to the Microsoft TSQL Q&A Forum!

    If you must execute the Powershel script through a stored procedure, then you can refer to Guoxiong's method, but I also recommend that you use Powershell to extract sql server data instead of using sql to execute Powershell.

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  3. Tom Phillips 17,771 Reputation points
    2021-03-01T19:26:19.76+00:00

    I highly recommend you use PowerShell to pull data from SQL Server, rather than trying to execute PowerShell from xp_cmdshell.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.