Keeping Newlines in Powershell For Loop

时间:2019-04-16 23:34:15

标签: powershell

I have a list of DisplayNames and I wan't to look up each of the SamAccountNames, but when I do I want to keep a blank line when there is no SamAccountName is found. Right now when I run it against my list of 400 DisplayNames the output is only 350, but I don't know where those 50 in my list that are missing. What I have right now is:

Get-Content C:\list.txt | ForEach-Object {(Get-ADUser -Filter {DisplayName -eq $_}).SamAccountName}

I've used a similar syntax with other commands that do produce blank lines, but as far as I can tell using -Filter seems to change it some how that causes the blank lines to no longer be present.

So, instead of something like this:

jonesb
williamsj

bakere

I get:

jonesb
williamsj
bakere

3 个答案:

答案 0 :(得分:1)

You can do this with an If statement inside your ForEach-Object loop by capturing the results of the Get-ADUser call, and then outputting the samaccountname if the user was found, and outputting an empty string if it wasn't found.

Get-Content C:\list.txt | 
    ForEach-Object {
        If(($User=Get-ADUser -Filter "DisplayName -eq '$_'")){
            $User.SamAccountName
        }else{
            ''
        }
    }

答案 1 :(得分:1)

400 DisplayNames minus 350 SamAccountNames gives 10?

I'd prefer an output where you see the DisplayName a SamAccountName couldn't be evaluated for.

$Data = foreach ($DisplayName in (Get-Content C:\list.txt)){
    [PSCustomObject]@{
        DisplayName    = $DisplayName
        SamAccountName = (Get-ADUser -Filter "DisplayName -eq '$DisplayName'").SamAccountName
    }
}
$Data | Out-GridView
$Data | Export-Csv C:\list.csv -NoTypeInformation

答案 2 :(得分:0)

First, an aside: It's best to avoid the use of script blocks ({ ... }) as -Filter arguments, which is why the solution below uses a string argument.


  • Using Get-AdUser with a -Filter argument that matches no users quietly returns "nothing" (effectively, $null), and, as a consequence, accessing the .SamAccountName property on that "nothing" returns $null.

  • While such a $null is present in the output, it doesn't print; you can make it print - as an empty line - if you cast it to a string:

Therefore:

Get-Content C:\list.txt | ForEach-Object {
  [string] (Get-ADUser -Filter "DisplayName -eq `"$_`"").SamAccountName
}

However, to provide context, consider outputting a [pscustomobject] instance in each iteration that includes the input display name, as shown in LotPings' helpful answer.