Execute PowerShell Scripts through SQL Server T-SQL
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 '
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.
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
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:
Source Code
- https://github.com/kevlangdo/powershell_from_tsql
Examples of executing PowerShell from T-SQL. Contribute to kevlangdo/powershell_from_tsql development by creating an account on GitHub.
This article is accurate and true to the best of the author’s knowledge. Content is for informational or entertainment purposes only and does not substitute for personal counsel or professional advice in business, financial, legal, or technical matters.
© 2020 Kevin Languedoc