Thursday, July 7, 2016

Preventing Screen Saver with PowerShell

Here's a short bit of PowerShell you can have run when you log in to a machine (or manually)...
Function Prevent-ScreenSaver
{
    [CmdletBinding()]
    Param(
        [int]$IntervalSeconds = 60,
        [string]$KeyToSend = "{F15}"
    )
    $Shell = New-Object -COM “WScript.Shell”
    While ($True)
    {
        Write-Verbose "Sending key '$KeyToSend'..."
        $Shell.SendKeys($KeyToSend)
     
        Write-Verbose "`t...waiting $IntervalSeconds seconds..."
     
        Start-Sleep $IntervalSeconds
    }
}

Save that to a file, then have it start on login (via shortcut in Startup folder)...





Inspired by: https://dmitrysotnikov.wordpress.com/2009/06/29/prevent-desktop-lock-or-screensaver-with-powershell/

There's an alternative little utility, called Screen Slayer. As of 7/7/2016, links and info can be found here: http://daniel-lange.com/archives/34-Disabling-a-group-policyd-screensaver-on-Windows.html


Wednesday, July 6, 2016

SharePoint URL De-muck Utility

SharePoint links/urls for pages and such, are ridiculously unfriendly for human consumption, or even putting in emails and documents.


I threw together a quick utility over at jsfiddle.net where you can paste a URL, and it will attempt to make it simpler, getting rid of gunk and muck as much as possible, while still staying functional.

https://jsfiddle.net/mrstevec/jux51s0b/


Friday, July 1, 2016

Shrink SQL DBs with PowerShell

Here's a little nugget that will iterate over DBs larger than specified size, and shrink them.

$shrinkDBsLargerThan = 50
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$sqlsrv = New-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$sqlsrv.Databases | ? Size -GT $shrinkDBsLargerThan | % {
    Write-Host "DB: $($_.Name)"
    Write-Host "`tInitial Size(MB): $($_.Size)"
    $_.Shrink(20, [Microsoft.SqlServer.Management.Smo.ShrinkMethod]'Default')
    $_.Refresh()
    Write-Host "`t Shrunk Size(MB): $($_.Size)"
}

Monday, June 27, 2016

T-SQL: Summary of all Databases on server

/* ALL DATABASES GENERAL INFO */

DECLARE @helpdb TABLE (dbname varchar(500), dbsize varchar(100), dbowner varchar(500), dbid1 int, dbcreated varchar(50), dbstatus varchar(1000), dbcompatibility_level int)
INSERT INTO @helpdb (dbname, dbsize, dbowner, dbid1, dbcreated, dbstatus, dbcompatibility_level) 
EXEC sp_helpdb
-- SELECT * FROM @helpdb

SELECT  @@SERVERNAME AS Server 
,d.dbname AS DBName 
,DATABASEPROPERTYEX(d.dbname,'status') as DBStatus
,DATABASEPROPERTYEX(d.dbname,'Recovery') as 'DBRecovery'
,d.dbowner as DBOwner
,d.dbcreated as create_date1
,CONVERT(smalldatetime,sdb.create_date) as create_date2
,sdb.create_date as create_date3
,(mdf.size + ldf.size) / 128 as DBTotal_MB
,mdf.size / 128 AS mdb_MB
,ldf.size / 128 AS ldf_MB
,mdf.name+'.mdf' as DBFileName
,ldf.name+'.ldf' AS LogFileName
,mdf.physical_name AS DBFileFullName
,ldf.physical_name AS LogFileFullName
,d.dbstatus AS ExtendedStatus
FROM @helpdb d
JOIN sys.master_files mdf 
ON d.dbid1 = mdf.database_id and mdf.[type] = 0
JOIN sys.master_files ldf 
ON d.dbid1 = ldf.database_id and ldf.[type] = 1
JOIN sys.databases sdb
ON d.dbid1 = sdb.database_id
ORDER BY d.dbname;

T-SQL: Summary of all Stored Procs in DB

SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DB_Name ,
        o.name AS SprocName ,
        o.Create_date ,
        sm.[definition] AS 'Stored Procedure script'
FROM    sys.objects o
        INNER JOIN sys.sql_modules sm ON o.object_id = sm.object_id
WHERE   o.[type] = 'P' -- Stored Procedures
        -- AND sm.[definition] LIKE '%insert%'
        -- AND sm.[definition] LIKE '%update%'
        -- AND sm.[definition] LIKE '%delete%'
        -- AND sm.[definition] LIKE '%tablename%'

ORDER BY o.name;

T-SQL: Summary of all Functions in DB

-- Function details
SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DB_Name ,
        o.name AS 'FunctionName' ,
        o.[type] ,
        o.create_date ,
        sm.[DEFINITION] AS 'Function script'
FROM    sys.objects o
        INNER JOIN sys.sql_modules sm ON o.object_id = sm.OBJECT_ID
WHERE   o.[Type] = 'FN' -- Function

ORDER BY o.NAME;

T-SQL: Summary of all Columns in DB

Verified in SQL 2008 R2:

SELECT  @@Servername AS Server ,
        DB_NAME() AS DBName ,
        isc.Table_Name AS TableName ,
        isc.Table_Schema AS SchemaName ,
        Ordinal_Position AS Ord ,
        Column_Name ,
        Data_Type ,
        Numeric_Precision AS Prec ,
        Numeric_Scale AS Scale ,
        Character_Maximum_Length AS LEN , -- -1 means MAX like Varchar(MAX)
        Is_Nullable ,
        Column_Default ,
        Table_Type
        --,CASE WHEN ISNULL(col.Computed_Column,'0') = '0' THEN '0' ELSE '1' END as IsComputed
        ,col.definition as ComputedDefinition
FROM    INFORMATION_SCHEMA.COLUMNS isc
        INNER JOIN information_schema.tables ist ON isc.table_name = ist.table_name
LEFT OUTER JOIN (
SELECT  t.Name AS TableName ,
c.Column_ID AS Ord ,
c.Name AS Computed_Column
,cc.definition
FROM    sys.Tables t
INNER JOIN sys.Columns c ON t.object_id = c.object_id
INNER JOIN sys.computed_columns cc ON t.object_id = cc.object_id AND c.column_id = cc.column_id
--WHERE   c.is_computed = 1
--ORDER BY TableName, Ord
) col on col.TableName = isc.TABLE_NAME AND col.Computed_Column = COLUMN_NAME
ORDER BY DBName,TABLE_TYPE,TableName,SchemaName
,Ordinal_position

T-SQL: Summary of all tables in a DB

To see a summary of all tables in a DB, similar to the OOTB report:

SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DBName ,
        sub.SchemaName
        ,o.name AS 'TableName'
        --,sub.NumRows
        ,subb.RowCounts
        ,subb.UsedSpaceKB
        ,subb.TotalSpaceKB
        ,sub.type_desc
        ,o.create_date
        ,o.modify_date
FROM    sys.objects o
JOIN (
SELECT  OBJECT_SCHEMA_NAME(p.object_id) AS SchemaName ,
OBJECT_NAME(p.object_id) AS TableName ,
i.Type_Desc ,
i.Name AS IndexUsedForCounts ,
SUM(p.Rows) AS NumRows,
p.object_id as TableID
FROM    sys.partitions p
JOIN sys.indexes i ON i.object_id = p.object_id AND i.index_id = p.index_id
WHERE   i.type_desc IN ( 'CLUSTERED', 'HEAP' ) -- This is key (1 index per table)
AND OBJECT_SCHEMA_NAME(p.object_id) <> 'sys'
GROUP BY p.object_id , i.type_desc , i.Name
--ORDER BY SchemaName , TableName
) sub ON sub.TableName = o.name
INNER JOIN (
SELECT
t.NAME AS TableName,
--s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM sys.tables t
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
--LEFT OUTER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY t.Name, p.Rows
) subb on subb.TableName = o.name
WHERE   o.Type = 'U' -- User table
ORDER BY
-- o.name
UsedSpaceKB desc

Tuesday, June 21, 2016

Reporting Document Version Sizes in SharePoint 2007 via PowerShell

Here's some PowerShell to crawl SharePoint 2007 webs to report on all document libraries, the documents, and the versions. The output csv can then be opened in Excel and filtered, pivoted, etc.

Paste the code below into a .ps1 file, and call it from a PowerShell prompt on a WFE in the SharePoint 2007 farm.
Param(
  [Parameter(Mandatory=$true)] [string]$siteCollectionUrl = 'http://rootweb',
  [string]$delimiter = "`t",
  [int]$maxWebs = 200
)
$dateStr = '{0:yyyyMMdd-HHmm}' -f $(Get-Date)
$outfile = "VersionSizeReport_$dateStr.csv"
function MAIN
{
  #Call the Function to Generate Version History Report
  GenerateVersionSizeReport $siteCollectionUrl
}
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
Function Get-SPWebApplication()
{
  Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
  return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
}

Function global:Get-SPSite()
{
  Param( [Parameter(Mandatory=$true)] [string]$SiteCollURL )
  if($SiteCollURL -ne '')
  {
    return new-Object Microsoft.SharePoint.SPSite($SiteCollURL)
  }
}
Function global:Get-SPWeb()
{
  Param( [Parameter(Mandatory=$true)] [string]$SiteURL )
  $site = Get-SPSite($SiteURL)
  if($site -ne $null)
  {
    $web=$site.OpenWeb();
  }
  return $web
}

Function GenerateVersionSizeReport()
{  
  Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
  $WebApp=Get-SPWebApplication($WebAppURL)

  #Write the CSV Header - Tab Separated
  "Site Name$($delimiter)Library$($delimiter)File URL$($delimiter)File Type$($delimiter)Last Modified$($delimiter)Item Versions$($delimiter)File Versions$($delimiter)Latest Version Size(MB)$($delimiter)Versions Size(MB)$($delimiter)Total File Size(MB)" |
    out-file $outfile

  #Loop through each site collection
  foreach($Site in $WebApp.Sites)
  {
    $webCount = 0
    foreach($Web in $Site.AllWebs)
    {
      $webCount++
      if (($webCount -le $maxWebs) -and ($webCount -ne -1))
      {
        Write-Host "WEB: $($Web.url)"
        foreach ($List in $Web.Lists)
        {
          Write-Host "`nLIST (Items:$($List.ItemCount), Type:$($List.BaseType)): $($Web.url)$($List.RootFolder.ServerRelativeUrl)"
          #if ( ($List.BaseType -eq "DocumentLibrary") -and ($List.Hidden -eq $false) )
          if ($List.BaseType -eq "DocumentLibrary")
          #if ($List.EnableVersioning -eq $true)
          {
            $itemNum = 0
            Write-Host "`t" -noNewLine
         
            foreach ($ListItem  in $List.Items)
            {
              $itemNum++
              if (-not ($itemNum % 10))
              {
                Write-Host "$itemNum " -noNewLine
              }
              if (-not ($itemNum % 200))
              {
                Write-Host "`n`t" -noNewLine
              }
              $versionSize=0

              #Get the versioning details
              foreach ($FileVersion in $ListItem.File.Versions)
              {
                $versionSize = $versionSize + $FileVersion.Size;
              }
              #To Calculate Total Size(MB)
              $TotalFileSize= [Math]::Round(((($ListItem.File.Length + $versionSize)/1024)/1024),2)
             
              #Convert Size to MB
              $VersionSize= [Math]::Round((($versionSize/1024)/1024),2)
             
              #Get the Size of the current version
              $CurrentVersionSize= [Math]::Round((($ListItem.File.Length/1024)/1024),2)
             
              #Get Site Name
              if ($Web.IsRootWeb -eq $true)
              {
                $siteName = $Web.Title +" - Root";
              }
              else
              {
                $siteName= $Site.RootWeb.Title + " - " + $Web.Title;
              }

              "$($siteName)"`
              + "$($delimiter)$($List.RootFolder.ServerRelativeUrl)"`
              + "$($delimiter)$($Web.Url)/$($ListItem.Url)"`
              + "$($delimiter)$($ListItem['File Type'].ToString())"`
              + "$($delimiter)$($ListItem['Modified'].ToString())"`
              + "$($delimiter)$($ListItem.Versions.Count)"`
              + "$($delimiter)$($ListItem.File.Versions.Count)"`
              + "$($delimiter)$CurrentVersionSize"`
              + "$($delimiter)$versionSize"`
              + "$($delimiter)$TotalFileSize"`
              | Out-File $outfile -Append
            }
          }
        } #webcount maxcount
      }
    $Web.Dispose()      
    }
  $Site.Dispose()      
  }
  write-host "`n`nVersioning Report Generated Successfully!`n$outfile"
}

MAIN


Monday, June 20, 2016

Assessing And Trimming SP 2007 AuditData table

In SharePoint 2007, the content database is where SharePoint stores the audit data, in a table named AuditData. It can grow quickly, and there is no automated OOTB way to keep only a certain number of days or up to a certain size. This has to be done manually.

First, running a query or two on the AuditData table can help confirm that the data is no longer needed.
SELECT MIN(Occurred) as 'Earliest'
,MAX(Occurred) as 'Latest'
,COUNT(*) as 'EventCount'
FROM AuditData
This gives us some basic info:
EarliestLatestEventCount
2009-06-19 20:12:13.0002014-01-02 22:02:09.000273213041

First we can look at how many events are happening per day:
SELECT CONVERT(date,Occurred) as 'EventDate'
  ,COUNT(*) as 'EventCount'
FROM AuditData
GROUP BY CONVERT(date,Occurred)
ORDER BY CONVERT(date,Occurred)
That will skip dates with 0 events. If you want to include every date, you'd need to do something like this:
DECLARE @dateRange TABLE (dateValue DATE)
DECLARE @date DATE, @EndDate DATE
SELECT @date='2009-06-18', @EndDate='2014-01-03'
WHILE @date <= @EndDate
BEGIN
  INSERT INTO @dateRange VALUES (@date)
  SET @date = DATEADD(d,1,@date)
END
SELECT dr.dateValue as 'EventDate'
  ,ISNULL(a.EventCount,0)
FROM @dateRange dr
LEFT OUTER JOIN (
  SELECT CONVERT(date,Occurred) as 'EventDate' 
    ,COUNT(*) as 'EventCount'
  FROM AuditData  GROUP BY CONVERT(date,Occurred)
) as a
  ON a.EventDate = dr.dateValue
ORDER BY dr.dateValue

We can see the sum of events per type per year:
SELECT ad.EventId
  ,YEAR(Occurred) as 'EventYear'
  ,COUNT(*) as 'EventCount'
FROM AuditData ad
GROUP BY ad.EventId
  ,YEAR(Occurred)
ORDER BY YEAR(Occurred), ad.EventId
If we need to pivot that data:
SELECT pvt.EventId
  ,ISNULL([2009],0) AS '2009'
  ,ISNULL([2010],0) AS '2010'
  ,ISNULL([2011],0) AS '2011'
FROM (
  SELECT EventId
    ,CONVERT(date,Occurred) as 'EventDate'
    ,YEAR(Occurred) as 'EventYear'
  FROM AuditData ad
) as SourceTable
PIVOT (
  COUNT(EventDate)
  FOR EventYear IN ([2009],[2010],[2011])
) as pvt
ORDER BY pvt.EventId

Then, if we want to get fancy, we can make this more human readable by replacing some IDs with actual values.

For the Event Types:
DECLARE @EventTypes TABLE (Id int, Name nvarchar(100))
INSERT INTO @EventTypes
SELECT 1, 'CheckOut' UNION ALL
SELECT 2, 'CheckIn' UNION ALL
SELECT 3, 'View' UNION ALL
SELECT 4, 'Delete' UNION ALL
SELECT 5, 'Update' UNION ALL
SELECT 6, 'ProfileChange' UNION ALL
SELECT 7, 'ChildDelete' UNION ALL
SELECT 8, 'SchemaChange' UNION ALL
SELECT 10, 'Undelete' UNION ALL
SELECT 11, 'Workflow' UNION ALL
SELECT 12, 'Copy' UNION ALL
SELECT 13, 'Move' UNION ALL
SELECT 14, 'AuditMaskChange' UNION ALL
SELECT 15, 'Search' UNION ALL
SELECT 16, 'ChildMove' UNION ALL
SELECT 30, 'SecGroupCreate' UNION ALL
SELECT 31, 'SecGroupDelete' UNION ALL
SELECT 32, 'SecGroupMemberAdd' UNION ALL
SELECT 33, 'SecGroupMemberDel' UNION ALL
SELECT 34, 'SecRoleDefCreate' UNION ALL
SELECT 35, 'SecRoleDefDelete' UNION ALL
SELECT 36, 'SecRoleDefModify' UNION ALL
SELECT 37, 'SecRoleDefBreakInherit' UNION ALL
SELECT 38, 'SecRoleBindUpdate' UNION ALL
SELECT 39, 'SecRoleBindInherit' UNION ALL
SELECT 40, 'SecRoleBindBreakInherit' UNION ALL
SELECT 50, 'EventsDeleted' UNION ALL
SELECT 100, 'Custom' 
For the Item Types:
DECLARE @ItemTypes TABLE (Id int, Name nvarchar(100))
INSERT INTO @ItemTypes
SELECT 1, 'Page/File' UNION ALL
SELECT 3, 'List Item' UNION ALL
SELECT 4, 'List' UNION ALL
SELECT 5, 'Folder' UNION ALL
SELECT 6, 'Web' UNION ALL
SELECT 7, 'Site Collection'
For User Info, you'll need to get that info from the UserInfo table, for what you need:
DECLARE @UserInfo TABLE (
  SiteId uniqueidentifier
  ,UserId int
  ,UserLogin nvarchar(255))
INSERT INTO @UserInfo
SELECT DISTINCT ad.SiteId
  ,ad.UserId  ,ui.tp_Login
FROM AuditData ad
LEFT OUTER JOIN UserInfo ui 
  ON ad.UserId = ui.tp_ID     AND ad.SiteId = ui.tp_SiteID

So your Yearly Pivoted data could be:
SELECT et.Id
,et.Name
  ,ISNULL([2009],0) AS '2009'
  ,ISNULL([2010],0) AS '2010'
  ,ISNULL([2011],0) AS '2011'
FROM (
  SELECT EventId
    ,CONVERT(date,Occurred) as 'EventDate'
    ,YEAR(Occurred) as 'EventYear'
  FROM AuditData ad
) as SourceTable
PIVOT (
  COUNT(EventDate)
  FOR EventYear IN ([2009],[2010],[2011])
) as pvt
RIGHT OUTER JOIN @EventTypes et
ON pvt.EventId = et.Id
ORDER BY et.Id



Now for getting rid of it.

If this is a non-production environment, then modifying the SharePoint database is a possibility, and quicker to just truncate the table.

Otherwise, use PowerShell to call STSADM 1 day at a time (to prevent transaction logs and such from filling drive and failing).
########################################
# TrimAuditLog via PowerShell and STSADM
#
# Authored: 2016/06/12
# Author: Steve Cervenak
########################################
# Set these variables to appropriate values
$startDate = [datetime]"6/1/2009"
$endDate = [datetime]"1/3/2014"
$url = "http://siteUrl"
$logFile = "C:\ps\trimLog.log"
##################################################
set-alias STSADM "${env:commonprogramfiles}\Microsoft Shared\Web Server Extensions\12\BIN\STSADM.EXE"
$timer = [system.diagnostics.stopwatch]::StartNew()
$subtimer = [system.diagnostics.stopwatch]::StartNew()
$logmsg = "$($timer.Elapsed.ToString()): Starting '$startDate' through '$endDate'"
$logmsg | Out-File $logFile -Append
Write-Host $logmsg
$date = $startDate
while ($date -le $endDate)
{
    $subtimer.Reset()
    $subtimer.Start()
    $dateStr = $date.ToString('yyyyMMdd')
    Write-Host "$($timer.Elapsed.ToString()): Trimming through '$dateStr'"
    STSADM -o trimauditlog -url $url -date $dateStr
    $logmsg = "$dateStr,$($subtimer.Elapsed.TotalSeconds)"
    $logmsg | Out-File $logFile -Append  
    Write-Host "$($timer.Elapsed.TotalSeconds) secs: $logmsg seconds`n`n" -f green
 
    $date = $date.AddDays(1);
}
$logmsg = "$($timer.Elapsed.ToString()): Completed '$startDate' through '$endDate'"
$logmsg | Out-File $logFile -Append
Write-Host "$logmsg `nCOMPLETE"



Here's a link to a PowerShell script that can export the audit data to a csv if that is needed: http://sharepoint.stackexchange.com/questions/119915/how-to-archive-the-auditdata-table-on-a-contentdb

Copied here:
$tabName = "AuditLog"

#Create Table object
$table = New-Object system.Data.DataTable $tabName

#Define Columns
$col1 = New-Object system.Data.DataColumn SiteUrl,([string])
$col2 = New-Object system.Data.DataColumn SiteID,([string])
$col3 = New-Object system.Data.DataColumn ItemName,([string])
$col4 = New-Object system.Data.DataColumn ItemType,([string])
$col5 = New-Object system.Data.DataColumn UserID,([string])
$col6 = New-Object system.Data.DataColumn UserName,([string])
$col7 = New-Object system.Data.DataColumn Occurred,([DateTime])
$col8 = New-Object system.Data.DataColumn Event,([string])
$col9 = New-Object system.Data.DataColumn Description,([string])
$col10 = New-Object system.Data.DataColumn EventSource,([string])
$col11 = New-Object system.Data.DataColumn SourceName,([string])
$col12 = New-Object system.Data.DataColumn EventData,([string])
$col13 = New-Object system.Data.DataColumn MachineName,([string])
$col14 = New-Object system.Data.DataColumn MachineIP,([string])

#Add the Columns
$table.columns.add($col1)
$table.columns.add($col2)
$table.columns.add($col3)
$table.columns.add($col4)
$table.columns.add($col5)
$table.columns.add($col6)
$table.columns.add($col7)
$table.columns.add($col8)
$table.columns.add($col9)
$table.columns.add($col10)
$table.columns.add($col11)
$table.columns.add($col12)
$table.columns.add($col13)
$table.columns.add($col14)

$site = Get-SPSite -Identity http://SiteCollectionName
$wssQuery = New-Object -TypeName Microsoft.SharePoint.SPAuditQuery($site)
$auditCol = $site.Audit.GetEntries($wssQuery)
$root = $site.RootWeb

for ($i=0; $i -le ($auditCol.Count)-1 ; $i++)
{
    #Get the Entry Item from the Collection
    $entry = $auditCol.item($i)

    #Create a row
    $row = $table.NewRow()

    #find the Current UserName 
    foreach($User in $root.SiteUsers)
    {
        if($entry.UserId -eq $User.Id)
        {
             $UserName = $User.UserLogin
        }
    }   

    #find the Item Name
    foreach($List in $root.Lists)
    {
        if($entry.ItemId -eq $List.Id)
        {
             $ItemName = $List.Title
        }
    }   

    #Define Description for the Event Property
     switch ($entry.Event)
    {
        AuditMaskChange{$eventName = "The audit flags are changed for the audited object."}
        ChildDelete {$eventName = "A child of the audited object is deleted."}
        ChildMove {$eventName = "A child of the audited object is moved."}
        CheckIn {$eventName = " A document is checked in."}
        'Copy' {$eventName = "The audited item is copied."}
        Delete {$eventName = "The audited object is deleted."}
        EventsDeleted {$eventName = "Some audit entries are deleted from SharePoint database."}
        'Move' {$eventName = "The audited object is moved."}
        Search {$eventName = "The audited object is searched."}
        SecGroupCreate {$eventName = "A group is created for the site collection. (This action also generates an Update event.See below.)"}
        SecGroupDelete {$eventName = "A group on the site collection is deleted."}
        SecGroupMemberAdd {$eventName = "A user is added to a group."}
        SecGroupMemberDelete {$eventName = "A user is removed from a group."}
        SecRoleBindBreakInherit {$eventName = "A subsite's inheritance of permission level definitions (that is, role definitions) is severed."}
        SecRoleBindInherit {$eventName = "A subsite is set to inherit permission level definitions (that is, role definitions) from its parent."}
        SecRoleBindUpdate {$eventName = "The permissions of a user or group for the audited object are changed."}
        SecRoleDefCreate {$eventName = "A new permission level (a combination of permissions that are given to people holding a particular role for the site collection) is created."}
        SecRoleDefDelete {$eventName = "A permission level (a combination of permissions that are given to people holding a particular role for the site collection) is deleted."}
        SecRoleDefModify {$eventName = "A permission level (a combination of permissions that are given to people holding a particular role for the site collection) is modified."}
        Update {$eventName = "An existing object is updated."}
        CheckOut {$eventName = " A document is checked Out."}
        View {$eventName = "Viewing of the object by a user."}
        ProfileChange {$eventName = "Change in a profile that is associated with the object."}
        SchemaChange {$eventName = "Change in the schema of the object."}
        Undelete {$eventName = "Restoration of an object from the Recycle Bin."}
        Workflow {$eventName = "Access of the object as part of a workflow."}
        FileFragmentWrite {$eventName = "A File Fragment has been written for the file."}
        Custom {$eventName = "Custom action or event."}
        default {$eventName = "The Event could not be determined."}
    }

    #Enter data in the row
    $row.SiteUrl = $site.Url
    $row.SiteID = $entry.SiteID
    $row.ItemName = $ItemName
    $row.ItemType = $entry.ItemType
    $row.UserID = $entry.UserID
    $row.UserName = $UserName
    $row.Occurred = $entry.Occurred
    $row.Event = $entry.Event
    $row.Description = $eventName
    $row.EventSource = $entry.EventSource
    $row.SourceName = $entry.SourceName
    $row.EventData = $entry.EventData
    $row.MachineName = $entry.MachineName
    $row.MachineIP = $entry.MachineIP

    #Add the row to the table
    $table.Rows.Add($row)

}

$date = get-date -format "d-M-yyyy"
$sDtae = [string]$date
$FileName = "AuditLogReport_For_" + $sDtae
#Export the CSV File to Folder Destination
$tabCsv = $table | export-csv C:\$FileName.csv -noType