powershell - 删除后缀为 _Inactive 的本地用户配置文件
问题描述
我想从 C:\Users 以及我公司大量机器上的注册表中删除本地用户配置文件。
一段时间以来的做法是将 C:\Users 中的用户配置文件文件夹从仅用户名重命名为 username_Inactive
我想简单地运行这个脚本:
$profilesToDelete = Get-WMIObject -Class Win32_UserProfile | where {$_.LocalPath -match '_Inactive'} -ErrorAction Stop
foreach ($profileToDelete in $profilesToDelete)
{
Write-Verbose "Removing Profile $($profileToDelete.LocalPath) & Associated Registry Keys on $env:COMPUTERNAME..."
Remove-WmiObject -InputObject $profileToDelete -ErrorAction Stop
}
但是....每个 win32_userprofile 的本地路径不反映手动配置文件文件夹名称从 username 更改为 username_Inactive
我可以使用此脚本通过运行以下命令向我显示名为 username_Inactive 的所有用户配置文件的列表:
Get-ChildItem -Path "C:\Users\" | Where {$_.Name -match '_Inactive'}
但在这一点上,我对如何前进有点茫然。我有一些想法,但没有足够的技术知识。
任何帮助将不胜感激。
解决方案
这是一个将路径关联起来并巧妙地处理LocalPath
业务的解决方案:
$inactiveList = (Get-ChildItem -Path 'C:\Users\*_Inactive').FullName -replace '_inactive$'
$deleteList = @(Get-WmiObject -Class Win32_UserProfile).Where{$PSItem.LocalPath -in $inactiveList}
foreach ($delete in $deleteList) {
Write-Verbose "Removing profile '$($delete.LocalPath)' and associated registry keys on $Env:COMPUTERNAME."
Rename-Item -LiteralPath "$($delete.LocalPath)_Inactive" -NewName $delete.LocalPath -Force
$delete | Remove-WmiObject
}
推荐阅读
- c# - DeleteMessageAsync()不删除SQS队列.Net Core中的消息
- python - 在 for 循环声明中发生未知故障。我该如何解决?
- oracle11g - oracle 11g application express接口虚拟列计算总销售额
- python - Is time.sleep a good way to run a python script every day?
- azure - 部署后 Web 应用无法从 Azure AD 身份验证返回
- spring-kafka - 使用 Spring Kafka 降低处理速率的选项
- arrays - 正则表达式从搜索的值中提取字符串值偏移量?
- bash - 获取洋葱站点标题的 Bash 脚本
- laravel - 与不同数据库连接模型的 Eloquent 多对多关系
- jenkins - 在 GKE 上部署时在 jenkins master 上挂载失败