using var and out-file in for each loop

This topic contains 7 replies, has 4 voices, and was last updated by  Frank Tucker 1 week, 4 days ago.

  • Author
    Posts
  • #76989

    baschi
    Participant

    Hey guys, yesterday I scripted some ps code and got some issues with it, I were able to solve it but I still have some questions in my head which I would like to get answered. I hope somebody can help 🙂

    $csv=import-csv -path DEHEREMEX48_gotactivated_listpart.txt -Delimiter ";"

    foreach ($line in $csv){
    get-aduser -filter {name -like $line.Name} -Properties ('Name', 'co')| Select Name, co
    }
    didn't work, I got an system.Object error why do I have to transform the var using $changeme=line.Name before I'm able to use it in the loop:

    foreach ($line in $csv){
    $changeme=$line.Name
    get-aduser -filter {name -like $changeme} -Properties ('Name', 'co')| Select Name, co
    }

    2. The output of above delivers a nice table like
    name co
    xyz DE
    yyx DE
    Do I use a >> to write the output to a file like:
    foreach ($line in $csv){
    $changeme=$line.Name
    get-aduser -filter {name -like $changeme} -Properties ('Name', 'co')| Select Name, co >>resul.txt
    }

    I'm getting a table like this one
    name co
    xyz DE
    name co
    yyx DE
    I know the workaround is to load the foreachloop into a var. That's working for me, but I'm still asking myself why I get with the first command a nice table and with the ">>restult.txt" added a really crappy one.

    Best Regards,
    baschi

  • #76990

    Simon B
    Participant

    I would use export-csv to output the data then you can import the results into a database or excel and do further manipulation

    • #76995

      baschi
      Participant

      thanks

      foreach ($line in $csv){
      $changeme=$line.Name
      get-aduser -filter {name -like $changeme} -Properties ('Name', 'co')| Select Name, co | export-csv -path testdel.csv
      }
      

      doesn't give a output in the csv at all.

  • #76998

    Simon B
    Participant

    try giving the csv a full path i.e. Export-csv c:\temp\testdel.csv

    • #77013

      baschi
      Participant

      still not. But thanks for your help. To be honest this is not what I'm searching for I already have an workaround with the variable I want to get an explanation as written in the startpost

  • #77016

    David Schmidtberger
    Participant

    while i don't have a good explanation, i'll wait for Don or one of the real experts.

    my process for this would be to do $($line.Name) instead of just $line.Name

    this always works for me

  • #77022

    Simon B
    Participant

    " i'll wait for Don or one of the real experts"

    Does this mean that Don is not one of the experts 🙂 lol

  • #77040

    Frank Tucker
    Participant

    I THINK it just a limitation with -Filter not the looping.
    Believe it will work with -Identity

You must be logged in to reply to this topic.