PurpleMist
PurpleMist

Reputation: 33

I can't get Powershell StartsWith function to work

I'm trying to create a Powershell script that prints out only certain AD groups from the Folder Permission settings. However for some reason Powershell doesn't recognize StartsWith function.

("C:\folder" | get-acl).Access | ForEach-Object { if (($_.IdentityReference).StartsWith("sl_test")) { continue }; $_ }

When I run this I got errors similar to this for every foreach object:

Method invocation failed because [System.Security.Principal.NTAccount] does not contain a method named 'StartsWith'. At C:\temp\test.ps1:1 char:56 + ("C:\folder" | get-acl).Access | ForEach-Object { if (($_.IdentityReference).St ... + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound

Any suggestions on how to get this to work?

Upvotes: 2

Views: 2735

Answers (3)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

If you want the string representation of an IdentityReference (regardless of whether it's and NTAccount object or a SID), you can reference the Value property:

$_.IdentityReference.Value.StartsWith('sl_test')

Upvotes: 1

guiwhatsthat
guiwhatsthat

Reputation: 2434

Try:

Get-Acl -Path "C:\folder" | Select-Object -ExpandProperty Access | Where-Object {$_.IdentityReference -like "sl_test*" }

You can customize the output with an additional | Select-Object -Property XY

Upvotes: 0

Martin Ba
Martin Ba

Reputation: 38861

IdentityReference is a [System.Security.Principal.NTAccount]according to your error message.

But .StartWith is a method on the String type. If you call a method, Powershell does no magic for you, AFAIK.

Try ... ($_.IdentityReference) -match "^sl_test" ..., which should do the implicit string conversion.

Upvotes: 3

Related Questions