我想通过删除最近6个月内未登录服务器的C:\用户的用户配置文件来释放服务器上的C盘空间。我使用PowerShell Cim命令连接到服务器。
到目前为止,我只发现了Get-CimInstance -CimSession $CimSession -ClassName Win32_UserProfile
命令,该命令将列出用户个人资料,但没有列出每个用户的上次登录时间。是否有另一个命令可用于使用LastLogon列出UserProfiles?有了该列表后,我想删除最近6个月内未登录服务器的所有配置文件。
答案 0 :(得分:0)
How to delete user profiles older than a specified number of days in Windows
此PowerShell脚本示例显示如何删除早于指定天数的用户配置文件。
Example 1:
C:\Script\RemoveLocalUserProfile.ps1 -ListUnusedDay 1
Example 2:
C:\Script\RemoveLocalUserProfile.ps1 -DeleteUnusedDay 1 -ExcludedUsers “marry”
# Begin Script
If ($ProfileInfo -eq $null)
{
Write-Warning -Message "The item not found."
}
Else
{
Foreach ($RemoveProfile in $ProfileInfo)
{
#Prompt message
$Caption = "Remove Profile"
$Message = "Are you sure you want to remove profile '$($RemoveProfile.LocalPath)'?"
$Choices = [System.Management.Automation.Host.ChoiceDescription[]]`
@("&Yes", "&No")
[Int]$DefaultChoice = 1
$ChoiceRTN = $Host.UI.PromptForChoice($Caption, $Message, $Choices, $DefaultChoice)
Switch ($ChoiceRTN)
{
0
{
Try {$RemoveProfile.Delete(); Write-Host "Delete profile '$($RemoveProfile.LocalPath)' successfully."}
Catch {Write-Host "Delete profile failed." -ForegroundColor Red}
}
1 {break}
}
}
$ProfileInfo|Select-Object @{Expression = {$_.__SERVER}; Label = "ComputerName"}, `
@{Expression = {$_.ConvertToDateTime($_.LastUseTime)}; Label = "LastUseTime"},`
@{Name = "Action"; Expression = {If (Test-Path -Path $_.LocalPath)
{"Not Deleted"}
Else
{"Deleted"}
}
}
}
# End Script
类似的方法可以在这里看到:
https://community.spiceworks.com/how_to/124316-delete-user-profiles-with-powershell
https://www.business.com/articles/powershell-manage-user-profiles
答案 1 :(得分:0)
删除个人资料时请多加注意,您不想访问计算机专用帐户。 Win32_UserProfile
类具有您可以依赖的LastUseTime
属性。
$session = New-CimSession -ComputerName $cn
$gcimParams = @{
'CimSession' = $session
'ClassName' = 'Win32_UserProfile'
'Filter' = 'RefCount<1 and Special="false" and Loaded="false"'
}
$profileList = (Get-CimInstance @gcimParams).Where{$PSItem.LastUseTime -lt (Get-Date).AddMonths(-6)}
foreach ($user in $profileList)
{
$user | Remove-CimInstance -CimSession $session
}