Note:
Generally, it's better to use PowerShell commands, so you don't have to rely on parsing text and can operate objects and their properties: see Get-ADUserGroupMember
; in the simplest case (doesn't distinguish between members of type user, computer, and group):
(Get-ADUserGroupMember $groupName).Name > $outFile
If you don't have the ActiveDirectory
module installed / cannot install it, you can use the [adsi]
class (short for: System.DirectoryServices.DirectoryEntry
), as Santiago Squarzon recommends:
If you want to stick with your text-parsing approach, use the unary form of the -split
operator to parse the output from your net.exe group
call, which splits strings by runs of whitespace, ignoring leading and trailing whitespace:
# ...
-split $transform > $outFile
Caveat: This won't work if the group member names themselves contains space. If they do, you'd have to split by runs of multiple spaces, under the assumption that such runs are exclusive to the whitespace separating the names:
# ...
$transform -split ' +' > $outFile # split by 2 or more spaces
Note: >
is an effective alias of Out-File
, which means that in Windows PowerShell you'll get a "Unicode"-encoded file (UTF-16LE). If that is undesired, pipe to | Set-Content -Encoding utf8 $outFile
, for instance.
To illustrate with simple examples that simulate the relevant part of net group
's output:
PS> -split (
'groupmemberOne groupmemberTwo groupmemberThree',
'groupmemberFour groupmemberFive groupmemberSix'
)
groupmemberOne
groupmemberTwo
groupmemberThree
groupmemberFour
groupmemberFive
groupmemberSix
PS> (
'groupmember One groupmember Two groupmember Three',
'groupmember Four groupmember Five groupmember Six'
) -split ' +'
groupmember One
groupmember Two
groupmember Three
groupmember Four
groupmember Five
groupmember Six