I am trying to write a Powershell script that will use the Write-Host commands a couple of times. when i run the script i get the output of the Write-host and then the output from the commands themselves. I've looked and Googled this issue but no joy. here is the script if any one can help?
#Use this script to find all acounts in the External Contractors OU with accounts that have expired and will expire with in the next 365 days
$cred = Get-Credential
Write-Host "Accounts due to expire in the next 365 days" -ForegroundColor red -BackgroundColor white
Search-ADAccount -Server teeis0002.europe.tel.com -Credential $cred `
-searchbase "OU=External Contractors,OU=Users,OU=xxxxxx,DC=xxxxxx,DC=xxxxxx,DC=xxxxx" `
-AccountExpiring -TimeSpan 365.00:00:00 -UsersOnly -ResultPageSize 2000 -resultSetSize $null |
Select-Object Name, UserPrincipalName, DistinguishedName, AccountExpirationDate |
Sort-Object -Property AccountExpirationDate
Write-Host "Currently Expired Accounts" -ForegroundColor red -BackgroundColor white
Search-ADAccount -Server teeis0002.europe.tel.com -Credential $cred `
-searchbase "OU=External Contractors,OU=Users,OU=xxxxxx,DC=xxxxxx,DC=xxxxxx,DC=xxxxx" `
-AccountExpired -UsersOnly -ResultPageSize 2000 -resultSetSize $null |
Select-Object Name, UserPrincipalName, DistinguishedName, AccountExpirationDate |
Sort-Object -Property AccountExpirationDate
I looked at using Do While and For each
If I understand your question correctly, you want to suppress all the output from the commands with the exception of your
Write-Hostlines.In PowerShell, you have a couple of options for that:
[void](Verb-Noun)to keep your terminal screen clean, this casts the output tovoid. There's actually quite a few different ways to go about this, and while they may be technically not doing all the exact same thing, for all intents and purposes it's doing what you want it to do:But sometimes that may not be enough if you also want to suppress error messages (although you should think hard about whether that's something you really want to do but that's besides the point here).
Error messages are expected to written to the error stream. You can read more about streams here.