用于删除 AD 用户和配置文件的 Powershell 脚本

Powershell Script for deleting AD User & Profile

我是 coding/powershell 的新手。我“写”了这个小脚本

$Username = Read-Host -Prompt 'Bitte den Usernamen eingeben'

$HomeDirectory = '\server\user'
$ProfilePath = '\server\profiles'
$TsProfiles = '\server\tsprofiles'

foreach ($user in $Username) {
    Remove-ADUser -Identity $user
}

foreach ($user in $Username) {
    Remove-Item "$HomeDirectory$user" -Recurse -Force -Verbose -whatif
}

foreach ($user in $Username) {
    Remove-Item -Path "$ProfilePath$user" -Recurse -Force -Verbose -whatif
}

foreach ($user in $Username) {
    Remove-Item "$TsProfiles$user*" -Recurse -Force -Verbose -whatif
}

现在这个脚本 运行 没问题。但我有一个小“问题”

1.) 对于某些用户,没有 TsProfiles 或 ProfilePath 或用户。所以当我 运行 脚本时我得到这个错误

At line:15 char:5
+     Remove-Item -Path "$ProfilePath$user" -Recurse -Force -Verbose - ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (\server\profiles\myusername:String) [Remove-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

当然可以,因为没有这样的路径,因为用户在该文件夹中没有配置文件。现在我正在寻找一个解决方案,可以将这样的内容写入日志文件

** %Username% 的主目录已删除 **

** %Username% 的 TsProfiles 已删除 **

** 找不到 %Username% 的配置文件路径 **

好的,首先你应该在一个循环中完成所有操作,而不是几个循环,但是你只与 1 个用户一起工作,所以没有什么可以循环的。我们将删除所有循环。

然后,如果你想输出你是否删除了一些东西,你需要检查它是否存在。对于用户,我们可以使用 Get-ADUser,对于文件路径,我们可以使用 Test-Path.

$Username = Read-Host -Prompt 'Bitte den Usernamen eingeben'

$HomeDirectory = '\server\user'
$ProfilePath = '\server\profiles'
$TsProfiles = '\server\tsprofiles'

If(Get-ADUser $username){
    Remove-ADUser -Identity $username
    Add-Content -Value "** User Account for $Username deleted **" -Path $LogFile
}Else{
    Add-Content -Value "** User Account for $Username not found **" -Path $LogFile
}
If(Test-Path "$HomeDirectory$username"){
    Remove-Item "$HomeDirectory$username" -Recurse -Verbose -Force -WhatIf
    Add-Content -Value "** HomeDirectory of $Username deleted **" -Path $LogFile
}Else{
    Add-Content -Value "** HomeDirectory of $Username not found **" -Path $LogFile
}
If(Test-Path "$ProfilePath$username"){
    Remove-Item "$ProfilePath$username" -Recurse -Verbose -Force -WhatIf
    Add-Content -Value "** ProfilePath of $Username deleted **" -Path $LogFile
}Else{
    Add-Content -Value "** ProfilePath of $Username not found **" -Path $LogFile
}
If(Test-Path "$TsProfiles$username"){
    Remove-Item "$TsProfiles$username" -Recurse -Verbose -Force -WhatIf
    Add-Content -Value "** TsProfiles of $Username deleted **" -Path $LogFile
}Else{
    Add-Content -Value "** TsProfiles of $Username not found **" -Path $LogFile
}