I have powershell version 2.0.0.1082 on my server. I want to import data from a text file to SQL server, and add two new fields (character and current datetime) to the input to SQL 2008 database. I have been using bulk import or SSIS to do it but I want to use powershell for the ease of maintaining the process. The file has column name at top and each field is seperated by “|”.
Code so far:
clear
import-csv "Disk.txt" -Delimiter "|" |
foreach { add-member -in $_ -membertype noteproperty DateRecorded $((Get-Date).ToString("yyyy-MM-dd"))
add-member -in $_ -membertype noteproperty SystemName 'System Name'
add-member -in $_ -membertype noteproperty Drive 'Drive Letter'
add-member -in $_ -membertype noteproperty TotalSizeGB 'Total Size'
add-member -in $_ -membertype noteproperty UsedGB Used
add-member -in $_ -membertype noteproperty FreeGB Free
add-member -in $_ -membertype noteproperty PercentFree '% Free'}|
select DateRecorded,SystemName,Drive,TotalSizeGB,UsedGB,FreeGB,PercentFree |Format-Table
Any ideas please?
Thanks!
Manjot
You’ll either need to add the
-PassThruswitch to theAdd-Membercmdlet to forward the objects on in the pipeline or put$_all by itself at the end of the ForEach block.Here is an example using
-PassThru:Another example without
-PassThru:Once you’ve prepared your CSV data for input into the database you can use the
Invoke-SqlCmdcmdlet that comes with SQL Server 2008 to perform Inserts. There is a wealth of information on MSDN here to show you how.