How can I save the results from a Powershell command to a MS SQL DB?
For example:
I run this at a Powershell prompt: get-psdrive and it returns some results in a column view.
How can I take each element of the result and log it into a separate DB row/column?
I recommend saving the results of your command to a variable. Such as:
The variable can be indexed like this:
First Element:
Last Element:
You can iterate through each element with
foreach:Or the
ForEach-Objectcmdlet:Now that you have the data to populate your table with you are ready to connect to the database and perform the database record inserts.
You can make use of the Powershell SQL server cmdlets or you can connect using .NET objects. Depending on what version of SQL server you have will drive your choice on which to use. SQL Server 2008 has Powershell cmdlets, 2005 does not. There is a wealth of information about the SQL server 2008 Powershell integration here. For SQL Server 2005 you have some different options. This question answer here provides a list of Powershell options to use with SQL Server 2005.
More Info:
When Powershell displays object information it uses a type system to selectively determine what properties of the object to display on the screen. Not all of the object’s are displayed. Powershell uses XML files to determine what properties to display which are stored in the Powershell directory:
The objects returned from
Get-PsDriveare of typeSystem.Management.Automation.PSDriveInfo. The filePowerShellCore.format.ps1xmltells the formatting engine what properties to display in the Powershell window. It just might be that these are the exact properties you are looking for however many objects have additional properties that are not displayed. For example an object of typeSystem.IO.DirectoryInfowill not have all it’s properties displayed by default. You can view the rest of the objects properties using theGet-Membercmdlet, for example:This will show all of the object’s methods and properties. You can also view all of the object’s properties using the
Select-Objectcmdlet using a wildcard for the property parameter:To access an objects properties values use the following syntax:
Now that you know how to view an objects properties and access their values you’ll need to use this to construct an
InsertSQL statement. Here is an example using theInvoke-SqlCmdcmdlet provided with SQL Server 2008.Here’s an example looping through objects returned from
Get-PsDriveassuming you have a table called MyTable and it has at least two columns which accept textual data: