简体   繁体   中英

Powershell script for IIS site count

I have written a powershell script, which will search for a specific word in IIS:\Sites.if the word is matched then it will automatically bind 443 with SSL certificate. Finally, I need a value which will show how many sites are being matched or updated? So I have written sum of "n" number program for this query. Is there any alternate method in Powershell to find the value other than this?

So here is my code,

$site= @((Get-ChildItem IIS:\Sites).Name) 
$count=0
echo "All the IIS site have been taken in array"
for($i=0;$i -le $site.count;$i++){
echo "IIS site count"
$hostname=$site[$i] 
echo "ALL sites are now in variable hostname"
if($hostname -match ".8ktest.com"){
echo "searching for the match .8ktest site"
echo "Matching found for .8ktest.com"
echo "Binding in progress"
#New-WebBinding -Name $hostname -IPAddress * -Port 443 -Protocol https -HostHeader $hostname -SslFlags 1
echo "Binding is done "
$cert = (Get-ChildItem "cert:\LocalMachine\my" `
| where-object { $_.Subject -like "*.8ktest.com" } `
| Select-Object -First 1).Thumbprint
$binding = Get-WebBinding -Name $hostname -Protocol https  
if ($binding) {
echo "Adding SSL certificate in progress"
$binding.AddSslCertificate($cert, "my")
echo "succesffully binded 443 in the site $hostname"
$hostname
$count=$hostname.count+$count
}
$count
}
}
else{
echo "No match found "
}
}

If you want to keep track of how many sites required a certificate, you can simply just add $count++ to increment $count after your AddSslCertificate() method:

if ($binding) {
    $binding.AddSslCertificate($cert, "my")
    $count++
}

If you want to track the count of site names that match the naming criteria, you can consider the following scenarios:

If $sites is always a collection (two or more sites), then you can simply do the following:

($sites -match '\.8ktest\.com').Count

If $sites could contain zero or more sites, you will need to handle the scalar and collection scenarios:

([regex]::Matches($sites,'\.8ktest\.com') | Where Success).Count

Since -match uses regex, you should technically escape your literal . characters. Otherwise 48ktests.com -match '.8ktest.com' would be true .

-match works in two modes. When the left-hand side (LHS) is a single item, the operator will return true or false . If the LHS is a collection, it will return the items that match the condition. So you can't rely on ($item -match 'text').Count for every situation because, for example, ('nothing' -match 'text').Count still returns 1 even though the comparison returns false .

Using [regex]::Matches() | Where Success [regex]::Matches() | Where Success , you will get consistent results regardless of the item count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM