Pre Migration Offline Cache Report Powershell Script

john zuh 51 Reputation points
2021-02-04T11:21:01.247+00:00

I am trying to achieve the follow steps below so i decided to put something together quickly above
A script needs to be created running in the user context (like the login script) that checks the Offline Cache Status.

  • If Offline Cache is deactivated no further actions are necessary
  • If Offline Cache is activated the script needs to check the last sync date:
  • If this is older than 1 week the script needs to write the user account and the last sync date in an error report which is accessible to me
  • If the sync date is less than one week ago the Offline Cache should be deactivated

I couldn't define variables for the Get-WMIObject functions cos they weren't producing accurate results so decided to utilize functions directly functions directly. Date , time just dummy

$LastSyncTime = Get-WmiObject Win32_FolderRedirectionHealthConfiguration | Select LastSyncDurationCautionInHours, LastSyncDurationUnhealthyInHours | where {$.LastSyncDurationCautionInHours -ge "240" -and $.LastSyncDurationUnhealthyInHours -ge "480"}
$Username = Get-WMIObject -class Win32_ComputerSystem | select username | Out-String

#Check VPN is connected if not alert user to connect 
#Check Offline Cache is enabled and active if yes check last sync Activity if more than a week write out Last Syn Date & USer Account info my email
if((get-wmiobject -class win32_networkadapter | select netconnectionid, name, InterfaceIndex, netconnectionstatus | where {$_.netconnectionstatus -match "2" -and $_.netConnectionid -match "Ethernet 2" -and $_.name -like "VPN Client Name"}) -and 
(Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache"  | where {$_.Active -match "True" -and $_.Enabled -eq "True"}) -and 
(Get-WmiObject Win32_FolderRedirectionHealthConfiguration | Select  LastSyncDurationCautionInHours, LastSyncDurationUnhealthyInHours | where {$_.LastSyncDurationCautionInHours -ge "240" -and $_.LastSyncDurationUnhealthyInHours -ge "480"}))
    Send-MailMessage -to "Offline Cache Analysis <xyz@Champ.com>" -from "LastSyncReport <xyz@Champ.com>" -subject "Offline File Last Sync" -Body "$($Username;$LastSyncTime)" -smtpserver "Champ.com"

#If Offline Sync activity is less than a week check lsimply Deactivate, reboot where required. 
    if((Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache"  | where {$_.Active -match "True" -and $_.Enabled -eq "True"}) 
 -and (Get-WmiObject Win32_FolderRedirectionHealthConfiguration | Select  LastSyncDurationCautionInHours, LastSyncDurationUnhealthyInHours | where {$_.LastSyncDurationCautionInHours -lt "240" -and $_.LastSyncDurationUnhealthyInHours -lt "480"})){
           Invoke-CimMethod -ClassName Win32_OfflineFilesCache -MethodName Enable -Arguments @{Enable = $false}
           if ($OSCInactive.RebootRequired){
           write-host "Computer will force restart to in order to disable offline Cache." -F Yellow
           sleep -Seconds 5
           restart-computer -Force
     }      
   }
}
else{Write-Host "Your VPN is disconnected, :( Please Connect Your VPN and run the Script Again" -ForegroundColor "Red"}
Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,717 questions
Windows
Windows
A family of Microsoft operating systems that run across personal computers, tablets, laptops, phones, internet of things devices, self-contained mixed reality headsets, large collaboration screens, and other devices.
4,802 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,390 questions
{count} votes

2 answers

Sort by: Most helpful
  1. john zuh 51 Reputation points
    2021-02-08T23:42:52.83+00:00

    Hi @Ian Xue (Shanghai Wicresoft Co., Ltd.) What i meant by accurate results is to verify if Last Sync Activity between Offline Cache and Netshare was greater than 1 week, if yes send an Email alert to the admin but the CIM Classes win32_OfflineFilesCache doesnt include classes to check last sync status for Offline File Cache so i decided to use the Last Read /Write Activity to the C:\Windows\CSC or Synced Netshare in order to get the LastWrite Activity (TimeStamp) and then compare if it was more than one week. I dont know if that is enough or accurate. I also found https://learn.microsoft.com/en-us/previous-versions/windows/desktop/offlinefiles/win32-offlinefilesfilesysinfo . I also tried filtering through Win32_UserProfile but the information there wasn't that useful. There was a similar issue reported on this post https://social.technet.microsoft.com/Forums/ie/en-US/cdc831e8-1431-4c6a-9b3d-b835da8b7fbd/redirected-folder-offline-files-health?forum=winserverfiles. I have the second version of the Script below with a few changes like using Get-CimInstance instead of Get-wmiobject in some cases and adding a few more conditions based on the use case unique to us. I couldn't use the assigned variables because results were inconsistent using them, i dont know if it was due to the datatypes etc. Some recommendations and/or improvements will be very much appreciated.

    Unused Variables

    #$LastSyncTimeGreater = Get-CimInstance -Class Win32_UserProfile | Select Win32_FolderRedirectionHealth | where {$_.LastSuccessfulSyncTime -ge "(Get-Date).AddDays(-7)" -or $_.LastSyncTime -ge "(Get-Date).AddDays(-7)" -or $_.LastSyncStatus -eq "3" -and  $_.OfflineAccessEnabled -eq "$true" -and $_.redirected -eq "$true"}  
        $Username = Get-CimInstance -class Win32_ComputerSystem | select username | Out-String  
        $CSCInactive = Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache"  | where {$_.Active -match "$False" -and $_.Enabled -eq "$True"}  
        $CSCDisabled = Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache"  | where {$_.Active -match "$False" -and $_.Enabled -eq "$False"}  
        $RebootRequired = Invoke-CimMethod -ClassName Win32_OfflineFilesCache -MethodName Enable -Arguments @{Enable = $false} | where {$_.RebootRequired -eq "$True"}  
        #$LastWriteNetShare = Get-Childitem "\\NetShare\HomeDrive\" | Select LastWriteTime |  where {$_.LastWirteTime -le $WeekOld}  
        $LastWriteCSC = Get-item C:\Windows\CSC | Select LastWriteTime |  where {$_.LastWirteTime -le $WeekOld}  
        $WeekOld =(Get-Date).AddDays(-7)  
        $Username = Get-CimInstance -class Win32_ComputerSystem | select username | Out-String  
    

    Start Script Block

        #Verify if VPN is connected if not, notify user to connect in order to proceed  
        if(Get-CimInstance -class win32_networkadapter | where {$_.netconnectionstatus -eq "2" -and $_.netConnectionid -match "Ethernet 2" -and $_.name -like "VPN Client"}){  
            Write-Host "VPN Connected, We shall go ahead and conduct Offline Cache Analysis" -ForegroundColor "Green"  
          
        #No further Action Required in case Offline Cache is already disabled, you proceed with Migration  
        If(Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache"  | where {$_.Active -match "$False" -and $_.Enabled -eq "$False"}){  
          Write-Host "No further Action Required, Offline Cache is already disabled, You can commence with your Migration"  
          }     
            
        #If Offline Cache is enabled, check last Sync and Notify Administrator in case Last Sync Activity is older than a week. If Offline Cache is Disabled but requires reboot, pls go ahead and reboot.   
              if((Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache" | where {$_.Active -eq "$True" -and $_.Enabled -eq "$True" -or $_.Active -eq "$False"}) -and (Get-Item "C:\Windows\CSC" | Select LastWriteTime | where {$_.LastWirteTime -gt $WeekOld})){  
                 Send-MailMessage -to "Offline Cache Analysis <admin@domain.com>" -from "LastSyncActivityReport <admin@domain.com>" -subject "Offline Cache Last Sync Activity" -Body "$($Username|Out-String;$LastWriteCSC|Out-String)" -smtpserver "Xchange.comm.net"  
                 }  
                 if((Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache" | where {$_.Active -eq "$True" -or $_.Enabled -eq "$True"}) -and (Get-Item "C:\Windows\CSC" | where {$_.LastWirteTime -le $WeekOld})) {  
                      Invoke-CimMethod -ClassName Win32_OfflineFilesCache -MethodName Enable -Arguments @{Enable = $false}  
                      }  
                       if((Get-wmiobject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache"  | where {$_.Active -match "$True" -and $_.Enabled -eq "$False"}) -or (Invoke-CimMethod -ClassName Win32_OfflineFilesCache -MethodName Enable -Arguments @{Enable = $false} | where {$_.RebootRequired -eq "$True"})){  
                             write-host "Computer will Force restart in order to disable offline Cache. Run the Script again after restarting Computer" -F Yellow  
                             sleep -Seconds 10  
                             restart-computer -Force  
                          }       
                      }          
    Else{Write-Host "Your VPN is disconnected, Please Connect Your VPN and run the Script Again" -ForegroundColor "Red"}  
    

  2. Rich Matheisen 45,096 Reputation points
    2021-02-09T22:39:10.513+00:00

    In addition to the true/false problem IanXue pointed out, you have an undefined variable named "$OSCInactive" you're checking for the property "RebootRequired", and a missing set of "{" and "}" surrounding the Send-MailMessage

    You can also eliminate most of your "Select-Object" cmdlets since you only creating a PSCustomObject that holds the same property names that are present in the object from which you're extracting them.

    I cleaned up the code a bit (except for the undefined object problem):

    $LastSyncTime = Get-WmiObject Win32_FolderRedirectionHealthConfiguration | 
        Where-Object { $.LastSyncDurationCautionInHours -ge "240" -and $.LastSyncDurationUnhealthyInHours -ge "480" }
    $Username = Get-WmiObject -class Win32_ComputerSystem | 
        Select-Object username | 
            Out-String
    
    #Check VPN is connected if not alert user to connect 
    #Check Offline Cache is enabled and active if yes check last sync Activity if more than a week write out Last Syn Date & USer Account info my email
    if ((Get-WmiObject -class win32_networkadapter | 
            Where-Object { $_.netconnectionstatus -match "2" -and $_.netConnectionid -match "Ethernet 2" -and $_.name -like "VPN Client Name" }
        ) -and 
        (Get-WmiObject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache" | 
            Where-Object { $_.Active -and $_.Enabled}
        ) -and 
        (Get-WmiObject Win32_FolderRedirectionHealthConfiguration | 
            Where-Object { $_.LastSyncDurationCautionInHours -ge "240" -and $_.LastSyncDurationUnhealthyInHours -ge "480" }
        )
    ){
        Send-MailMessage -to "Offline Cache Analysis <xyz@Champ.com>" -from "LastSyncReport <xyz@Champ.com>" -subject "Offline File Last Sync" -Body "$($Username;$LastSyncTime)" -smtpserver "Champ.com"
    }
    #If Offline Sync activity is less than a week check lsimply Deactivate, reboot where required. 
    if ((Get-WmiObject -computername localhost -Namespace root\CIMV2 -Query "Select * from Win32_OfflineFilesCache" | 
            Where-Object { $_.Active -and $_.Enabled}
        ) -and 
        (Get-WmiObject Win32_FolderRedirectionHealthConfiguration | 
            Where-Object { $_.LastSyncDurationCautionInHours -lt "240" -and $_.LastSyncDurationUnhealthyInHours -lt "480" }
        )
    ){
        Invoke-CimMethod -ClassName Win32_OfflineFilesCache -MethodName Enable -Arguments @{Enable = $false }
        if ($OSCInactive.RebootRequired) {
            Write-Host "Computer will force restart to in order to disable offline Cache." -F Yellow
            Start-Sleep -Seconds 5
            Restart-Computer -Force
        }      
    }
    else{ 
        Write-Host "Your VPN is disconnected, :( Please Connect Your VPN and run the Script Again" -ForegroundColor "Red" 
    }
    
    0 comments No comments