【问题标题】:There are spaces in string, but I can't split it in powershell字符串中有空格,但我无法在powershell中拆分它
【发布时间】:2022-01-26 06:54:04
【问题描述】:

我想比较用户的组和 DFS 的组,看看用户是否有访问 DFS 的权限。但我陷入了拆分字符串。

这是我的代码的一部分:

$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

$getSGs的值:

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

$getSGsSplit 的值:

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

我想要的是用空格分割 $getSGsSplit:

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

但是我已经尝试了很多模式,它们都不起作用。

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

无论我使用哪种模式,write-host $arr[2] 的控制台仍然是空格。 write-host $arr[2].getType() 的控制台总是 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> 

谁能建议如何解决这个问题?

【问题讨论】:

  • ($getSGsSplit -split '\s').Where({ $_ -ne '' }) 。您的.split\S 结合使用有一个好主意,但.net 方法的.split 参数不采用正则表达式值。 Powershell -Split 运算符虽然可以。

标签: powershell replace split


【解决方案1】:

只考虑你已经拥有的字符串:

下面应该给你你正在寻找的东西:

$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\','')

【讨论】:

    【解决方案2】:

    为什么不简单地遍历 Get-Acl 返回的值并替换每个项目的域部分?

    类似

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

    附注 您的代码 $getSGs = (get-acl $folder).Access | Select-Object -uniq -ExpandProperty IdentityReference 不返回 字符串,而是返回一个 对象 数组,其中包含帐户名称的 Value 属性。
    因为你后来在上面使用了-split('.*\\'),结果变成了一个字符串数组,但是如果你把它去掉,代码会简单得多。

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多