1

I am very new to PowerShell and I can't seem to find a solution to the the question about splitting my selected properties value in powershell which works for me.

My current code without the split is:

((get-Acl 'c:\temp').Access | where {$_.IdentityReference -like '*\*'} | Select IdentityReference

The purpose is to get a list of users who have access to a folder.

the results give me the domain and the user.

Domain\username

and I just want the username as it will be used in a further SQL query to look up details.

so I figured the best way to do it was to split the returned string on the '\' and take the 2nd value of the array it creates.

so far I am not getting any results back.

  • 2
    `(Get-Acl 'c:\temp').Access | select -ExpandProperty IdentityReference | foreach { $_.Value.Split('\')[1] }` – kuujinbo Jul 20 '18 at 19:54
  • 1
    Great! When you're selecting properties, remember to be aware of each property type. In this case, [IdentityReference](https://msdn.microsoft.com/en-us/library/system.security.principal.identityreference.aspx) is not a string like you were expecting. If in doubt pipe the result to [Get-Member](https://ss64.com/ps/get-member.html) to see what you're working with. – kuujinbo Jul 20 '18 at 20:08

3 Answers3

2

You can create custom results with Select-Object:

(get-Acl 'c:\temp').Access | where {$_.IdentityReference -like '*\*'} | Select @{n='User'; e={$_.IdentityReference.Split('\')[1]}}
EBGreen
  • 36,735
  • 12
  • 65
  • 85
1

In PSv3+ you can take further advantage of member-access enumeration, combined with Split-Path -Leaf (which, as in WayneA's answer, is repurposed to extract the last \-separated component from a <realm>\<username> token):

(Get-Acl c:\temp).Access.IdentityReference | Split-Path -Leaf

Note that I've omitted the where {$_.IdentityReference -like '*\*'} filter, because - as far as I can tell - all .IdentifyReference match this pattern (with the first \-based token either being a domain name, a machine name, or a literal such as NT AUTHORITY or BUILTIN).

Also, this outputs an array of strings containing usernames only - whereas a Select-Object call without -ExpandProperty would output custom objects with the specified (possibly calculated) property/ies instead.

In PSv4+, you can make the command slightly more efficient by using the .ForEach() collection method:

(Get-Acl c:\temp).Access.IdentityReference.ForEach({ ($_ -split '\\')[-1] })
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

EBGreens answer is spot on, but I like to use split-path

You can do something like:

(get-Acl 'c:\temp').Access | where {$_.IdentityReference -like '*\*'} | Select @{name="UserName";Expression={$_.IdentityReference | split-path -leaf}}
WayneA
  • 339
  • 1
  • 7