通过powershell脚本根据上次修改日期删除用户配置文件

q1qsirdb  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(228)

我正在为我的雇主做一个项目-目标是把我们的机器的一个子集,这是相当不断地填补由于过剩的配置文件,许多人谁不再是员工。在做研究对此,我发现这个https://stackoverflow.com/a/72101998/22953610由约翰史密斯,这似乎非常有帮助,正是我们想做的。
然而,我遇到了一个问题:当执行脚本时,它按预期打印,但据我所知,实际上并没有采取任何行动。

$VerbosePreference = 'Continue'
$ExcludedUsers="Public","default","defaultuser0","public","administrator"
$path = "$Env:SystemDrive\users"

## getting the name of the users
## this returns the filtered results below
$useraccounts = Get-ChildItem -Path $path -Exclude $ExcludedUsers | Where-Object {$_.lastwritetime -lt (Get-Date).AddDays(-30)}

## $useraccounts returns

<#

Directory: /Users

UnixMode   User             Group                 LastWriteTime           Size Name
--------   ----             -----                 -------------           ---- ----
drwxr-x--- jacoby         staff                5/2/2022 19:04           1056 jacoby
drwxrwxrwt root             wheel               3/26/2022 00:21            128 Shared

#>

## $useraccounts.name returns

<#

PS > $useraccounts.name

jacoby
Shared

#>

## if we use get-childitem | get-member we can see that we have access to a lot of
## properties returned like the .name value

#### we don't need any of this
####$sort = $useraccounts | ForEach-Object {$_.Name}
#####$removeaccounts = $sort -join '|'

## ok let's do something here
## for each account in my list
foreach ($account in $useraccounts)
{

    ## let's write some info so we know what's happening
    Write-Verbose -Message ('currently working with {0}' -f $account)

    ## we want to check moditfication time of folder so we gotta see if it exists
    ## we want to test c:\users\ the current account \ appdata\local
    ## $account.FullName gives us c:\users\accountname so we just need to add the rest

    $testpath1 = $account.FullName + '\appdata\local'
    Write-Verbose -Message ('we generated the path {0}' -f $testpath1)

    ## imma give you some error checking
    ## this is ugly because it could be there but we can't access it

    if ((Test-Path -Path $testpath1 -ErrorAction SilentlyContinue) -eq $true)
    {

        ## if the path exists here's what we'll do

        ## get a count of all the file modified in the last 30 days

        $count = (Get-ChildItem -Path $testpath1 | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-30) }).Count

        ## now that we have a count we can test if the count is less than than 1 (0)
        ## that means no files in these folders were modified in the last 30 days

        if ($count -lt 1) {

            ####
            ##
            ## this is the area where we can take action on the
            ## folders/files that have not been modified in the
            ## last 30 days
            ## you might delete them or just log them somewbere
            ##
            ####

            Write-Verbose -Message 'no file modified in the last 30 days'

            ####
            ## this is your original deletion pipeline
            Get-WmiObject -Class Win32_userprofile | Where-Object {($_.LocalPath -contains "$account") -and (!$_.special)} | Remove-WmiObject
            ##i have not tested this. be careful.
            ####
        }

        else {

            Write-Verbose -Message ('{0} files have been modified in the last 30 days! We do not want delete this.' -f $count)

            ####
            ##
            ## these is the area where we can take action if the
            ## files/folder HAVE been modified recently
            ## we would NOT want to delete these files
            ##
            ####
        }
    }
    ## do some stuff before ending the for each loop
    ## maybe write our changes somewhere permanent
}

字符串
我在这里的目标是实际上通过并完全删除所有用户配置文件没有修改在过去30天。
我看到删除管道如下:

####
            ## this is your original deletion pipeline
            Get-WmiObject -Class Win32_userprofile | Where-Object {($_.LocalPath -contains "$account") -and (!$_.special)} | Remove-WmiObject
            ##i have not tested this. be careful.
            ####


我已经删除了hashtags,以便取消注解。然而,当运行脚本时,我只得到以下结果:

VERBOSE: currently working with C:\Users\#088DFEBE.jpg
VERBOSE: we generated the path C:\Users\#088DFEBE.jpg\appdata\local
VERBOSE: currently working with C:\Users\#76B7EBF1.doc
VERBOSE: we generated the path C:\Users\#76B7EBF1.doc\appdata\local
VERBOSE: currently working with C:\Users\#8A09F1A9.xls
VERBOSE: we generated the path C:\Users\#8A09F1A9.xls\appdata\local
VERBOSE: currently working with C:\Users\#D97B2BA6.pptx
VERBOSE: we generated the path C:\Users\#D97B2BA6.pptx\appdata\local
VERBOSE: currently working with C:\Users\$42D864D7.doc
VERBOSE: we generated the path C:\Users\$42D864D7.doc\appdata\local
VERBOSE: currently working with C:\Users\$649D0AFD.pptx
VERBOSE: we generated the path C:\Users\$649D0AFD.pptx\appdata\local
VERBOSE: currently working with C:\Users\$D4DC362C.xls
VERBOSE: we generated the path C:\Users\$D4DC362C.xls\appdata\local
VERBOSE: currently working with C:\Users\$EA0D76A7.jpg
VERBOSE: we generated the path C:\Users\$EA0D76A7.jpg\appdata\local


这就是它所做的一切。
我想知道我做错了什么,它实际上不是通过和删除配置文件?

iugsix8n

iugsix8n1#

  • 看起来您的第一个Get-ChildItem调用也与 files 匹配,您可以通过-Directory开关来阻止这种情况。
  • AppData是一个 * 隐藏 * 目录,因此您需要-ForceGet-ChildItem来枚举它。
  • 顺便说一句:CIM指令程式(例如,Get-CimInstance)取代了WMI cmdlet(例如,Get-WmiObject)在PowerShell v3中的部署(于2012年9月发布)。因此,应避免使用WMI cmdlet,尤其是因为PowerShell(Core)v6+(未来的所有工作都将在其中进行)甚至不再 * 具有 * 这些cmdlet。不过,请注意,WMI仍然 * 作为CIM cmdlet的基础。有关更多信息,参见this answer

不过,我建议采用以下精简方法:

#requires -RunAsAdministrator

Get-CimInstance Win32_UserProfile | 
  Where-Object -OutVariable profilesToDelete { 
    -not $_.Special -and 
      (Split-Path -Parent $_.LocalPath) -eq "$env:SystemDrive\Users" -and
      (Split-Path -Leaf $_.LocalPath) -notin 'Public', 'default', 'defaultuser0', 'administrator' -and
      $_.LastUseTime -lt (Get-Date).Date.AddDays(-30)
  } |
  Remove-CimInstance -WhatIf

# To also delete the user accounts associated with the deleted profiles:
Remove-LocalUser -SID $profilesToDelete.SID -WhatIf

字符串
注意事项:上述命令中的**-WhatIf公共参数 * 预览 * 操作。删除-WhatIf,并在确定给定操作将执行所需操作后重新执行。

  • 上述命令使用Get-CimInstanceRemove-CimInstance CIM cmdlet。
  • 给定的用户配置文件在过去30天内是否被 * 使用过 *(登录过),可以从返回的每个Win32_UserProfile示例的.LastUseTime属性中推断出来。
  • 注意:您似乎 * 必须 * 以管理员身份 * 以提升权限 * 运行 *,才能仅 * 查询 * 此值。
  • 除了删除 profile(目录和注册表项)之外,您可能还希望删除关联的 user accounts,这正是Remove-LocalUser调用所做的。
  • 请注意,在带有自选变量名profilesToDeleteWhere-Object调用中使用了公共-OutVariable参数(注意:* 没有 * $),从而允许以后通过$profilesToDelete访问要删除的概要文件。

相关问题