title: How to delete old profiles with script
body: <p>So I am trying to adapt this code I got from another post for the needs of my current organization. Please see below code:</p>
  <pre><code>$Admin = &quot;Administrator&quot;,&quot;Public&quot;,&quot;Default&quot;,&quot;Administrator&quot;
  
  foreach($file in Get-ChildItem C:\Users\)
  {
      if ($file -in $Admin)
  
          {
              Write-Host = &quot;`r`nUser account is&quot; $file &quot;. This is an Administrator Account, it will not be deleted.&quot;
          }
  
      else
  
          {
  
              Write-Host = &quot;`r`nUser account is&quot; $file &quot;. Checking profiles age...&quot;
              $FileDate = (Get-item C:\Users\$file).CreationTime
              Write-Host = $FileDate 
              $TestDate = (Get-Date).addDays(-30)
              Write-Host = $TestDate
  
          If ($FileDate -lt $TestDate)
  
              {
                  Write-Host = &quot;Since&quot; $file &quot;is older than 30 Days (&quot; $FileDate &quot;) it will be deleted.&quot;
                  $UserAccountPath = &quot;C:\\Users\\$file&quot;
                  $WMIQuery = &quot;SELECT * FROM Win32_UserProfile WHERE localpath = '$UserAccountPath'&quot;
                  $UserProfile = get-wmiobject win32_userprofile | where localpath -eq c:\\users\\$file
                  Remove-WmiObject -InputObject &quot;$UserProfile&quot;
  
              }
  
          else
  
              {
                  Write-Host = &quot;Since File is dated less than 30 days old (&quot; $FileDate &quot;) it will not need to be deleted.&quot;
              }
  
          }
  
  }
  </code></pre>
  <p>After running this I get the following error:</p>
  <pre><code>Remove-WmiObject : Object reference not set to an instance of an object.
  At line:28 char:17
  +                 Remove-WmiObject -InputObject &quot;$UserProfile&quot;
  +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Remove-WmiObject], NullReferenceException
      + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.RemoveWmiObject
  </code></pre>
  <p>Any help is appreciated.</p>