在Powershell中,如何从Get-ADUser结果中删除前x个字符



我有一个Get-ADUser的结果列表,其中列出了OU中的所有用户。输出用户名的格式为"-前缀用户名"。我需要删除7个字符的"-前缀-",然后对剩余的"用户名"部分进行另一次Get-ADUser查找。我发现的问题是,如果我只运行第二次Get-ADUser查找,其中我将$User设置为一个特定的"前缀用户名",它可以正常工作,但当我尝试处理列表时,我要么收到一个错误,在修剪后的用户名后似乎有空格(txt格式列表-Get-ADUser:无法在下面找到标识为"User"的对象(,要么用户名包含一个";我无法从用户名末尾删除(csv格式列表-Get-ADUser:找不到标识为"user"的对象(。

到目前为止,我有:

get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 | 
Select SAMAccountName | 
Out-File C:TempUserList.txt
$UserList = (Get-Content C:TempUserList.txt)
$StandardUsers = ForEach($User in $UserList) {

Write-Host "Now checking $User"
Get-ADUser $User.Substring(7) -Properties * | 
Select-object DisplayName, UserPrincipalName, Mail, Manager,EmployeeID    
}
$StandardUsers | Out-File -FilePath C:TempStandardUserList.txt

首先要提到的是,如果使用Select -ExpandProperty SAMAccountName创建列表,则在文件中只能获得SamAccountnames。

话虽如此,为什么要麻烦一个"介于两者之间"的文件,并简单地做:

# By default, Get-ADUser returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# Only ask for properties that are not already in this list.
Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 -Properties DisplayName, EmailAddress, Manager, EmployeeId |
Select-Object DisplayName, UserPrincipalName, EmailAddress, Manager,EmployeeID |  
Set-Content -Path 'C:TempStandardUserList.txt'

您可能会遇到将其保存到文件(在其中进行格式化(,然后再将其读回的问题。格式化可能是添加"并读取换行符(您认为是空格(。如果你真的需要保存它,那么请执行以下操作(否则只需连接管道(:

$userList = Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 | 
Select-Object SAMAccountName
$userList | 
Out-File C:TempUserList.txt
$standardUsers = $userList |
Select-Object -ExpandProperty SAMAccountName -PipelineVariable user |
ForEach-Object {
Write-Host "Now checking $user"
$userWithoutPrefix = ($user -Replace '^-prefix-','') -Replace '(w|n)$','' # to use a more advanced version of the suggestion by @Avshalom
Get-ADUser $userWithoutPrefix -Properties * | Write-Output
} | 
Select-Object DisplayName, UserPrincipalName, Mail, Manager, EmployeeID
$standardUsers | Out-File -FilePath C:TempStandardUserList.txt