VitaminD
asked on
How to Load the Output of a Powershell Function into a SQL Server table
I am using this PowerShell Function to get the local drive and mount point information from a Server. I need to use this function to retrieve information from many servers and then dump the output into a SQL Server table. I am not sure how to do this correctly. Below is the function I am using as well as some info I gathered but I am not sure how to put it all together. Any suggestions would be appreciated.
Function Get-DiskDrive
{
Param(
[string[]]$drive = $env:SystemDrive,
[string[]]$computername = $env:COMPUTERNAME
) #end param
Get-WmiObject -Class win32_Volume -ComputerName $computername |
Select-object DriveLetter, Label, FileSystem, PageFilePresent,
@{Name = "ComputerName"; Expression = {$_.__Server} },
@{Name = "Capacity(GB)"; Expression = {$_.capacity / 1GB} },
@{Name = "FreeSpace(GB)"; Expression = {$_.Freespace / 1GB} },
@{Name = "PercentFree"; Expression = { ($_.FreeSpace / $_.Capacity)*100 } }
} #end function get-diskdrive
-------------------------- -------
$serverlist = (Get-Content -path C:\ServerNames\Serverlist. txt)
foreach ($server in $serverlist)
{
Get-DisksSpace $server
$dataTable = Get-DisksSpace $server | out-DataTable
$connectionString = "Data Source=<server\instance>; Integrated Security=True;Initial Catalog=<databaseName>;"
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCo py") $connectionString
$bulkCopy.DestinationTable Name = "<schema.table>"
$bulkCopy.WriteToServer($d ataTable)
Function Get-DiskDrive
{
Param(
[string[]]$drive = $env:SystemDrive,
[string[]]$computername = $env:COMPUTERNAME
) #end param
Get-WmiObject -Class win32_Volume -ComputerName $computername |
Select-object DriveLetter, Label, FileSystem, PageFilePresent,
@{Name = "ComputerName"; Expression = {$_.__Server} },
@{Name = "Capacity(GB)"; Expression = {$_.capacity / 1GB} },
@{Name = "FreeSpace(GB)"; Expression = {$_.Freespace / 1GB} },
@{Name = "PercentFree"; Expression = { ($_.FreeSpace / $_.Capacity)*100 } }
} #end function get-diskdrive
--------------------------
$serverlist = (Get-Content -path C:\ServerNames\Serverlist.
foreach ($server in $serverlist)
{
Get-DisksSpace $server
$dataTable = Get-DisksSpace $server | out-DataTable
$connectionString = "Data Source=<server\instance>; Integrated Security=True;Initial Catalog=<databaseName>;"
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCo
$bulkCopy.DestinationTable
$bulkCopy.WriteToServer($d
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window
is to be preferred overOpen in new window
$connectionString above is an exception, as the string is really long, and so using a var here makes the code more readable.