在 PowerShell 中删除用户配置文件偶尔会留下配置文件

Deleting user profiles in PowerShell occasionally leaves behind profiles

我创建了我的第一个 PowerShell 脚本来批量删除用户配置文件,在大多数情况下它工作正常,但是,当 Get-CimInstance win32_UserProfile 是 运行.

尽管 PowerShell 似乎看不到这些配置文件,但它们确实会被脚本触及,因此它们的最后访问日期是最新的,除了它们的 appdata 文件夹之外的所有内容都被删除,它们仍在 C:\Users目录。

我目前唯一的解决方案是在 Users 中手动 select 这些配置文件,然后删除它们,但我正在尝试完全自动化此过程。我不知道是什么导致了这种情况,因此非常感谢任何建议或指导。这是我的代码:

# Grab all the user profiles and ignore anything in our exceptions
$Profiles = Get-CimInstance Win32_UserProfile | where {((!$_.Special) -and ($_.LocalPath -ne "C:\Users\Administrator") -and ($_.LocalPath -ne "C:\Users\admin1") -and ($_.LocalPath -ne "C:\Users\admin2") -and ($_.LocalPath -ne "C:\Users\admin3") -and ($_.LocalPath -ne "C:\Users\admin4"))}

# Get the number of profiles to use in -PercentComplete
$ProfilesCount = $Profiles.Count 

# This for loop iterates through profiles and deletes them as well as creates our progress bar
Function ProfilesB-Gone 
{
    for ($i = 1; $i -lt $ProfilesCount; $i++)
    { 
        # Our progress bar is generated and updated 
        Write-Progress -Activity 'Removing Profiles' -Status "Deleted $i out of $ProfilesCount profiles" -PercentComplete (($i/$ProfilesCount) * 100) 

        # Here we're suppressing errors and continuing while deleting our profiles 
        Remove-CimInstance $Profiles[$i] -EV Err -EA SilentlyContinue 
    }
    # Remove progress bar once complete
    Write-Progress -Activity 'Removing Profiles' -Status 'Complete!' -Completed
}

# Call function
ProfilesB-Gone;

# Remove all leftover profiles that remain ocasionally due to noncritical and inconsistent bug and suppress errors. Not suppressing errors causes as many error windows to show as there were $ProfilesCount.
$Profiles | Remove-CimInstance -EV Err -EA SilentlyContinue 

# Give success message to inform user of script completion
Write-Host "Profiles Deleted!"

一个 win10 应用程序 (MicrosoftOfficeHub) 生成了无法以正常方式删除的奇怪链接。当 powershell 和 wmi 不可用时,使用 cmd /c rmdir /s /q c:\users\user 之类的东西仍然有效。