Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Looking for better way to output Foreach loop statements correctly to CSV

$
0
0

New to Powershell here. I'm trying to figure out a better way to write this short script. The script searches through a list of groups and determines if those groups meet certain parameters. If they do, the script outputs the group names to a CSV file under a certain column heading:

cls

$results = foreach($name in gc C:\GroupList.txt){

get-adgroup -filter 'Name -eq $name' -Properties * | select `
@{n="HasOwner";e={If($_.Managedby -ne $null){$name}}},`
@{n="HasUser";e={If(  (($_.Name) | get-adgroupmember | %{$_.objectclass}) -eq 'User'){$name}}}
}

$results | Export-Csv C:\results.csv

invoke-item C:\results.csv

The problem here of course is that if a group doesn't meet both criteria, the next group through the loop will not output on the first available row in the CSV file.

Take for example 2 groups, Group1 and Group2. Group1 has an owner but no users. Thus, Group1 will be output to Row1 under the "HasOwner" column in the CSV file as shown below, but Row1 of the "HasUser" column will be left blank because Group1 has no user. Great.

Group2 has no owner, but does have a user. Thus, Group2 will be output to Row2 under the "HasUser" column in the CSV file as shown below, but Row2 of the "HasOwner" column will be left blank because Group2 has no owner. The complete results look as follows:

I would like for there to be no blank spaces above and below group names, but my current code doesn't allow for this. How can I re-write my code above to get Group1 and Group2 on the same line?


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>