I'm coming from a *nix scripting background and I'm a total newbie to powershell and Windows admin in general. I'm trying to write a script that will check the SmartHost value on a collection of exchange/IIS smtp virtual hosts. I'm trying to figure out how to insert the looped variable into the ADSI query string but the + operator doesn't do the trick:
$hosts = @("host1","host2")
foreach ($hostname in $hosts) {
$SMTPSvc = [ADSI]'IIS://' + $hostname + '/smtpsvc/1'
echo $SMTPSvc.SmartHost
}
Using the + with single or double quotes gives me this error:
Method invocation failed because [System.DirectoryServices.DirectoryEntry] does not contain a method named 'op_Addition'.
At line:3 char:1
+ $SMTPSvc = [ADSI]'IIS://' + $hostname + '/smtpsvc/1'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
What would be the proper or preferred way to insert the looped host value into the ADSI query string?
It looks like an order of operations issue. The first part of the query:
[ADSI]'IIS://'
is being converted to the query string and then you try to add a string to the resulting [System.DirectoryServices.DirectoryEntry] object. Since that class does not provide an addition operator, it fails. Instead, generate the entire string first before constructing the query by enclosing it in brackets:
$SMTPSvc = [ADSI]('IIS://' + $hostname + '/smtpsvc/1')