Execute PowerShell Scripts through SQL Server T-SQL

Updated on February 14, 2020
klanguedoc profile image

Kevin is a Software Developer with 20 years experience designing and building business intelligence and system integration solutions.

The Microsoft PowerShell language has a very rich API that is accessible using cmdlets. Unfortunately, the API doesn’t have an interface with T-SQL (Transact-SQL) like C#, Python and R have. However, the T-SQL API does offer the xp_cmdshell command that allows TSQL to execute a Windows process.

The xp_cmdshell

xp_cmdshell is a stored procedure that executes a Windows process. This can be any process or application. It is just like a command line interface. In addition to the named process, you can also pass any arguments or parameters as needed.

The results, if any, are displayed in the standard output window in SSMS or other SQL editor or command window if you are using sqlcmd. If you rather not have any output returned, you can use the optional [no_output] parameter.

This is the xp_cmdshell syntax:

xp_cmdshell { 'command_string' } [ , no_output ]  

The command string must contain an executable process, like notepad, or in our case powershell.exe followed by input parameters as needed. All contained in the same string.

Example:

Xp_cmdshell ‘ "powershell.exe hello.ps1" ’

or

xp_cmdshell ‘ "powershell.exe hello.ps " ’, no_output 

or

xp_cmdshell ‘powershell.exe -command some_cmdlet’

Enable the xp_cmdshell

Before you can use the xp_cmdshell stored procedure, you need to enable it in SQL Server as it is disabled by default. You will need to run the following commands to activate the xp_cmdshell stored procedure.

EXEC sp_configure 'show advanced options', 1;
GO
Reconfigure;
GO
 
EXEC sp_configure 'xp_cmdshell',1
GO
Reconfigure
GO

After running the two commands from above plus the Reconfigure, you should get the following status messages:

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.

Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.

Sp_configure is a stored procedure that Displays or changes global configuration settings for the current SQL server. You need to run the same command where you want to execute external process like PowerShell.

Complete information on sp_configure is available at this document at Microsoft Docs. The “show advanced options” sets stored procedures like “xp_cmdshell” visible. The second command, sp_configure ‘xp_cmdshell’, 1 simply enables it on the server that you are executing the external process.

Limitations

The external process must be available on the machine that you want to execute as well as the script you want to execute unless you use a fully qualified path and the user agent (the entity that is launching the xp_cmdshell has the permissions to execute and has access to the various locations on the machine and network as needed.

If you execute the xp_cmdshell from your local machine, like through SSMS or sqlcmd, the command is actually being executed on the server. In other words, if you try something like this:

Xp_cmdshell ‘powershell.exe "c:\scripts\myscript.ps1" ’

The server will assume that “c:\myscripts” is actually on the server.

Set Execution Rights

Before you execute Powershell commands, you will also need to set the execution rights as follows from PowerShell CLI with Administrator rights

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force 

The Set-ExecutionPolicy changes the execution rights for the script otherwise you will get an error stating that the file is not digitally signed

The second command, Get-Children will list recursively all directories in the Test directory as n the following screenshot

Write and Test PowerShell Script

This sample script will list all folders and sub-folders. Here are the steps to follow

1.right-click the PowerShell Ide or Command Line Interface as select “run as Administrator”

2.Create a ps1 file named dirList.ps1 or whatever you would like

3.write the following code:

xp_cmdshell 'PowerShell.exe Get-ChildItem
 -Path C:\\Test -Recurse -Directory 
-Force -ErrorAction SilentlyContinue '
Source

Execute via T-SQL

Now that we have our script and it is saved to a folder on the server if you are running the script from a remote server, or alternatively if you have a development server on your laptop, you can run locally from SSMS or the command line using sqlcmd

You can include the script directly as a input parameter as in the following code:

xp_cmdshell 'PowerShell.exe -command "get-diskspace"'

For this example, you will to install the “NTFSSecurity” module first using elevated administrator rights. I suggest using the PS CLI or in Administrator mode or SSMS as the same. Personally, I am using the PS CLI.

Install-Module -Name NTFSSecurity -RequiredVersion 4.2.4

The output is listed in the following screenshot.

Source

With the module installed I head back over to the SSMS editor and try the get_diskspace command again. A subset of the output is listed in the table below

AvailableFreeSpacePercent
50.30%
AvailableFreeSpaceUnitSize
239.29 GB
ClusterSize
4096
DriveName
\\?\Volume{d00cb8c0-d019-4fb3-9128}\
TotalSizeUnitSize
475.71 GB
UsedSpacePercent
49.70%
UsedSpaceUnitSize
236.42 GB
FreeBytesAvailable
2.57E+11
TotalNumberOfBytes
5.11E+11
TotalNumberOfFreeBytes
2.57E+11
BytesPerSector
512
NumberOfFreeClusters
62727174
SectorsPerCluster
8
TotalNumberOfClusters
124703487

Now that we know this command will work from the editor, let us try running the same script from a ps1 script file. I am storing the scripts in a script folder on the “C” drive, but you can store yours wherever you like. To execute a PowerShell script that is stored in a ps1 script file, you will use the following syntax:

xp_cmdshell 'powershell.exe "c:\\PS_Scripts\\diskSpace.ps1"'

In the ISE Editor, add the “get-diskspace” without double quotes or the -command flag and save the file as a ps1 script file as in the following screenshot

Source

Once you execute the script file you should get the same results as before. You can also run PowerShell scripts from a SQL Agent, but I am not covering that in the article.

Store Data in SQL Table

Finally, you can redirect the output from the PowerShell script to a standard SQL table using the following steps:

1- Install the “SqlServer” module from the Nuget website

2- Copy and execute the following Nuget command from a Ps CLI with elevated rights: Install-Module -Name SqlServer

3- Create a PS script as like this:

(get-diskspace) | Write-SqlTableData -ServerInstance "localhost" -DatabaseName "PowerShell" -SchemaName "dbo" -TableName "diskspace" -Force

4- Execute the script from a SQL Editor page like before:

xp_cmdshell 'powershell.exe "c:\\PS_Scripts\\diskSpaceTable.ps1"'

Please note that this script will only run from PowerShell 5 which can be downloaded from the Microsoft downloads page at (https://www.microsoft.com/en-us/download/details.aspx?id=54616) current at the time of this writing. If the link is not working, try searching for PowerShell 5 Download. Make sure you are downloading from an official Microsoft site.

This wraps up this article and you have enough information to create and execute any manner of PowerShell scripts and store the information in a SQL Database. All this scripts and SQL code is stored in the following GitHub repo:

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)