Stephen Archbold
Stephen Archbold

Reputation: 93

Using PowerShell how to I split the string of a selected property

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.

Upvotes: 1

Views: 3532

Answers (3)

mklement0
mklement0

Reputation: 437833

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] })

Upvotes: 1

WayneA
WayneA

Reputation: 339

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}}

Upvotes: 0

EBGreen
EBGreen

Reputation: 37730

You can create custom results with Select-Object:

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

Upvotes: 2

Related Questions