Find list of websites on servers.

Welcome Forums General PowerShell Q&A Find list of websites on servers.

This topic contains 13 replies, has 3 voices, and was last updated by

 
Participant
2 days, 23 hours ago.

  • Author
    Posts
  • #113275

    Participant
    Points: 0
    Rank: Member

    Hello I need help with powershell scrpit, I am new and currently learning. My current task is to find below information on servers. I have about 3500 servers.

    Need to find if its web server or SQL ( iis installed or not, SQL installed or not)

    Need to find list of  websites hosted if any.

    Thanks

  • #113321

    Participant
    Points: 20
    Rank: Member

    Did you at least try to write something from what you know in PowerShell. This is fairly an easy task for someone who know the basics of PowerShell. You can grab the basics in a day.

    https://mva.microsoft.com/liveevents/powershell-jumpstart

    • #113390

      Participant
      Points: 0
      Rank: Member

      Hello  Kvprasoon, I have the following script that I was able to work
      $RemoteComputers = Get-Content -Path C:\scripts\servers.txt
      ForEach ($Computer in $RemoteComputers)
      {

                   Invoke-Command -ComputerName $Computer -ScriptBlock {
                   Get-WebBinding | % {
          $name = $_.ItemXPath -replace '(?:.*?)name="([^"]*)(?:.*)', '$1'
          New-Object psobject -Property @{
              Server = $Computer
              Name = $name
              Binding = $_.bindinginformation.Split(":")[-1]
          }
      } | Group-Object -Property Name |
      Format-Table Server, Name, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap

                   }
                                }
       

      It gives me the list of websites and binding information. It does not include the server name, and I also need if it can list the  website is active and not active. I also need help with script that can get me the users logged in last 15 days to servers.

       

      Thanks

  • #113402

    Participant
    Points: 10
    Rank: Member

    As for this...

    Need to find if its web server or SQL ( iis installed or not, SQL installed or not)

    … You use the Get-Service cmdlet to see if these services are running.

    You as using a remote session. You have to use scope to use local variables in a remote session. It's call the Using statement.

    $ps = "Windows PowerShell"
    Invoke-Command -ComputerName S1 -ScriptBlock {
      Get-WinEvent -LogName $Using:ps
    }
    

    See details here:

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-6

    So this …

    $Computer
    

    … should be this …

    $Using:Computer
    

    As for this...

    It does not include the server name

    … you already know this because you are passing that in via your command, you are just not asking it to be shown.

    As for this...

    if it can list the website is active and not active

    … you just ask for that they same way you did for bindings using the cmdlets...

    Get-Website
    Get-WebSiteState
    

    As for this...

    get me the users logged in last 15 days to servers.

    … You get this from event logs, using the Get-WinEvent cmdlet.
    See details here:

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/get-winevent?view=powershell-6

    Also, please take some tim eto review / use this module:

    Introducing IISAdministration in the PowerShell Gallery

    https://blogs.iis.net/iisteam/introducing-iisadministration-in-the-powershell-gallery

    and this details ..
    Web Server (IIS) Administration Cmdlets in Windows PowerShell
    https://technet.microsoft.com/en-us/library/hh867899(v=wps.630).aspx

  • #113431

    Participant
    Points: 0
    Rank: Member

    Hello I tried modified as per you suggestion, Code runs but wont show Ip address, computer name and website state, I can see only bindings and site name

     

    $ps = "Windows PowerShell"

    $RemoteComputers = Get-Content -Path C:\scripts\servers.txt

    ForEach ($Computer in $RemoteComputers)

    {

     

    Invoke-Command -ComputerName $Computer -ScriptBlock {

    Get-WebsiteState [[-Name] ]

    Get-WebBinding | % {

    $name = $_.ItemXPath -replace '(?:.*?)name="([^"]*)(?:.*)', '$1'

    New-Object psobject -Property @{

    Server = $PSComputerName

    Name = $name

    IpAddress = $_.ipaddress

    Binding = $_.bindinginformation.Split(":")[-1]

     

     

    }

    } | Group-Object -Property Name |

    Format-Table Server, Name,IpAddress, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap

     

    }

    }

     

     

  • #113434

    Participant
    Points: 20
    Rank: Member

    I would suggest you to develop and test the code locally on one server, once succeeded, wrap it up in a scriptblock with Invoke-Command targeting multiple servers.

    There is an unwanted Get-WebsiteState [[-Name] ] in your code and -ComputerName can accept array of strings, hence no need to use foreach, you can Invoke-Command -ComputerName $RemoteComputers {}

  • #113437

    Participant
    Points: 0
    Rank: Member

    Can you arrange this code for once, Thanks for your reply as I am pretty new and cant get it to work.

  • #113438

    Participant
    Points: 10
    Rank: Member

    You say you changed the code and it's not working, but you don't show those changes.

    What kvprasoon and I are saying is that we are here to help, but since you are new, you really need to take some time and get ramped up before you overly frustrate yourself. Hence our responses.

    Based on your post, it appears you found this block of code on the web somewhere and tweaked for what you are after, which is fine and all, but it's confused you and really over complicated for that you are after.

    If all you want is scanning your ADDS host for the services you mention, and that partial info, a simpler starting point, after going through several of the video trainings via MS Virtual Academy, or the many PowerShell videos on YouTube, could be like this:

    Clear-Host
    $RemoteComputers = 'iis01','dc01','sql01'
    
    ForEach ($RemoteComputer in $RemoteComputers)
    {
        "`n" # Insert a new line.
        "*"*24 # Banner line record seperator
    
        Invoke-Command -ComputerName $RemoteComputer -ScriptBlock {
    
            "Services on the host $Using:RemoteComputer $(((Get-NetIPAddress).IPV4Address) -Notmatch '127.0.0.1')"
            ( $TargetServices = 'W3SVC','MSSQLSERVER' | % { Get-Service -Name $_ -ErrorAction SilentlyContinue} )
           
            Try 
            { Get-Website -ErrorAction SilentlyContinue }
            Catch { Write-Warning -Message "Web services are not running on host $Using:RemoteComputer" }
        }
    }
    
    ************************
    Services on the host iis01    192...
    
    Status   Name               DisplayName                            PSComputerName                                                                                     
    ------   ----               -----------                            --------------                                                                                     
    Running  W3SVC              World Wide Web Publishing Service      iis01                                                                                          
    
    Name           : Default Web Site
    ID             : 1
    State          : Started
    PhysicalPath   : %SystemDrive%\inetpub\wwwroot
    Bindings       : Microsoft.IIs.PowerShell.Framework.ConfigurationElement
    PSComputerName : iis01
    
    
    Name           : kcd
    ID             : 2
    State          : Started
    PhysicalPath   : C:\inetpub\kcd
    Bindings       : Microsoft.IIs.PowerShell.Framework.ConfigurationElement
    PSComputerName : iis01
    
    ...
    
    ************************
    Services on the host sql01    192...
    Running  MSSQLSERVER        SQL Server (MSSQLSERVER)               sql01                                                                                          
    WARNING: Web services are not running on host sql01
    

    As for getting user logon info, again, that is in the event logs whether on a server or via the domain. There are lots of examples of what I show above and this user log on stuff all over the web, and yes, complete samples via sites like the MS PowerShellGallery. For Example:

    Powershell script to extract all users and last logon timestamp from a domain
    https://gallery.technet.microsoft.com/scriptcenter/Powershell-script-to-398c5aab

    Yet, again, really, spend the time on the ramp up, so to decrease any unnecessary hair-pulling and angst that is to come anyway. Trust me, we all have had and will continue to have to deal with that with anything.

    Note:
    There are always more elegant ways to do X or Y, so what I am showing is just a direct raw approach to what you say your info use case gathering effort is. If you want to make it elegant, I'll leave that to a homework assignment for you. ;^}

  • #113528

    Participant
    Points: 0
    Rank: Member

    Thanks you guys for your help, It help me complete the pending task. It will take while for me to understand the powershell.

  • #114313

    Participant
    Points: 0
    Rank: Member

    So with the help of both of you guys and google. I was able to connect couple already available scripts and some changes, got script that gives me all the information that I need. Everything works fine But when I try to export it to csv it  give me headers only no other information is getting populated. I have trying using the variable $results = @ () foreach {} $results += Select-Object .....|export-csv But still does not populated. Can you guys help in formatting. So I can get the results the way I see in powershell window.

    Thanks

     

    Clear-Host

    $ps = "Windows PowerShell"

    $RemoteComputers = 'local1','local2'

     

    ForEach ($RemoteComputer in $RemoteComputers)

     

    {

     

    #"`n" # Insert a new line.

    #"*"*24 # Banner line record seperator

     

    Invoke-Command -ComputerName $RemoteComputer -ScriptBlock {

     

    $Service = ( $TargetServices = 'W3SVC','MSSQLSERVER' | % { Get-Service -Name $_ -ErrorAction SilentlyContinue} )

    $IPAddress = ([System.Net.Dns]::GetHostByName($Inputmachine).AddressList[0]).IpAddressToString

    Import-Module WebAdministration

     

    $hostname = hostname

    $Websites = Get-ChildItem IIS:\Sites

    $date = (Get-Date).ToString('MMddyyyy')

    foreach ($Site in $Websites) {

    $Binding = $Site.bindings

    [string]$BindingInfo = $Binding.Collection

    [string[]]$Bindings = $BindingInfo.Split(" ")#[0]

    $i = 0

    $status = $site.state

    $path = $site.PhysicalPath

    $fullName = $site.name

    $state = ($site.name -split "-")[0]

    $Collection = ($site.name -split "-")[1]

    $status = $site.State

    $anon = get-WebConfigurationProperty -Filter /system.webServer/security/authentication/AnonymousAuthentication -Name Enabled -PSPath IIS:\sites -Location $site.name | select-object Value

    $basic = get-WebConfigurationProperty -Filter /system.webServer/security/authentication/BasicAuthentication -Name Enabled -PSPath IIS:\ -location $site.name | select-object Value

    Do{

    if( $Bindings[($i)] -notlike "sslFlags=*"){

    [string[]]$Bindings2 = $Bindings[($i+1)].Split(":")

    $obj = New-Object PSObject

    $obj | Add-Member Date $Date

    $obj | Add-Member Host $hostname

    $obj | Add-Member State $state

    $obj | Add-Member SiteName $Site.name

    $obj | Add-Member SiteID $site.id

    $obj | Add-member Path $site.physicalPath

    $obj | Add-Member Protocol $Bindings[($i)]

    $obj | Add-Member Port $Bindings2[1]

    $obj | Add-Member Header $Bindings2[2]

    $obj | Add-member AuthAnon $Anon.value

    $obj | Add-member AuthBasic $basic.value

    $obj | Add-member Status $status

    $obj | Add-Member Ipaddress $IpAddress

    $obj | Add-Member Service $Service

     

     

    $obj#

    $i=$i+2

    }

    else{$i=$i+1}

    } while ($i -lt ($bindings.count))

     

     

    }}| Format-Table -AutoSize -Property Host,IpAddress,SiteID,Port,Protocol,Status,SiteName,Path,Header,Service -GroupBy IpAddress |

    Select-Object Host,IpAddress,SiteID,Port,Protocol,Status,SiteName,Path,Header,Service | Export-csv -Append -notypeinformation -path c:\temp\iis.csv

    }

     

     

     

     

     

  • #114325

    Participant
    Points: 10
    Rank: Member

    That is because of this...

    | Format-Table -AutoSize -Property Host, IpAddress, SiteID, Port,
    Protocol, Status, SiteName, Path, Header, Service `
    -GroupBy IpAddress

    ... you never do this sort of thing before a select. Always get all your data before you try formatting. Also, that is not how you use that Format-table cmdlet.

    You only need to do this to see your results. I made one more change, that in most cases, there is no IIS on a SQL server, so, no need to load that WebAdministration module.

    ### Find list of websites on servers
    
    
    Clear-Host
    $ps = "Windows PowerShell"
    $RemoteComputers = 'local1','local2'
    
    ForEach ($RemoteComputer in $RemoteComputers)
    {
        #"`n" # Insert a new line.
        #"*"*24 # Banner line record seperator
    
        Invoke-Command -ComputerName $RemoteComputer `
        -ScriptBlock {
            $Service = ( $TargetServices = 'W3SVC', 'MSSQLSERVER' `
            | % { Get-Service -Name $_ -ErrorAction SilentlyContinue} )
    
            $IPAddress = ([System.Net.Dns]::GetHostByName($Inputmachine).AddressList[0]).IpAddressToString
    
            If (Get-Service -Name W3SVC)
            {
                Import-Module WebAdministration
    
                $hostname = hostname
                $Websites = Get-ChildItem -Path 'IIS:\Sites'
                $date = (Get-Date).ToString('MMddyyyy')
    
                foreach ($Site in $Websites)
                {
                    $Binding = $Site.bindings
                    [string]$BindingInfo = $Binding.Collection
                    [string[]]$Bindings = $BindingInfo.Split(" ")#[0]
    
                    $i = 0
                    $status = $site.state
                    $path = $site.PhysicalPath
                    $fullName = $site.name
                    $state = ($site.name -split "-")[0]
                    $Collection = ($site.name -split "-")[1]
                    $status = $site.State
    
                    $anon = get-WebConfigurationProperty `
                    -Filter '/system.webServer/security/authentication/AnonymousAuthentication' `
                    -Name Enabled `
                    -PSPath 'IIS:\sites' `
                    -Location $site.name `
                    | select-object Value
    
                    $basic = get-WebConfigurationProperty `
                    -Filter '/system.webServer/security/authentication/BasicAuthentication' `
                    -Name Enabled -PSPath 'IIS:\' `
                    -location $site.name `
                    | select-object Value
    
                    Do
                    {
                        if ( $Bindings[($i)] -notlike "sslFlags=*")
                        {
                            [string[]]$Bindings2 = $Bindings[($i + 1)].Split(":")
    
                            $obj = New-Object PSObject
                            $obj | Add-Member Date $Date
                            $obj | Add-Member Host $hostname
                            $obj | Add-Member State $state
                            $obj | Add-Member SiteName $Site.name
                            $obj | Add-Member SiteID $site.id
                            $obj | Add-member Path $site.physicalPath
                            $obj | Add-Member Protocol $Bindings[($i)]
                            $obj | Add-Member Port $Bindings2[1]
                            $obj | Add-Member Header $Bindings2[2]
                            $obj | Add-member AuthAnon $Anon.value
                            $obj | Add-member AuthBasic $basic.value
                            $obj | Add-member Status $status
                            $obj | Add-Member Ipaddress $IpAddress
                            $obj | Add-Member Service $Service
                            $obj#
    
                            $i = $i + 2
                        }
                        else {$i = $i + 1}
    
                    } while ($i -lt ($bindings.count))
    
                }
            }
        } | 
            Select-Object Host, IpAddress, SiteID, Port, Protocol, Status, SiteName, 
            Path, Header, Service | 
            Format-Table -AutoSize 
    }
    
  • #114358

    Participant
    Points: 0
    Rank: Member

    Thanks postanote for your help and time appreciate that, So when I used this to export file, Did not posted the whole as rest is same as above post as you added in the previous post.

     

     

    } |

    Select-Object Host, IpAddress, SiteID, Port, Protocol, Status, SiteName,

    Path, Header, Service |

    Format-Table -AutoSize |

    Export-csv -Append -notypeinformation -path c:\temp\iis.csv

    }

    I received the below error

    Export-csv : Cannot append CSV content to the following file: c:\temp\iis.csv.

    The appended object does not have a property that corresponds to the following

    column: Host. To continue with mismatched properties, add the -Force

    parameter, and then retry the command.

    At line:95 char:9

    +         Export-csv -Append -notypeinformation -path c:\temp\iis.csv

    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidData: (Host:String) [Export-Csv], Invalid

    OperationException

    + FullyQualifiedErrorId : CannotAppendCsvWithMismatchedPropertyNames,Micro

    soft.PowerShell.Commands.ExportCsvCommand

     

     

    When I used the below with -force, I get the same results, only column headers gets populated and rest is empty. I am exporting the results on my local machine, where i running this script from.

    Export-csv -Force -Append -notypeinformation -path c:\temp\iis.csv

     

     

  • #114360

    Participant
    Points: 0
    Rank: Member

    So When I used

    export-file c:\temp\iis.csv -Append -Encoding unicode

    I was able to get the results in the file but they all are getting populated to one first column only.

    Thanks

  • #114394

    Participant
    Points: 10
    Rank: Member

    Again, it's all about placement and where the call to data and format are applied.

    ### Find list of websites on servers
    
    
    Clear-Host
    $ps = "Windows PowerShell"
    $RemoteComputers = $env:COMPUTERNAME
    
    ForEach ($RemoteComputer in $RemoteComputers)
    {
        #"`n" # Insert a new line.
        #"*"*24 # Banner line record seperator
    
        Invoke-Command -ComputerName $RemoteComputer `
        -ScriptBlock {
            $Service = ( $TargetServices = 'W3SVC', 'MSSQLSERVER' `
            | % { Get-Service -Name $_ -ErrorAction SilentlyContinue} )
    
            $IPAddress = ([System.Net.Dns]::GetHostByName($Inputmachine).AddressList[0]).IpAddressToString
    
            If (Get-Service -Name 'W3SVC')
            {
                Import-Module WebAdministration
    
                $hostname = hostname
                $Websites = Get-ChildItem -Path 'IIS:\Sites'
                $date = (Get-Date).ToString('MMddyyyy')
    
                foreach ($Site in $Websites)
                {
                    $Binding = $Site.bindings
                    [string]$BindingInfo = $Binding.Collection
                    [string[]]$Bindings = $BindingInfo.Split(" ")#[0]
    
                    $i = 0
                    $status = $site.state
                    $path = $site.PhysicalPath
                    $fullName = $site.name
                    $state = ($site.name -split "-")[0]
                    $Collection = ($site.name -split "-")[1]
                    $status = $site.State
    
                    $anon = get-WebConfigurationProperty `
                    -Filter '/system.webServer/security/authentication/AnonymousAuthentication' `
                    -Name Enabled `
                    -PSPath 'IIS:\sites' `
                    -Location $site.name `
                    | select-object Value
    
                    $basic = get-WebConfigurationProperty `
                    -Filter '/system.webServer/security/authentication/BasicAuthentication' `
                    -Name Enabled -PSPath 'IIS:\' `
                    -location $site.name `
                    | select-object Value
    
                    Do
                    {
                        if ( $Bindings[($i)] -notlike "sslFlags=*")
                        {
                            [string[]]$Bindings2 = $Bindings[($i + 1)].Split(":")
    
                            $obj = New-Object PSObject
                            $obj | Add-Member Date $Date
                            $obj | Add-Member Host $hostname
                            $obj | Add-Member State $state
                            $obj | Add-Member SiteName $Site.name
                            $obj | Add-Member SiteID $site.id
                            $obj | Add-member Path $site.physicalPath
                            $obj | Add-Member Protocol $Bindings[($i)]
                            $obj | Add-Member Port $Bindings2[1]
                            $obj | Add-Member Header $Bindings2[2]
                            $obj | Add-member AuthAnon $Anon.value
                            $obj | Add-member AuthBasic $basic.value
                            $obj | Add-member Status $status
                            $obj | Add-Member Ipaddress $IpAddress
                            $obj | Add-Member Service $Service
                            $obj#
    
                            $i = $i + 2
                        }
                        else {$i = $i + 1}
    
                    } while ($i -lt ($bindings.count))
    
                }
            }
        } | 
            Select-Object Host, IpAddress, SiteID, Port, Protocol, Status, SiteName, 
            Path, Header, Service | 
            Export-Csv -Path 'C:\Temp\iis.csv' -Append -NoTypeInformation | 
            Format-Table -AutoSize
    }
    
    Import-Csv -Path 'C:\Temp\iis.csv' | Format-Table -AutoSize
    

You must be logged in to reply to this topic.