Powershell Delete Computer Object - powershell

Can some one help me on the next code im trying to run..
it seem's to be ok for me but does not delete the Object when i execute-it
Import-Module ActiveDirectory
Clear-Host
$Computer = Read-Host "Type in the Host to Delete"
$rute = Get-ADComputer -Identity:"CN=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com"
if($rute.Contains($Computer)){
Clear-Host
Remove-ADComputer -Identity=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
#Clear-Host
Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
Start-Sleep -Seconds 5
} else{
Clear-Host
Write-Host "The Host does not exist on AD" -ForegroundColor Red
Start-Sleep -Seconds 3
}
try to delete a Active directory object.. expected to work

Your code is not very clear and seems overengineered, $rute.Contains($Computer) will never ever be $true, you probably meant $rute.DistinguishedName.Contains($Computer) which could be $true but .Contains is case-sensitive so it could also be $false.
Your Read-Host statement is assigned to $Computer but then you're using $Computadora. Also, it's unclear why you are hardcoding OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com, I would assume you want to use this OU as your -SearchBase.
Here is how you can approach and will most likely work:
$param = #{
SearchBase = "OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com"
LDAPFilter = "(name={0})" -f (Read-Host "Type in the Host to Delete")
Server = "DCKABI02.kabi.ads.fresenius.com"
}
$computer = Get-ADComputer #param
if($computer) {
Clear-Host
$computer | Remove-ADComputer -Server "DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
Start-Sleep -Seconds 5
}
else {
Clear-Host
Write-Host "The Host does not exist on AD" -ForegroundColor Red
Start-Sleep -Seconds 3
}

Related

If/Else Help in Powershell

Running an IF/Else statement and if "false" I want it to run a search for the current NVIDIA driver and tell me the current version then stop the script. Tried a couple different things to no avail. Currently it is continuing the script and running the "Get-WmiObject" out of order in a subsequent function.
Function Namespace_Check
{ Write-Host "Checking available namepace" -ForegroundColor Green
if ((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV'){return}
else { return (Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "*nvidia*"})}
Write-Host "If Stopped, install latest NVIDIA driver from SWE"
Write-Host "Complete" -ForegroundColor Green
}
Here is the whole script, if there needs to be other changes to the logic
Function Namespace_Check
{ Write-Host "Checking available namepace" -ForegroundColor Green
Write-Host "Complete" -ForegroundColor Green
if ((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV'){return}
else {
exit (Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "*nvidia*"})
Write-Warning "Install latest NVIDIA driver from SWE"
Write-Host
}
}
Function InstallSWE
{
Write-Host "Installing SWE Icon..." -ForegroundColor Green
$ps = new-object System.Diagnostics.Process
$ps.StartInfo.FileName = "\\nt-iss-1\setools\xsetup.exe"
$ps.StartInfo.Arguments = " -Silent -NoPrompt -NoBanner"
Write-Host " Execute Software Express"
[Void]$ps.start()
$ps.WaitForExit()
Write-Host "Complete" -ForegroundColor Green
}
Function CheckNVIDIADriver
{
Write-Host "Checking NVIDIA Drivers..." -ForegroundColor Green
$productName = Get-WmiObject -namespace "root\cimv2\nv" -Class Gpu | Select -ExpandProperty productName
$driverVersion = Get-Wmiobject -namespace "root\cimv2\nv" -class System | Select -ExpandProperty verDisplayDriver | Select -ExpandProperty strValue
Write-Host " Product Name : $productName"
Write-Host " Video Driver Version: $driverVersion"
Write-Host "Complete" -ForegroundColor Green
}
Function SetNVIDIA3DGlobalPreset
{
Write-Host "Setting NVIDIA 3D Global Preset..." -ForegroundColor Green
$global3DPreset = "Dassault Systemes CATIA - compatible"
$profileManager = Get-WmiObject -namespace "root\cimv2\nv" -Class ProfileManager
"Change Global 3D Preset to $global3DPreset"
[void](Invoke-WmiMethod -Path $profileManager.__PATH -Name setCurrentProfile3D -ArgumentList $global3DPreset, $null)
Write-Host "Complete" -ForegroundColor Green
}
Function SetScreenSaver
{
Write-Host "Setting Screen Saver..." -ForegroundColor Green
$regkeypath = "HKCU:\Control Panel\Desktop"
$screensaver = "C:\Windows\SysWOW64\CORPOR~1.SCR"
Write-Host " Change Screen Saver to Corporate Screen Saver"
Set-ItemProperty -Path $regkeypath -Name "SCRNSAVE.EXE" -Value $screensaver
Write-Host "Complete" -ForegroundColor Green
}
Function ChangePowerSettings
{
Write-Host "Changing Power Settings..." -ForegroundColor Green
Write-Host " Disable Monitor Timeout"
powercfg -x -monitor-timeout-ac 10
powercfg -x -monitor-timeout-dc 10
Write-Host " Disable Disk Timeout"
powercfg -x -disk-timeout-ac 0
powercfg -x -disk-timeout-dc 0
Write-Host " Disable Standby Timeout"
powercfg -x -standby-timeout-ac 0
powercfg -x -standby-timeout-dc 0
Write-Host " Disable Hibernate and Hybrid Sleep"
powercfg -x -hibernate-timeout-ac 0
powercfg -x -hibernate-timeout-dc 0
powercfg -h off
Write-Host "Complete" -ForegroundColor Green
}
Function ChangeVirtualMemory
{
Write-Host "Changing Virtual Memory Settings..." -ForegroundColor Green
$mem = [Math]::Round((Get-WmiObject -Class Win32_ComputerSystem |Select -ExpandProperty TotalPhysicalMemory) / [Math]::pow(1024, 3))
$initialSize = 2048 * $mem
$maximumSize = 2 * $initialSize
Write-Host " Disable Automatic Managed Page File"
$System = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges
$System.AutomaticManagedPagefile = $False
[Void]$System.Put()
Write-Host " Set Page File Size (Initial Size: $initialSize MB / Maximum Size: $maximumSize MB)"
$PageFile = Get-WmiObject -class Win32_PageFileSetting
$PageFile.InitialSize = $initialSize
$PageFile.MaximumSize = $maximumSize
[Void]$PageFile.Put()
Write-Host "Complete" -ForegroundColor Green
}
Function EnableRDP
{
Write-Host "Enabling Remote Desktop and User..." -ForegroundColor Green
$computername = $(gc env:computername)
$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\CIMV2\TerminalServices
Write-Host " Enable Remote Desktop"
$result = $RDP.SetAllowTsConnections(1, 1)
Try
{
$user ="CAxILABRemoteUsers"
$domain ='NW'
$objUser = [ADSI]("WinNT://$domain/$user")
$objGroup = [ADSI]("WinNT://$computername/Remote Desktop Users")
Write-Host " Add Remote Desktop User $domain\$user"
$objGroup.PSBase.Invoke('Add',$objUser.PSBase.Path)
}
Catch
{
}
Write-Host "Complete" -ForegroundColor Green
}
Function CheckAdministrator
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
# Filename: CAxILab_Final_Config.ps1
$pshost = get-host
$pswindow = $pshost.ui.rawui
$newsize = $pswindow.buffersize
$newsize.height = 999
$pswindow.buffersize = $newsize
$newsize = $pswindow.windowsize
#$newsize.height = 60
#$pswindow.windowsize = $newsize
$host.ui.RawUI.ForegroundColor = "White"
$isAdmin = CheckAdministrator
if ($isAdmin)
{
Namespace_Check
Write-Host
InstallSWE
Write-Host
CheckNVIDIADriver
Write-Host
SetNVIDIA3DGlobalPreset
Write-Host
SetScreenSaver
Write-Host
ChangePowerSettings
Write-Host
ChangeVirtualMemory
Write-Host
EnableRDP
Write-Host
}
else
{
Write-Warning "Administrator rights is required to run this script"
Write-Host
}
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# end of script
If you want the script stopped completely when the namespace is not found, change the function Namespace_Check into something like this:
Function Namespace_Check {
Write-Host "Checking available namepace" -ForegroundColor Green
if (!((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV')) {
# if we got here, the namespace is not found
# output the current version, then stop the script
$driver = Get-WmiObject Win32_PnPSignedDriver|
Select-Object devicename, driverversion |
Where-Object {$_.devicename -like "*nvidia*"}
Write-Host "If Stopped, install latest NVIDIA driver from SWE"
if ($driver) {
Write-Host "Current driver(s)" -ForegroundColor Yellow
$driver | Format-Table -AutoSize
}
else {
Write-Warning "No nvidia drivers found"
}
Write-Host "Script Complete" -ForegroundColor Green
# stop the script
exit
}
}
In your version you are trying to write to console after you have exited the function using a return statement. These lines will therefore never be executed.
Edit
Alternatively, you can have the function Namespace_Check return a value of $true of $false like this:
Function Namespace_Check {
Write-Host "Checking available namepace" -ForegroundColor Green
if (!((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV')) {
# if we got here, the namespace is not found
# output the current version, then stop the script
$driver = Get-WmiObject Win32_PnPSignedDriver|
Select-Object devicename, driverversion |
Where-Object {$_.devicename -like "*nvidia*"}
Write-Host "If Stopped, install latest NVIDIA driver from SWE"
if ($driver) {
Write-Host "Current driver(s)" -ForegroundColor Yellow
$driver | Format-Table -AutoSize
}
else {
Write-Warning "No nvidia drivers found"
}
Write-Host "Script Complete" -ForegroundColor Green
return $false
}
return $true
}
and in the main part of your script do
if ($isAdmin) {
if (Namespace_Check) {
Write-Host
InstallSWE
Write-Host
CheckNVIDIADriver
Write-Host
SetNVIDIA3DGlobalPreset
Write-Host
SetScreenSaver
Write-Host
ChangePowerSettings
Write-Host
ChangeVirtualMemory
Write-Host
EnableRDP
Write-Host
}
}
else {
Write-Warning "Administrator rights is required to run this script"
Write-Host
}
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# end of script
This will make the script end gracefully instead of when using the exit statement.

how to automate Wusa with remoting and overcoming the lack of wait cmd

Scenario: Taking a list of kb files and executing them remotely with WUSA install of target machines across network.
The flow is like this:
enter a powershell session W/ target computer
for each loop $KB in $List
wusa.exe $kb
wait 'til installed
back to the wusa.exe for next device in $list
Code:
# SET UP ERROR-HANDLING FOR THE PS SESSION
$ErrorActionPreference = "continue"
# DECLARE VARIABLE THAT CONTAINS LIST OF PATCHES AVAILABLE FOR INSTALL
$PatchList = (Get-ChildItem -Path C:\WinPatch -recurse | Where-Object {$_.Extension -eq '.msu'})
# ESTABLISH LOOP TO ITERATE THRU PATCHES
foreach ($Patch in $PatchList)
{
Try
{
Write-Host ("`n Preparing to install: " + $Patch) -ForegroundColor Yellow
Write-Host ("`n Installing...") -ForegroundColor Magenta
$SB = {
$arglist = "$Patch", "/quiet", "/norestart"
Start-Process -FilePath "C:\windows\system32\wusa.exe" -ArgumentList $arglist -Wait}
Invoke-Command -ScriptBlock $SB
Write-Host "`n Installation complete`n" -ForegroundColor Green
}
Catch
{
[System.Exception]
Write-Host "Installation failed with Error -- $Error()" -ForegroundColor Red
$Error.Clear()
}
}
# RESTART OPTIONS
$Ans1 = Read-Host "`n Would you like to restart this computer now (Type Y for yes or N for no)"
if ($Ans1 -eq 'Y' -or $Ans1 -eq 'y')
{
Remove-Item -Path C:\WinPatch\*.msu -Force
Write-Host "`n This computer will restart in 5 seconds..." -ForegroundColor Yellow
Start-Sleep -Seconds 5
Restart-Computer -Force
}
else
{
# TEST COMPUTER FOR PS VERSION
$Tester = test-wsman -computername localhost | Select-Object -Property ProductVersion
if ($Tester.ProductVersion.EndsWith("1.0"))
{
Write-Host "`n This computer has PS v1.0 installed and you will have to open Task Scheduler to schedule restart" -ForegroundColor Red
Read-Host "`n Press ENTER to continue..."
}
elseif ($Tester.ProductVersion.EndsWith("2.0"))
{
Write-Host "`n This computer has PS v2.0 installed and you will have to open Task Scheduler to schedule restart" -ForegroundColor Red
Read-Host "`n Press ENTER to continue..."
}
else
{
# SCHEDULE RESTART
Import-Module PSScheduledJob
$RST = Read-Host -Prompt "`n Enter date/time to restart computer...format is --> mm/dd/yyyy hh:mmAM/PM"
$Ans2 = Read-Host -Prompt "`n You entered: $RST... if this is correct, enter Y for yes"
if ($Ans2 -eq 'Y' -or $Ans2 -eq 'y')
{
$Nomen = Read-Host -Prompt "`n Enter name for scheduled restart "
$Trig = New-JobTrigger -Once -At $RST
Register-ScheduledJob -Name $Nomen -Trigger $Trig -ScriptBlock { Restart-Computer -force } -RunAs32
}
else
{
Write-Host "`n Please restart the script and try again" -ForegroundColor Red
}
}
}
Break
PsExec.exe -u $domain\$username -p $password -h -s -accepteula \\$computer wusa.exe /quiet 'C:\Program Files\WindowsPowershell\Modules\windows10.0-kb5005112-x64.msu' /wait /forcerestart
This works for me. If you wrap this in an Invoke-Command block you can run this remotely. :-)
Thanks,

Assistance in properly scripting a Join and Un-Join Domain script

Hello guys i have started to create a script that would basically automate the un-join and joining of a computer via a script this initially works fine right up until the point i need to start pinging for the computer to come back online. For the instance of un-joining it works fine but all the issue arise when trying to join.
Maybe fresh pair of eyes can lend me some Intel on the matter thank you.
<#
############################################################################################################
# Written by CPineda # NOTE: This only works if computer is on the wire. #
# This Script un-joins and re-joins the domain. # So its very important that we connect the devce #
# Created: 04/27/2016 # to the LAN. #
# Last revision 4/6/2016 # #
############################################################################################################
#>
# Set up your Variables
$ComputerIP = "" #Stores the Computers IP
$ComputerName = "" #Stores the Name of the computer you will be working with.
#$LocalCredentials = "" #Stores the Local Administrator credentials. (As Neeeded)
$DomainCredentials = "" #Stores the Domain Administrator credentials.
# Get information needed for the script to run.
while ($ComputerIP -eq ""){
Clear-Host #Clear the PS Console Window
$ComputerIP = Read-Host "Enter the name of the Computer IP"
}
while ($ComputerName -eq ""){
Clear-Host #Clear the PS Console Window
$ComputerName = Read-Host "Enter the name of the Computer"
}
<# while ($LocalCredentials -eq ""){
Clear-Host #Clear the PS Console Window
$LocalCredentials = Read-Host "Enter the User name of the Local User Admin Account"
}
#>
while ($DomainCredentials -eq ""){
Clear-Host #Clear the PS Console Window
$DomainCredentials = Read-Host "Enter the User name of the Domain User Admin Account"
}
# Remove the computer from the Domain.
Remove-Computer -ComputerName $ComputerName -LocalCredential $ComputerName\administrator -UnJoinDomainCredential kelsonfla\$DomainCredentials -WorkgroupName WORKGROUP -Force -Restart
Read-Host "Hit ENTER to continue"
# Ping until computer returns on the wire.
Clear-Host
Write-Host "At this time we will ping the compputer in question untill it returns back online"
Write-Host "Hit ENTER to continue"
Read-Host
Test-Connection ($ComputerIP) {
$result = Test-Connection $ComputerIP -Count 3 -Delay 10 -Quiet
if ($Result | where { $_ -match 'Reply from ' }){$true}
else {$false}
}
Write-Verbose "The computer $ComputerIP has went down for a reboot. Waiting for it to come back up..."
while (!(Test-Connection -ComputerName $ComputerIP)) {
Start-Sleep -Seconds 5
Write-Verbose "Waiting for $ComputerIP to come back online"
}
Write-Verbose "The computer $ComputerIP has come online. Waiting for OS to initialize"
$EapBefore = $ErrorActionPreference
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
while (!(Get-WmiObject -ComputerName $ComputerIP -Class Win32_OperatingSystem -Credential $LocalCredentials)) {
Start-Sleep -Seconds 5
Write-Verbose "Waiting for OS to initialize..."
$ErrorActionPreference = $EapBefore
}
# Add computer back to the Domain.
Add-Computer -ComputerName $ComputerIP -LocalCredential $ComputerName\administrator -DomainName kelsonfla.local -Credential kelsonfla\$DomainCredentials -Restart -Force
Read-Host "Hit ENTER to continue"
# Ping until computer returns on the wire.
Clear-Host
Write-Host "At this time we will ping the compputer in question untill it returns back online"
Write-Host "Hit ENTER to continue"
Read-Host
Test-Connection ($ComputerIP) {
$result = Test-Connection $ComputerIP -Count 3 -Delay 10 -Quiet
if ($Result | where { $_ -match 'Reply from ' }){$true}
else {$false}
}
Write-Verbose "The computer $ComputerIP has went down for a reboot. Waiting for it to come back up..."
while (!(Test-Connection -ComputerName $ComputerIP)) {
Start-Sleep -Seconds 5
Write-Verbose "Waiting for $ComputerIP to come back online"
}
Write-Verbose "The computer $ComputerIP has come online. Waiting for OS to initialize"
$EapBefore = $ErrorActionPreference
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
while (!(Get-WmiObject -ComputerName $ComputerIP -Class Win32_OperatingSystem -Credential $LocalCredentials)) {
Start-Sleep -Seconds 5
Write-Verbose "Waiting for OS to initialize..."
$ErrorActionPreference = $EapBefore
}
Clear-Host
Write-Output "If you are Reading this then you have successfully Unjoined and Re-Joined a Computer to the Network"
Start-Sleep -Seconds 3
Clear-Host
First : for the ping part, you should remove the code :
Test-Connection ($ComputerIP) {
$Result = ping $ComputerIP -n 3
if ($Result | where { $_ -match 'Reply from ' }) {
$true
} else {
$false
}
}
and simply use
!$result = $false
do {
Write-Verbose "Waiting for $ComputerIP to come back online"
$result = Test-Connection $ComputerIP -Count 2 -Delay 5 -Quiet
} while (!$result)
And then use the value of the $result boolean to see if your computer is reponding again. Test-Connection is a Cmdlet that cover the ping role.

Remove-ADComputer : Access is denied powershell

Long time lurker but I finally found a problem that I could not find an answer for so I decided it was time to join. Im trying to collect a list of computers in AD that are older than X days ($DelCompDays). Then based off of the DistinguishedName field delete that computer using the Identity flag. Problem is even with domain admin creds I am getting: Remove-ADComputer : Access is denied
Even if I run Remove-ADComputer -Identity "Full CN or Short name" I get an access denied. Anyone have any ideas? Thank you in advance!
#Get AD computers older than $DelCompDays
$results = Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan "$DelCompDays.00:00:00"
#Loop and try to delete
foreach ($result in $results){
if ($result -ne $NULL){
try {
Remove-ADComputer -Identity $result.DistinguishedName -confirm:$false
$Success = "Deleted: $result.DistinguishedName"
WriteCustomOutput -message "$Success" -foregroundcolor green -backgroundcolor DarkMagenta
}
catch {
$Error = "Failed to delete: $result.DistinguishedName"
WriteCustomOutput -message "$Error" -foregroundcolor Red -backgroundcolor Black
}
}
else{
$Warning = "No computers older than $ArcDays days to delete"
WriteCustomOutput -message "$Warning" -foregroundcolor yellow -backgroundcolor DarkMagenta
}
}
Figured it out. When running non-interactive you need to specify the creds in the command call.
$secpasswd = ConvertTo-SecureString "ClearTextPass" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("Username", $secpasswd)
Remove-ADComputer -Identity $result.DistinguishedName -Recursive -confirm:$false -credential $creds

Powershell - verify object exists in AD

i have a text file containing arround 100 servers, how can i push these into a script and test if they exist within AD? I have a simple script below:
$serverlist = get-content ServerList.txt
foreach ($server in $serverlist) {
if (Get-ADComputer $serverlist ) {
Write-Host "#########################"
Write-Host "Computer object exists"
Write-Host "#########################"
}
else {
Write-Host "#########################"
Write-Host "Computer object NOT FOUND"
Write-Host "#########################"
}
}
the above does not work returning a error:
Get-ADComputer : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADComputer' required by parameter 'Identity'. Specified method is not supported.
Can someone please explain does the get-adcomputer only allow a single object? Also if i remove the txt file and add a server shown below:
if (Get-ADComputer "server name" )
The above provides only results if the server exists within AD, if the server does not the error is shown below:
Get-ADComputer : Cannot find an object with identity: 'iuiub' under: 'DC=####,DC=#####,DC=#####'
Thank you for any insight / help!
Phil
Create an array - #(). If the array has 1 or more objects in it - which is $true - then you know the computer exists. If the array has 0 objects in it - which is $false- then you know the computer doesn't exist. I know some people don't like the ErrorAction to be set to SilentlyContinue but you're "Outputting an Error" if an error does occur.
$serverlist = get-content ServerList.txt
foreach ($server in $serverlist) {
if (#(Get-ADComputer $server -ErrorAction SilentlyContinue).Count) {
Write-Host "#########################"
Write-Host "Computer object exists"
Write-Host "#########################"
}
else {
Write-Host "#########################"
Write-Host "Computer object NOT FOUND"
Write-Host "#########################"
}
}
Another thing you could try are try catch blocks. Sorta like this:
$serverlist = get-content ServerList.txt
foreach ($server in $serverlist) {
try{
Get-ADComputer $server -ErrorAction Stop
Write-Host "#########################"
Write-Host "Computer object exists"
Write-Host "#########################"
}
catch{
Write-Host "#########################"
Write-Host "Computer object NOT FOUND"
Write-Host "#########################"
}
}
Line 3, change $serverlist to $server
With regards to handling a not found result. I'd try flipping the logic :
$serverlist = get-content ServerList.txt
foreach ($server in $serverlist) {
$tempVar = Get-ADComputer $server
if ($tempVar -like "Get-ADComputer : Cannot find an object with identity" ) {
Write-Host "#########################"
Write-Host "Computer object NOT FOUND"
Write-Host "#########################"
}
else{
Write-Host "#########################"
Write-Host "Computer object exists"
Write-Host "#########################"
}
}
In order to get a more helpful output, I'd go with the following... You'll just have a list of green and red lines indicating which server was found and which one wasn't.
$serverlist = get-content ServerList.txt
foreach ($server in $serverlist) {
try {
Get-ADComputer $server -ErrorAction Stop | Out-Null
Write-Host "$($server) exists" -ForegroundColor DarkGreen
}
catch {
Write-Host "$($server) NOT FOUND" -ForegroundColor DarkRed
}
}