用于从计算机中删除用户的 Powershell 脚本

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

我编写了一个脚本,使我能够删除与计算机相关的多个用户配置文件和注册表项。这是为了工作,多个人在我们的几个诊所共享计算机,最终计算机上充满了不再在那里工作或刚刚拥有自己的计算机的人的用户配置文件。所以存储空间最终会耗尽,这就是我进来的地方,删除了很多用户配置文件来清理磁盘。我想让这变得更容易,所以我尝试编写一个脚本。这里是。顺便说一句,这是所有域加入。我知道这可以通过组策略来完成,但我的工程师还没有实现这一点,我只是帮助台,试图让我的生活更轻松。

$profiles = Get-CimInstance -Class Win32_UserProfile
$users = 'schaudhary'
foreach ($profile in $profiles){
    if ($profile.Special -ne 'True'){
        if ($profile.LocalPath.split('\')[-1] -notcontains $users) {
            $profile | Where-Object { $_.LocalPath.split('\')[-1] } | Remove-CimInstance -WhatIf
            Write-Host "deleting" $profile.LocalPath
        }
    }
}

问题是当我尝试从删除过程中排除多个用户时,它不起作用。但是当我只有一个用户时,就像现在的“schaudhary”,它会起作用(它将排除 scaudhary)。我怎样才能让它排除多个用户?我必须排除本地管理帐户、计算机上的活动用户和一些特殊服务帐户。如果有人可以提供有关添加此处包含的上次使用时间的提示,那将会有所帮助。因此,仅当用户已存在 90 天或以上时才删除,类似的情况。

windows powershell automation scripting active-directory
3个回答
1
投票

与用户相关的事件意味着他正在计算机上工作。 但你必须确保有90天的日志

$sid =(Get-adUser $username).sid.value
$StartDate = (Get-Date) - (New-TimeSpan -Day 90)
Get-WinEvent -FilterHashtable @{LogName='Security';data=$sid;StartTime=$StartDate} -MaxEvents 1

0
投票

使用时,您正在反转变量

-notcontains
..

它的用途是

$collectionOfThings -contains $singleThing

$collectionOfThings -notcontains $singleThing

从 PowerShell 版本 3 开始,您还可以使用

-in
-notin
执行相反的操作,如
所示
$singleThing -in $collectionOfThings
或否定
$singleThing -notin $collectionOfThings

参见收容操作员

尝试

$profiles = Get-CimInstance -Class Win32_UserProfile
$users    = @('schaudhary')  # array of profiles to keep
foreach ($profile in $profiles){
    if (!$profile.Special) {
        $userName = $profile.LocalPath.split('\')[-1]
        # or: 
        # if ($userName -notin $users) {
        if ($users -notcontains $userName) {
            if (!$profile.Loaded) {
                $profile | Remove-CimInstance -Confirm:$false -WhatIf
                Write-Host "Deleting $($profile.LocalPath)"
            }
            else {
                Write-Warning "Profile $($profile.LocalPath) is currently loaded.."
            }
        }
    }
}

0
投票

因此,Theo 的脚本可以工作,但它留下了配置文件的文件夹结构。正在努力纠正这个问题。

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