Hello,
I am fairly new to PowerShell and am drawing a blank on what a Try/Catch is not running when part of an If/Else inside of a ForEach loop. I am working to automate license collections (partial key only) of existing and new client devices when onboarding new environments as part of my job at an MSP. The script runs the ForEach fine and collects the info I'm looking for, but it's ignoring the IF/ELSE and TRY/CATCH, so we keep getting duplicate entries in the resulting CSV and we're not getting an exceptions log to see what systems are not responding to requests for information.
The end goal is to remove the $cred variable and setup a scheduled task to run twice a day to eventually collect all device licensing info to hand off to the business for software inventory among other things. Any assistance would be greatly appreciated. I'm assuming this is either a syntax issue or my own ignorance of how these commands run.
Clear-Host
$DomName = Get-ADDomain |Select -Expand NetBIOSName
New-Item -ItemType Directory -Force -Path C:\TEMP\${DomName}_Onboarding\${DomName}_ServerLicensing\
Get-ADComputer -Filter {(OperatingSystem -Like '*Server*') -AND (Enabled -Eq 'TRUE')}|Select -Expand Name|Out-File C:\TEMP\${DomName}_Onboarding\${DomName}_ServerLicensing\Servers.txt
$cred=Get-Credential
$servers = Get-Content C:\TEMP\${DomName}_Onboarding\${DomName}_ServerLicensing\Servers.txt
$collected = Get-Content C:\TEMP\${DomName}_Onboarding\${DomName}_ServerLicensing\PS_MSOLicenses.csv
foreach ($server in $servers)
{
if ($server -in $collected.PSComputerName)
{
Write-Host "$server information already collected."
}
else
{
Write-Host "$server information NOT yet collected."
try {
(Get-WmiObject -Class SoftwareLicensingProduct -Filter 'ProductKeyId != NULL'-Computername $server) | Select-Object -Property PSComputerName,Name,Description,LicenseFamily,ProductKeyChannel,PartialProductKey |Export-csv C:\TEMP\${DomName}_Onboarding\${DomName}_ServerLicensing\PS_MSOLicenses.csv -NoTypeInformation -Append
}
catch {
"$server could not be contacted. System may be Windows Server 2008, be offline, or PS Remoting is not enabled." | Out-File -Append C:\TEMP\${DomName}_Onboarding\${DomName}_ServerLicensing\${DomName}_Server_Licensing_Exceptions.csv
}
}
}
Thanks again for any and all assistance.