Quick and simple question

This topic contains 5 replies, has 3 voices, and was last updated by  Vandrey Trindade 2 years, 4 months ago.

  • Author
    Posts
  • #27915

    Vandrey Trindade
    Participant

    Hi,

    I'm starting a new script and there is a big blank on my head now...

    This isn't supposed to work?


    $ADTitles = Get-ADUser -Filter {mail -like "*mail.com"} -Properties mail,title | select mail,title | sort mail

    foreach ($Title in $ADTitles){
    Set-MsolUser -UserPrincipalName $_.Mail -Title $_.Title
    }

    The only way to work is to change that line to:

    Set-MsolUser -UserPrincipalName $Title.Mail -Title $Title.Title

    I swear that in my head it should be working =p

  • #27917

    Richard Siddaway
    Moderator

    Your change is the correct one to make.

    $_.XXXX is when you're using the foreach-object cmdlet not a foreach loop

  • #27918

    Vandrey Trindade
    Participant

    Richard Siddaway,

    Thank you very much! =]

  • #27920

    Vandrey Trindade
    Participant

    Another one:

    Is there any benefits (performance) to use the foreach-object cmdlet or the foreach loop?


    $ADTitles | ForEach-Object {
    $_.Mail
    $_.Title
    }

    or


    foreach ($Title in $ADTitles){
    Set-MsolUser -UserPrincipalName $Title.Mail -Title $Title.Title
    }

  • #27921

    Dave Wyatt
    Moderator

    If you already have the collection stored in an array, then the foreach ($thing in $things) { } construct tends to be faster. The pipeline and ForEach-Object, on the other hand, can be used to process items in a streaming fashion without having to store them all in memory at one time (which can become a concern if you're dealing with very large data sets.)

  • #27922

    Vandrey Trindade
    Participant

    Dave Wyatt,

    Thank you for the information!

    Tried here to see:

    PS C:\Office 365> Measure-Command {$ADTitles | ForEach-Object {
    $_.Mail
    $_.Title
    }}

    Days : 0
    Hours : 0
    Minutes : 0
    Seconds : 0
    Milliseconds : 43
    Ticks : 432688
    TotalDays : 5,00796296296296E-07
    TotalHours : 1,20191111111111E-05
    TotalMinutes : 0,000721146666666667
    TotalSeconds : 0,0432688
    TotalMilliseconds : 43,2688

    PS C:\Office 365> Measure-Command {foreach ($Title in $ADTitles){
    $Title.Mail
    $Title.Title
    }}

    Days : 0
    Hours : 0
    Minutes : 0
    Seconds : 0
    Milliseconds : 7
    Ticks : 71764
    TotalDays : 8,30601851851852E-08
    TotalHours : 1,99344444444444E-06
    TotalMinutes : 0,000119606666666667
    TotalSeconds : 0,0071764
    TotalMilliseconds : 7,1764

You must be logged in to reply to this topic.