我有一个变量$CiscoCMDB
,它保存2968条记录的数据(有些字段都已填充,有些字段不像下面):
SearchCode: D12345678911 Name1: 1212 Category: Office Phone AssetTag: Status: Stock SerialNumber: FCH1549BBBB Model: CISCO IP PHONE 7945G MacAddress: Location: SF OwnerOrganization: OwnerPerson:
我还创建了一个SQL DB,CiscoCMDB,与行的列相同。我希望将所有记录写入SQL表。我曾尝试使用Write-Datatable
cmdlet,但它给了我错误。以及其他CMDlet。我想,如果我在我的代码中使用SQL SELECT语句,我应该在我的代码中使用SQL INSERT。唯一的问题是,我不知道如何解决这个问题,除了知道我需要一个foreach
循环来循环。
有人可以帮助我,因为我感到困惑和沮丧。我不确定如何正确循环。
^C
(我们所有的搜索代码都以C开头)^DN
(同样所有Name1都以DN开头)$CMDBCiscoQuery = @()
foreach ($row in $table) {
$hash = [ordered]@{
'SearchCode' = $row.SearchCode
'Category' = $row.Category
'Status' = $row.Status
'Name1' = $row.Name1
'SerialNumber' = $row.SerialNumber
'Model' = $row.Model
'MacAddress' = $row.MacAddress
'Location' = $row.Location
'OwnerOrg' = $row.OwnerOrganization
'Owner' = $row.OwnerPerson
}
$obj = New-Object -TypeName PSObject -Property $hash
$CMDBCiscoQuery+= $obj
$CMDBCisco = $CMDBCiscoQuery |
Select @{n='SearchCode';e={$_.Searchcode -replace "^C"}},
@{n='Name1';e={$_.DN -replace "^DN"}}, Category, AssetTag,
Status, SerialNumber, Model, MacAddress, Location,
OwnerOrganization, OwnerPerson
#Filling CMDB table
Write-Verbose "Filling CMDBCisco Table"
$ConnectionTimeout = 30
$ServerInstance = "myserver"
$Database = "Audits"
$conn = New-Object System.Data.SqlClient.SQLConnection
$ConnectionString = "Server={0};Database={1};Connect Timeout={2};Integrated Security = True;" -f $ServerInstance,$Database,$ConnectionTimeout
$conn.ConnectionString = $ConnectionString
$conn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($conn);
$conn.Close()