无法修剪/修改“$”

时间:2014-08-26 12:05:00

标签: powershell active-directory powershell-v2.0

我正在尝试从在线资源修改PS脚本:

Trap {"Error: $_"; Break;}

$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"

$Searcher.Filter = "(objectCategory=computer)"

$Searcher.PropertiesToLoad.Add("samAccountName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null

# Create hash table of users and their last logon dates.
$arrComp = @{}

# Enumerate all Domain Controllers.
ForEach ($DC In $D.DomainControllers)
{
$Server = $DC.Name
$Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
{
    $DN = $Result.Properties.Item("samAccountName")
    $LL = $Result.Properties.Item("lastLogon")
    If ($LL.Count -eq 0)
    {
        $Last = [DateTime]0
    }
    Else
    {
        $Last = [DateTime]$LL.Item(0)
    }
    If ($Last -eq 0)
    {
        $LastLogon = $Last.AddYears(1600)
    }
    Else
    {
        $LastLogon = $Last.AddYears(1600).ToLocalTime()
    }
    If ($arrComp.ContainsKey("$DN"))
    {
        If ($LastLogon -gt $arrComp["$DN"])
        {
            $arrComp["$DN"] = $LastLogon
        }
    }
    Else
    {
        $arrComp.Add("$DN", $LastLogon)
    }
}
}

上面的脚本给了我computername&其'上次登录日期,但计算机名称为" $"在末尾。我想修剪" $"为了让我使用它以后从AD中删除计算机。但是我的脚本无效。

$Compdollar = $arrComp.getEnumerator() | Select-Object Key | out-string

$AllComp = @()
Foreach ($inactD in $Compdollar) {
    $AllComp += $inactD.Trim("$")
    }

$Allcomp

输出仍是计算机名称" $",任何人都可以告诉我为什么它没有被修剪?

1 个答案:

答案 0 :(得分:3)

不要使用带引号的双引号,因为它被视为变量。改为使用单引号。

$AllComp += $inactD.Trim('$')

或者使用反引号来逃避美元符号。

$AllComp += $inactD.Trim("`$")