0

The code below does not error, it inserts into a SQL Server table with no issues. However the [ServicePrincipalNames] data is not inserted how I planned.

The value that gets inserted into the table is

Microsoft.ActiveDirectory.Management.ADPropertyValueCollection

What I am trying to insert is the value in that object collection which looks like this:

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

The code to do the insert is shown here below. How could I change this to have the insert put all the services in the column, separated by |?

$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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Leo Torres
  • 673
  • 1
  • 6
  • 18

1 Answers1

0

Ok after a more time googling and learning about out-string. In order to display objects i had to create an expression on that column and rewrite it as below. and it worked

In query replace the

ServicePrincipalNames

with

@{Label="ServicePrincipalNames";Expression={$_.ServicePrincipalNames -join ";" }}
Leo Torres
  • 673
  • 1
  • 6
  • 18