Turning an object property into a string
Hi
I'm retrieving a list of servers from AD
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher.Filter = ("OperatingSystem=Window*Server*")
$objSearcher.PropertiesToLoad.Add("Name") | Out-Null
$colResults = $objSearcher.FindAll()
I'd like to put $objResult.Properties.name into a string value but can't work out how.
Help Please.
Alex
February 20th, 2015 10:30am
Hi Alex,
Here's one method:
$str = ($colResults | ForEach { $_.Properties['Name'] }) -join ','
$str
February 20th, 2015 10:46am
Hi Mike
I'm already trying something similar
foreach ($objResult in $colResults) {
$server = $objResult.Properties.name
}
But the $server is still an object. The thing is I'm using each server name in an invoke-sqlcmd command, so I need to loop through them one at a time.
Cheers
Alex
February 20th, 2015 11:03am
Here's an adjustment:
foreach ($objResult in $colResults) {
[string]$server = $objResult.Properties.name
$server
$server.GetType().Name
}
February 20th, 2015 11:08am
Sorry I've got it wrong!!!???!!
The Line I'm having trouble with is
invoke-sqlcmd -query "select @@servername, name, compatibility_level, collation_name, recovery_model_desc From sys.databases where name not in ('master', 'tempdb', 'model', 'msdb') Order by Name" -serverinstance $server
If I manually define $server eg $server = "server1" it works fine.
If I use
foreach ($objResult in $colResults) {
$server = $objResult.Properties.name
Invoke-SQL.............
}
I get an error
invoke-sqlcmd : Value cannot be null.
Parameter name: ServerInstance
Any help???
February 20th, 2015 11:28am
You're dropping the cast.
February 20th, 2015 11:31am
I find I must use $Object.Properties.Item("attribute_name").Value. Otherwise the attribute names must be in all lower case, which is annoying.
February 20th, 2015 3:45pm
The disconnect seems to be that X.500 is specified as "case sensitive' and Microsoft is "case preserving" but MS has to honor the X.500 spec at certain levels. There is a no-man's land in between.
February 20th, 2015 3:48pm
Hi
I'm not sure whats going wrong here but if I use
$server = $objResult.Properties.item('name').value
it returns a blank value with either single or double quotes.
If I remove the .value it returns the server name but the invoke-sqlcmd still fails.
What am I getting wrong?
February 23rd, 2015 6:55am
Here is how you will need to do this to get what you want.
$searcher=[adsisearcher]'OperatingSystem=Window*Server*'
$searcher.FindAll() |
ForEach-Object{
Write-Host "ServerName is $($_.Properties['name'][0])" -fore green
}
February 23rd, 2015 8:58am
That's brilliant.
Thanks jrv
February 23rd, 2015 10:19am