简单的脚本以删除旧的用户配置文件



我正在编写一个简单的脚本,该脚本将用于删除超过90天的用户配置文件。我可以捕获我想要的轮廓,但是当涉及"面包和黄油"时,我很难过。

我的代码:

$localuserprofiles = Get-WmiObject -Class Win32_UserProfile | Select-Object localPath,@{Expression={$_.ConvertToDateTime($_.LastUseTime)};Label="LastUseTime"}| Where{$_.LocalPath -notlike "*$env:SystemRoot*"} #Captures local user profiles and their last used date
$unusedday = 90 # Sets the unused prifile time threshold
$excludeduserpath = $excludeduser.LocalPath # Excludes the DeltaPC user account
$profilestodelete = $LocalUserProfiles | where-object{$_.lastusetime -le (Get-Date).AddDays(-$unusedday) -and $_.Localpath -notlike "*$excludeduserpath*"} #Captures list of user accounts to be deleted
#Deletes unused Profiles
Foreach($deletedprofile in $profilestodelete)
    {
        $deletedprofile.Delete()
    }

代码返回此错误:

Method invocation failed because [Selected.System.Management.ManagementObject] does not contain a method named 'Delete'. 
At line:3 char:13 
+ $deletedprofile.Delete()} 
+ ~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo : InvalidOperation: (Delete:String) [], RuntimeException 
    + FullyQualifiedErrorId : MethodNotFound

因为您要获得WMI对象,因此可以使用Remove-WMIObject CMDLET。

因此,只需修改删除循环,就应该正确删除所需的配置文件:

Foreach($deletedprofile in $profilestodelete)
    {
        Remove-WMIObject $deletedprofile
    }

根据其他答案,WMI提供的用户配置文件没有Delete()方法。虽然您只能删除配置文件目录,但通常不建议您留下其他各种数据(例如注册表条目(,如果这些用户随后将这些用户重新登录到机器。

有一个免费的第三方工具,名为delprof2.exe:https://www.sepago.com/blog/2011/05/01/new-free-delprof2-user-prof2-user-profile-deletion-toolion-tool

我没有亲自使用过,因此请谨慎使用,但是它似乎已经可以选择删除X天不活动的配置文件,例如:

Delprof2 /d:90

现在,如果您简单地删除用户配置文件目录会发生什么情况 在C下方:用户没有修改注册表?下次用户 Windows上的登录显示一个气球尖端,窗户无法发牢骚 加载用户配置文件,并使用临时登录用户 轮廓。那不好吗?是的!如果 Windows无法加载用户配置文件。注销后,它们被删除,并且 所有数据都丢失了。这当然是避免它们的原因。

  • https://www.sepago.com/blog/2011/05/01/new-free-delprof2-user-profile-deletion-tool-tool

在自定义对象$deletedprofile上没有定义任何Delete()方法。使用

Foreach($deletedprofile in $profilestodelete)
    {
        $aux = Get-Item $deletedprofile.localPath
        $aux.Delete()
    }

或简单

Foreach($deletedprofile in $profilestodelete)
    {
        (Get-Item $deletedprofile.localPath).Delete()
    }

您可能需要指定.Delete($true)

PS C:Windowssystem32> Get-Item  $profilestodelete[0].localPath | Get-Member -Name Delete

   TypeName: System.IO.DirectoryInfo
Name   MemberType Definition
----   ---------- ----------
Delete Method     void Delete(), void Delete(bool recursive)

编辑

正如Mark Wragg所述,不建议简单地删除用户配置文件目录,因为这不会从注册表中删除与配置文件关联的数据。另请参见详尽的文章删除本地用户配置文件 - 不像Helge Klein(delprof2工具的作者(那样容易

但是,有一个纯PowerShell脚本包含 a函数( Remove-UserProfile (,用于删除用户配置文件,以及C: Users目录(如果指定(的其他内容gallery.technet.microsoft.com的本地计算机 Remove-UserProfile-删除本地用户配置文件和清洁C:用户目录

最新更新