使用PowerShell在Windows中删除用户配置文件

时间:2019-01-25 10:50:26

标签: powershell

我正在创建一个脚本,该脚本应该删除Windows系统中最近180天未使用的配置文件。

以下是我的代码。

$profiles = Get-WMIObject -Class Win32_UserProfile | Where {
    (!$_.Special) -and
    ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-1))
}
$count = $profiles | Measure-Object | select -ExpandProperty Count
if ($count -eq 0) {
    Write-Output "No Profiles found for Deletion"
    exit
}
Write-Output "Number of profiles : $count"
$profiledeleted = @()
$profileerror = @()
foreach ($profile in $profiles) {
    $profile | Remove-WmiObject
    if ($?) {
        $profiledeleted += $profile.Localpath 
        continue
    } else {
        $profileerror += $profile.Localpath
    }
}
if ($profiledeleted.Length -gt 0) {
    Write-Output "Localpath of removed profiles"
    $profiledeleted
}
if ($profileerror.Length -gt 0) {
    Write-Output "Error While removing below profiles"
    $profileerror
}

该代码应与系统帐户一起运行,但出现以下错误。

Remove-WmiObject :
At C:\Users\Admin\GRT-2687_deleteunuseduserprofiles.ps1:22 char:32
+     $profile | Remove-WmiObject <<<<
    + CategoryInfo          : InvalidOperation: (:) [Remove-WmiObject], COMException
    + FullyQualifiedErrorId : RemoveWMICOMException,Microsoft.PowerShell.Commands.RemoveWmiObject

编辑:它将删除除文件夹C:\ Users \ Username之外的所有数据。

0 个答案:

没有答案