Powershell - 从PsObject中的AD属性获取最后3个字符

时间:2016-04-12 09:14:43

标签: string csv powershell psobject

我有一个脚本导出到csv的一些AD属性 我希望得到'缩写'的最后3个字符。 PsObject中的属性,但我有一个错误,我花了几个小时... 你能帮帮我吗?

错误:

*Method invocation failed because [Microsoft.ActiveDirectory.Management.ADUser] doesn't contain a method named 'substring'.
At C:\scripts\ExtractDWH\Untitled2.ps1:15 char:26
+                 "Test" = $_.substring <<<< ($_.initials.length - 3, 3)
    + CategoryInfo          : InvalidOperation: (substring:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound*

守则:

 $output = 'c:\scripts\ExtractDWH\consultants_test.csv'
 $users = Get-ADUser -Filter * -SearchBase "ou=Rennes,ou=Consultants,ou=Utilisateurs,ou=FedFinance,dc=dfedinterim,dc=fr" -     Properties *  | ? { ($_.initials -notlike 'IC*') -and ($_.initials -notlike 'IM*') -and ($_.initials -ne $null) }
      fileIn | % {
        $users | % { 
           New-Object psobject -Property @{
               "ID" = $_.initials
               "Last 3 strings ID" = $_.substring($_.initials.length - 3, 3) 
               "Centre Imputation" = $_.extensionAttribute10
               "Date Entrée" = $_.extensionAttribute9
                # The line below does not work                 
               "Test" = $_.substring($_.initials.length - 3, 3) 
             }
         }
     } | Select-Object ID, 'Centre Imputation', 'Date Entrée', 'Test' 
 | Export-CSV $output -Delimiter ';' -Encoding "UTF8" -NoTypeInformation    `

谢谢!

2 个答案:

答案 0 :(得分:2)

改变这个:

"Last 3 strings ID" = $_.substring($_.initials.length - 3, 3) 

To This:

"Last 3 strings ID" = $_.initials.substring($_.initials.length -3, 3)

答案 1 :(得分:1)

Avshalom向您展示了错误。您还可以使用以下内容访问最后3个字符:

"Test" = $_.initials[-3 .. -1] -join ''