删除用户配置文件

<#
.SYNOPSIS
Removes user profiles on computers running Windows Vista or later.
.DESCRIPTION
Removes specified user profiles found on a computer (local or remote) running Windows Vista or later,
and logs the information in a CSV file. If no computer names are provided, the script will remove the profiles
of the machine where it is running. You can provide user names to be skipped on the command line, or via
an input file.
.PARAMETER computerNames
The name, or names of computers whose profiles are to be removed. If providing more than one name,
list them separated by commas.
.PARAMETER excludedUsers
The name or names of the user accounts that should NOT be removed.
.PARAMETER excludedUsersInputFile
A file containing the name or names of the user accounts that should NOT be removed. The file should
contain one user account per line.
.PARAMETER logFile
The log file that will be written with details of profile removal. By default, the
file is written to the same directory where the script resides, and has the .csv extension.
.PARAMETER whatIf
If specified, the script will simulate profile removal but won‘t actually remove anything.
.PARAMETER confirm
If specified, the script will prompt for confirmation for every profile it intends to remove.
.EXAMPLE
.\Remove-UserProfiles.ps1 -whatIf
.EXAMPLE
.\Remove-UserProfiles.ps1 -computerNames COMPUTER1 -confirm:$false
.EXAMPLE
.\Remove-UserProfiles.ps1 -computerNames COMPUTER1,COMPUTER1,COMPUTER1
.EXAMPLE
.\Remove-UserProfiles.ps1 -computerNames COMPUTER1,COMPUTER1,COMPUTER1 -excludedUsers domain\user1,domain\user2
.EXAMPLE
.\Remove-UserProfiles.ps1 -computerNames COMPUTER1,COMPUTER1,COMPUTER1 -excludedUsersInputFile c:\userlist.txt
.EXAMPLE
.\Remove-UserProfiles.ps1 -computerNames COMPUTER1,COMPUTER1,COMPUTER1 -logFile c:\logfile.txt
#>
[CmdletBinding(DefaultParametersetName="ExcludedUsersFromCommandLine")]
param(
    [Parameter(Position=0,ValueFromPipeline=$true)]
    $computerNames,
    [Parameter(ParameterSetName="ExcludedUsersFromCommandLine")]
    $excludedUsers,
    [Parameter(ParameterSetName="ExcludedUsersFromFile")]
    $excludedUsersInputFile,
    [switch]
    $whatIf,
    [switch]
    $confirm=$true,
    [ValidateNotNullOrEmpty()]
    [string]
    $logFile="removeprofileslog.csv"
)
Function Log-Message {
    param(
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        $userProfile,
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $removalStatus
    )
    $currentDate = Get-Date
    $dateString = $currentDate.toShortDateString()
    $timeString = $currentDate.toShortTimeString()

    Add-Content $LogFile ($dateString + " " + `
                            $timeString + "," + `
                            $userProfile.computerName + "," + `
                            $userProfile.accountName + "," + `
                            $userProfile.SID + "," + `
                            $userProfile.LocalPath + "," + `
                            $(Convert-WMIDateStringToDate -dateString $userProfile.LastUseTime) + "," + `
                            $removalStatus)
}
Function Convert-WMIDateStringToDate {
    param (
        [parameter(Mandatory=$true)]
        [AllowNull()]
        [AllowEmptyString()]
        [string]
        $dateString
    )
    if ($dateString) {
        return [System.Management.ManagementDateTimeConverter]::ToDateTime($dateString)
    }
}
Function Get-UserProfiles {
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $computerName
    )
    return Get-WmiObject -class Win32_UserProfile -computername $computerName
}
Function Get-AdUserForSid {
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $sid
    )
    try {
        $userSid = New-Object System.Security.Principal.SecurityIdentifier($sid)
        $user = $userSid.Translate([System.Security.Principal.NTAccount])
        return $user.Value
    } catch [System.Security.Principal.IdentityNotMappedException] {
        return $null
    }
}
Function Get-LocalUserForSid {
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $sid,
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $computerName
    )
    try {
        $user = Get-WmiObject win32_useraccount -Filter "SID=‘$sid‘ AND domain=‘$computerName‘" -computername $computerName
        return $user.Name
    } catch {
        return $null
    }
}
Function Update-ProfileWithAccountName {
    param (
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        $userProfile,
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        $computerName
    )

    $accountName = Get-AdUserForSid -sid $userProfile.SID
    if(!$accountName) {
        $accountName = Get-LocalUserForSid -sid $userProfile.SID -computerName $computerName
    }

    Add-Member -InputObject $userProfile -MemberType NoteProperty -Value $accountName -Name "accountName"
    Add-Member -InputObject $userProfile -MemberType NoteProperty -Value $computerName -Name "computerName"
    return $userProfile
}
Function Should-AccountBeSpared {
    param(
        [Parameter(Mandatory=$true)]
        [AllowNull()]
        [AllowEmptyString()]
        $userProfile,
        [Parameter(Mandatory=$true)]
        [AllowNull()]
        [array]
        $accountNamesToBeSpared
    )
    if ($userProfile.accountName -ne $null) {
        foreach ($name in $accountNamesToBeSpared) {
            if (([string]::Compare($userProfile.accountName, $name, $true)) -eq 0) {
                return $true
            }
        }
    }
    return $false
}
Function Write-ProfileDetails {
    param (
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        $userProfile
    )
    Write-Host "Computer:`t" $userProfile.computerName
    Write-Host "SID:`t`t" $userProfile.SID
    Write-Host "Account:`t" $userProfile.accountName
    Write-Host "Local Path:`t" $userProfile.LocalPath
    Write-Host "Last Use:`t" $(Convert-WMIDateStringToDate -dateString $userProfile.LastUseTime)
}
Function Prompt-ForConfirmation {
    Write-Host "`nAre you sure you want to remove profile?"
    $answer = Read-Host "[Y] Yes, [N] No, [A] All: "
    return $answer.toLower()
}
if ($computerNames -eq $null) {
    $computerNames = Hostname
}
if ($confirm -eq $false) {
    $answer = "a"
}
if ($excludedUsersInputFile) {
    $excludedUsers = Get-Content $excludedUsersInputFile
}
foreach ($computerName in $computerNames) {
    $allUserProfiles = Get-UserProfiles -computerName $computerName

    foreach ($userProfile in $allUserProfiles) {
        $removalStatus = ""
        $userProfile = Update-ProfileWithAccountName -userProfile $userProfile -computerName $computerName
        if ($userProfile.Special -ne $true) {
            Write-ProfileDetails $userProfile
            if ((Should-AccountBeSpared -userProfile $userProfile -accountNamesToBeSpared $excludedUsers) -eq $true) {
                $removalStatus = "Skipped: Account is in the exclusion list."
            } else {
                if ($userProfile.Loaded -eq $true) {
                    $removalStatus = "Skipped: Profile in use."
                } else {
                    if ($confirm) {
                        $answer = Prompt-ForConfirmation

                        if ($answer.compareTo("a") -eq 0) {
                            $confirm = $false
                        }
                    }
                    if (($answer.compareTo("y") -eq 0) -or ($answer.compareTo("a") -eq 0)) {
                        $removalStatus = "Removed"
                        if ($whatIf -ne $true) {
                            $userProfile.Delete()
                        }
                    } else {
                       $removalStatus = "Skipped"
                    }
                }
            }
            if ($whatIf) {
                $removalStatus = "What If - " + $removalStatus
            }
            Write-Host $removalStatus -Foreground Yellow
            Log-Message $userProfile $removalStatus
        }
    }
}
时间: 2024-10-13 14:23:34

删除用户配置文件的相关文章

删除用户配置文件 (正则表达式)

$parttern = "\b\d{6}\b" $today = Get-Date $hostname = "cnhzpd-47d173x" $profiles = Get-WmiObject -Class win32_userprofile -ComputerName $hostname | Select-Object -Property LocalPath, @{N='time'; E={$_.ConverttoDateTime($_.lastusetime)}

如何重建域用户配置文件?

如何重建域用户配置文件? ?Lander Zhang 专注外企按需IT基础架构运维服务,IT Helpdesk 实战培训践行者博客:https://blog.51cto.com/lander IT Helpdesk 工程师实战培训课程:https://edu.51cto.com/lecturer/733218.html轻松进外企:IT Helpdesk工程师实战自学之路:https://blog.51cto.com/lander/2413018更新时间:2020/04/06 故障现象在域环境中,

windows 7中修改用户配置文件的路径

在windows 7中用户配置文件的默认位置是在c:\users文件夹中.我建议最好在安装完操作系统之后就将用户配置文件的默认位置改变到其他分区. Warning在视图更改注册表之前,请备份好注册表相关键值. 1. 将c:\user文件夹Copy到新的位置(默认情况下 "Default" directory 是隐藏的,请到 Tools > Folder Options > View (tab) > Show Hidden files, folders, and dri

linux用户配置文件passwd和密码配置文件shadow,用户管理,组管理

一.linux和windows互传文件 1.安装支持包:lrzsz yum -y install   lrzsz putty工具 不支持lrzsz 2.rz windows文件fail2ban-0.8.14.tar.gz 到linux 当前目录 3.sz baidu.png 传输文件从linux 到 windows 二. 用户配置文件和密码配置文件 1.用户配置文件 ls /etc/passwd [[email protected]_46_188_centos ~]# cat /etc/pass

Ansible 从MySQL数据库添加或删除用户

mysql_user - 从MySQL数据库添加或删除用户. 概要 要求(在执行模块的主机上) 选项 例子 笔记 状态 支持 概要 从MySQL数据库添加或删除用户. 要求(在执行模块的主机上) MySQLdb的 选项 参数 需要 默认 选择 注释 append_privs (1.4 加入) no no yes no 将priv定义的权限附加到此用户的现有权限,而不是覆盖现有的权限. check_implicit_admin (1.3 加入) no no yes yes 检查mysql是否允许以

2.27linux和windows互传文件 3.1 用户配置文件和密码配置文件 3.2 用户组管理 3.3 用户管理

2.27linux和windows互传文件 3.1 用户配置文件和密码配置文件 3.2 用户组管理 3.3 用户管理 2.27 linux和windows互传文件 首相只能使用远程工具 xshell  .securecrt 首先安装一个包 yum install  -y lrzsz sz + 文件名   把linux 上的文件 传到  windows上 把 linux 上的 4.txt 传到windows 上 使用rz 回车 就可以吧windows 上的文件传到linux 下 的当前目录下 传输

Win2008R2 删除用户目录后无法生成

打开注册表 regedit 在"注册表编辑器"中,找到: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList在左窗格中,找到以"S-1-5"开头,后跟一长串数字的文件夹名称.然后单击每个文件夹,在右窗格中找到"ProfileImagePath",查看哪个跟无法重建配置文件的账户名字一样,将整个S-1-5XXX删除即可. Win2008R2 删除用户

python之修改用户配置文件

用户的配置文件如下 backend oldboy school school1 age 21 weight 210 qq 550124281 iphone 13925293887backend oldgirl school school2 age 22 weight 220backend oldteacher school school3 age 23 weight 230backend oldstudent school school4 age 24 weight 240 作业要求: 1.实现

Sharepoint 2010 用户配置文件同步服务无法启动

文章摘要 在安装Sharepoint 2010后想要启动用户配置文件同步服务,但是无论如何都无法启动,重启了好多次,也没有作用,这个问题遇到了很多次,每次的解决办法都不一样,有时候使用同样的办法却无法解决问题,下面描述一下最近的解决办法,可以尝试,但不一定成功. 开始 据说要想启动这个服务,在windows服务中的"Forefront Identity Manager Service"和"Forefront Identity Manager Synchronization S