Search code examples
powershelliissharepointw3clogparser

Finding last accessed website


Checking to see if this logic makes any sense or if I'm missing something.

Each IIS Site has their own Site ID. This Site has it's own IIS Log folder based on that Site ID. So if your Site ID is 2385, then your Log folder is W3SVC2385.

You can get the Site ID for each Site in command line by running '%windir%\system32\inetsrv\appcmd list site' which gives you SITE "Site Name" (id:####, bindings, State)

By pulling that data into a file, one should be able to isolate both the Site Name and the ID, then create a variable for each IIS Log folder. Using this information, you can pull in file information from the IIS Logs folders. By looking at the date the last created and/or modified log file was created/updated in each folder, shouldn't that tell us, what day that site was last accessed? Or am I missing something?


Solution

  • So here is the code I came up with. This only works if your site name is also the URL for the site (which is the case for us here). It inserts the Website Name into the first part of the URL stem.

    Because this is for a SharePoint farm for us, I also filtered for default.aspx and home.aspx in the LogParser command.

    Using Get-Website, I get both the site name & id. I add the name into the url stem and use the id to get into the appropriate log folder and then create a csv file based on the site name.

    Hopefully this can be helpful for others!

    $Sites = Get-WebSite
    
    foreach ($site in $sites)
    {
        $id = $SITE.id
        $name = $site.name
        $name = $name -replace '\s',''
        $filename = $name + '.csv'
        $logfolder = 'D:\LOGS\IISLOGS\W3SVC' + $id
        $logpath = $logfolder + "\*.*"
    
        & "C:\Program Files (x86)\Log Parser 2.2\LogParser.exe" -i:iisw3c "SELECT DISTINCT TO_LOWERCASE(cs-uri-stem),max(date) into "$filename" from $logpath WHERE cs-uri-stem LIKE '%Default.asp%' OR cs-uri-stem LIKE '%home.asp%' group by cs-uri-stem" -o:CSV
    
        $Content = @()
        $NewContent = @()
        $Content = Get-Content $filename 
        foreach ($line in $Content)
        {
            $NewContent += $name + $line
            }
        $NewContent[0] = "Site URL,DateLastAccessed"
        $NewContent | Set-Content $filename
    }