将数据导入 SQL 并在输入中添加字段
我的服务器上有 powershell 版本 2.0.0.1082。我想将数据从文本文件导入到 SQL Server,并将两个新字段(字符和当前日期时间)添加到 SQL 2008 数据库的输入中。我一直在使用批量导入或 SSIS 来执行此操作,但我想使用 powershell 以便于维护该过程。该文件的顶部有列名称,每个字段由“|”分隔。 到目前为止的代码:
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
请问有什么想法吗?
谢谢!
曼乔特
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将
-PassThru
开关添加到Add-Member
cmdlet 以在管道中转发对象,或者将$_
全部位于 ForEach 块的末尾。以下是使用
-PassThru
的示例:另一个不使用
-PassThru
的示例:准备好 CSV 数据以输入数据库后,您可以使用
Invoke- SQL Server 2008 附带的用于执行插入的 SqlCmd cmdlet。 MSDN 此处上有大量信息向您展示如何操作。
You'll either need to add the
-PassThru
switch to theAdd-Member
cmdlet 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-SqlCmd
cmdlet that comes with SQL Server 2008 to perform Inserts. There is a wealth of information on MSDN here to show you how.