用集合对象向SQL Server表中插入数据



下面的代码没有出错,它插入到SQL Server表中没有任何问题。但是,[ServicePrincipalNames]数据没有按我计划的方式插入。

插入到表中的值是

Microsoft.ActiveDirectory.Management.ADPropertyValueCollection

我要插入的是对象集合中的值,它看起来像这样:

WSMAN/Server1Name
WSMAN/Server1Name.mx.ds.abc.com
TERMSRV/Server1Name
TERMSRV/Server1Name.mx.ds.abc.com
RestrictedKrbHost/Server1Name
HOST/Server1Name
RestrictedKrbHost/Server1Name.mx.ds.abc.com
HOST/Server1Name.mx.ds.abc.com

执行插入的代码如下所示。我如何改变这一点,让插入将所有服务放在列中,由|分隔?

$sqlServer='SomeServer'
$catalog = 'SomeDatabase'

$insert = @"
Insert into dbo.ADServers([Name],[OperatingSystem],[OperatingSystemVersion],[ipv4Address],[Created],[Deleted],[whenChanged],[Modified],[Description],[ServicePrincipalNames],[DisplayName],[Location],[DistinguishedName],[DNSHostName])
values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}', '{13}')
"@
$start = (Get-Date).ToString('MM/dd/yyyy hh:mm:ss tt')


$connectionString = "Data Source=$sqlServer;Initial Catalog=$catalog;Integrated Security=SSPI"
# connection object initialization
$conn = New-Object System.Data.SqlClient.SqlConnection($connectionString)
#Open the Connection 
$conn.Open()
# Prepare the SQL 
$cmd = $conn.CreateCommand()
#WMI ouput transformation to SQL table

Get-ADComputer -Filter {operatingSystem -Like 'Windows*server*2019*'} -Property * |` 
Select Name,OperatingSystem,OperatingSystemVersion,ipv4Address,Created,Deleted,whenChanged,Modified,Description,ServicePrincipalNames,DisplayName,Location,DistinguishedName,DNSHostName |`
forEach-object{
$cmd.CommandText = $insert -f $_.Name, $_.OperatingSystem, $_.OperatingSystemVersion, $_.ipv4Address, $_.Created, $_.Deleted, $_.whenChanged, $_.Modified,$_.Description, $_.ServicePrincipalNames , $_.DisplayName,$_.Location,$_.DistinguishedName,$_.DNSHostName
$cmd.ExecuteNonQuery()
}


$end = (Get-Date).ToString('MM/dd/yyyy hh:mm:ss tt')
Write-Host $start
Write-Host $end

好了,在谷歌搜索和学习了out-string之后。为了显示对象,我必须在该列上创建一个表达式并将其重写如下。它成功了

在查询中替换

ServicePrincipalNames

@{Label="ServicePrincipalNames";Expression={$_.ServicePrincipalNames -join ";" }}

相关内容

  • 没有找到相关文章

最新更新