[英]Test if computer object exists in Active Directory in PowerShell
I have a problem checking if a computer object exists in AD or not.我在检查计算机 object 是否存在于 AD 中时遇到问题。 To be specific it should go into an "else" if not.
具体来说,如果不是,它应该将 go 变成“else”。
This is my code:这是我的代码:
if (Get-ADComputer "$Computer") {
Get-ADComputer $Computer | Set-ADComputer -Enabled $false
Start-Sleep -s 2
Get-ADComputer $Computer | Move-ADObject -TargetPath $PathOU
Start-Sleep -s 2
} else {
write-host "Example"
}
When the input computer doesn't exist, the problem is, the command Get-ADComputer "$Computer"
already fails in the if
statement, so it never reaches the else
.当输入计算机不存在时,问题是
Get-ADComputer "$Computer"
命令在if
语句中已经失败,因此它永远不会到达else
。
How can I avoid that?我怎样才能避免这种情况?
Thanks in advance.提前致谢。
Add the Get-ADComputer
to a variable before the if
block to help.将
Get-ADComputer
添加到if
块之前的变量以提供帮助。 Also before setting that variable with the command, set it to null per the below example.同样在使用命令设置该变量之前,请按照以下示例将其设置为 null。 In addition to that, change up the
if
block to first check if it does not exist and to run that logic first then else
run logic if it does exist.除此之外,更改
if
块以首先检查它是否不存在并else
运行该逻辑然后如果它确实存在则运行逻辑。
$comp = "";
$comp = Try {Get-ADComputer "$Computer"} Catch {$false};
if (!$comp) {
write-host "Example"
} else {
$comp | Set-ADComputer -Enabled $false
Start-Sleep -s 2
$comp | Move-ADObject -TargetPath $PathOU
Start-Sleep -s 2
};
!
logical not逻辑非
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.