PowerShell 删除配置文件(注册表、配置文件文件夹和本地帐户)

问题描述 投票:0回答:1

我希望删除所有计算机上所有未使用的本地帐户(400+/-。)我有一个脚本,可用于删除我主要针对的 2 个本地帐户的基本部分,但我想确保它保留所有域帐户。有没有办法向 $AccountsToKeep 行添加通配符,以保留所有域帐户而无需输入每个帐户?我尝试了“DOMAIN*”,但似乎不起作用。

这是我正在使用的(除了“DOMAIN*”部分之外,它似乎有效):

$AccountsToKeep = @('administrator','Public','default', 'NetworkService', 'LocalService', 'SystemProfile', 'DOMAIN\*')
Get-CimInstance Win32_UserProfile | Where-Object { $PSItem.LastUseTime -lt [datetime]::Now.AddDays(-0) } | Remove-CimInstance

Remove-Item c:\users\local1 -Recurse -Force
Remove-Item c:\users\local2 -Recurse -Force
net user local1 /delete
net user local2 /delete
powershell profile
1个回答
0
投票

$_.Special -eq $false
子句中使用
Where-Object
可以避免在
$AccountsToKeep
变量中指定这些特殊帐户。

(Split-Path $_.LocalPath -Leaf) -notin $AccountsToKeep

 中使用 
Where-Object
 将忽略与用户配置文件文件夹的最后一个文件夹部分匹配的帐户。

使用

(New-Object System.Security.Principal.SecurityIdentifier($_)
逻辑将转换 SID 值(如果它们与域帐户 SID 匹配)。

-WhatIf

 中的最后一行代码中删除 
| Remove-CimInstance -WhatIf
,以便在测试并确认此类解决方案足以满足您的需求后运行。

PowerShell

$domain = "Domain";
$AccountsToKeep = @('Administrator.machinename','administrator');
$sids = (Get-CimInstance Win32_UserProfile | Where-Object {$PSItem.LastUseTime -lt [datetime]::Now.AddDays(-0) -and $_.Special -eq $false -and (Split-Path $_.LocalPath -Leaf) -notin $AccountsToKeep}).SID;

$NameSidCombo = $sids | ForEach-Object {
    $account = (New-Object System.Security.Principal.SecurityIdentifier($_)).Translate([System.Security.Principal.NTAccount]).Value;
    If($account -notmatch "$domain\\"){"$($account),$($_)"};
    };

$NameSidCombo;

$NameSidCombo | ForEach-Object { $sid = ($_).Split(",")[1]; Get-CimInstance Win32_UserProfile | Where-Object {$_.SID -eq $sid} | Remove-CimInstance -WhatIf};

支持资源

© www.soinside.com 2019 - 2024. All rights reserved.