I'm having trouble terminating a foreach-object loop in PowerShell v2. For a rough idea of the task I'm trying to accomplish, here's the pseudo-code:
- Read lists of host machines from a text file
- For each host in the text file get Win32_Product (filtered against an exclusion list), convert output to html and save.
The reason for the script is that I've amassed a text file listing all applications included on standard client images, and would like to periodically scan hosts from another text file to see if there are any unauthorized, sketchy or otherwise unnecessary applications on the host machines.
The code does work in a rough sense, but the main issue I'm having is that the script will not terminate without manual intervention. I guess the component I'm missing here is to run the loop until some condition exists (ie. first line in the host file is encountered for the second time), then terminates the script. Although this is the method I've envisioned, I am always open to other logic, especially if its more efficient.
Here's the actual code:
Get-Content c:\path\to\testhostlist.txt | Foreach-Object {
Get-WmiObject Win32_Product |
Where-Object { $_.Name -f "'C:\path\to\testauthapplist.txt'" |
ConvertTo-Html name,vendor,version -title $name -body "<H2>Unauthorized Applications.</H2>"}} |
Set-Content c:\path\to\unauthapplisttest.html
$_.Name -f "'C:\path\to\testauthapplist.txt'"doesn't make sense, because$_.Nameisn't a format string. Perhaps there was a copy/paste error? It seems like there's something missing between$_.Nameand-f. Also, how would the first line of the host file be encountered a second time if you're only listing it once? This doesn't even seem to be an infinite loop that would need an exit condition. Foreach-Object doesn't repeat indefinitely. Maybe it's just getting stuck because the code is mangled.Where-Object { $_.Name -f "'C:\path\to\testauthapplist.txt'" |. I suspect that the problem is that that's not the correct syntax for whatever you're trying to do.Get-WmiObject Win32_Productis very slow, and you are doing it for each line in your input file. You should do it once at the beginning and keep the result in a list. I agree with Adi that your where-object is strange. I think you need to take a step back and rework the whole thing.