String Replace()/ Remove()不起作用

时间:2017-03-23 10:50:15

标签: powershell

我想删除搜索和分组的字符串的一部分,否则无法搜索它,但Replace() / Remove()无效:

    $RootPath = $Selection
    $Folders = dir $RootPath | where {$_.PSIsContainer -eq $true}
    try {
        foreach ($Folder in $Folders) {
            $ACLs = Get-Acl $Folder.FullName | ForEach-Object {
                $_.Access
            }
            foreach ($ACL in $ACLs) {
                if ($ACL.IdentityReference -notlike "Administrators" -and $ACL.IdentityReference - notlike "Creator Owner" - and $ACL.IdentityReference -notlike "BUILTIN\Administrators" -and $ACL.IdentityReference -notlike "NT AUTHORITY\SYSTEM" -and $ACL.IdentityReference -notlike "System") {
                    $strAcl = $ACL.IdentityReference
                    # value is for instance GESCOEUROPE\GR_G-FCASB-INT-ALL
                }
            }
        }

        $strNames = $strAcl.Replace("GESCOEUROPE\", "")
        # or:
        #$strNames = $strAcl.Remove(0, 12)

        $strUsers = Get-ADGroupMember -Identity $strNames -Recursive |
                    Get-ADUser -Property DisplayName |
                    Select Name |
                    Sort-Object Name
        $OutInfo = $Folder.FullName + "," + $trAcl + $strUsers
        $OutInfo | Select-Object -Unique
        Add-Content -Value $OutInfo -Path $OutFile | Sort-Object -Unique
    } catch [System.IO.IOException] {
    }
}

1 个答案:

答案 0 :(得分:4)

您将$strAcl设置为$ACL.IdentityReference,其类型为[System.Security.Principal.NTAccount](使用Get-Member验证); 字符串,因此您无法在其上调用.Replace()

如果您要对$ACL.IdentityReference进行字符串化,请在其上调用.ToString(),或将其强制转换为[string],或将其括在双引号字符串中的表达式中:

# Call .ToString()
$strAcl = $ACL.IdentityReference.ToString()

# Cast to [string]
$strAcl = [string] $ACL.IdentityReference

# Use string interpolation:
$strAcl = "$($ACL.IdentityReference)"

注意:在 this 的情况下,所有3种方法都是等效的,但有些情况.ToString() 文化敏感 [1] < / SUP> ,而其他两种方法总是文化 - 敏感。

[1]尝试[cultureinfo]::CurrentCulture = 'de-DE'; (0.5).ToString(); [string] 0.5; "$(0.5)"