Home > Mobile >  There are spaces in string, but I can't split it in powershell
There are spaces in string, but I can't split it in powershell

Time:12-28

I want to compare user's groups and DFS's groups to find out if the user has access authority to DFS. but I got stuck in split string.

here is part of my code:

$folder = Read-Host 'Enter the folder path'
$User = Read-Host 'Enter the sAMAccountName of user'
$getSGs = (get-acl $folder).Access | Select-Object -uniq -ExpandProperty IdentityReference 
$getSGsSplit = $getSGs -split('.*\\')
$arr = $getSGsSplit -split ' '
Write-Host $arr

the value of $getSGs:

domain-ORG\xxx-Read domain-ORG\xxx-Modify domain-ORG\xxx-Admin domain-ORG\xxx-Center domain-ORG\xxxx-Admin BUILTIN\Administrators

the value of $getSGsSplit:

 xxx-Read  xxx-Modify  xxx-Admin  xxx-Center  xxxx-Admin  Administrators 

What I Want is to split the $getSGsSplit by spaces:

xxx-Read
xxx-Modify
xxx-Admin
xxx-Center  
xxxx-Admin
BUILTIN\Administrators 

BUT I have been tried lots of patterns, all of them doesn't work.

$getSGsSplit -split ' .-`t`n`r'
$getSGsSplit -replace ' ','\n'
$getSGsSplit.split(' ').trim()
$getSGsSplit.split('\s').trim()
$getSGsSplit -split ' '

And no matter which pattern I used , the console of write-host $arr[2] still were spaces. And console of write-host $arr[2].getType() always were System.String

PS C:\Users\zzz\Desktop> C:\Users\zzz\Desktop\12.ps1
Enter the folder path: \\domain.org\xxx\xx\xxx
Enter the sAMAccountName of user: zzz


PS C:\Users\zzz\Desktop> 

Can anyone advise how to resolve this?

CodePudding user response:

Why not simply loop over the values returned by Get-Acl and replace the domain part on every item?

Something like

((Get-Acl $folder).Access | 
    Select-Object IdentityReference -Unique).IdentityReference | 
    ForEach-Object { $_ -replace '^domain-ORG\\' }

P.S. Your code $getSGs = (get-acl $folder).Access | Select-Object -uniq -ExpandProperty IdentityReference does not return a string, but an array of objects with a Value property in which the account name is held.
Because you later use -split('.*\\') on it, the result becomes an array of strings, but if you simply leave that out the code can be much simpler.

CodePudding user response:

Just considering the string that you already have:

Below should give you what you are looking for:

$a= "domain-ORG\xxx-Read domain-ORG\xxx-Modify domain-ORG\xxx-Admin domain-ORG\xxx-Center domain-ORG\xxxx-Admin BUILTIN\Administrators"

($a -split '\s').replace('domain-ORG\','')
  • Related