locked
Export Powershell results to CSV file RRS feed

  • Question

  • Hi,

    I've written a short PowerShell script to get all the user names and their email addresses from a MOSS 2007 site. I could able to get the results but I am unable to export them to a CSV file. Please see the below script.

    $site = New-Object Microsoft.SharePoint.SPSite("http://localhost/sites/intranet")
    $groups = $site.RootWeb.sitegroups
    foreach ($grp in $groups) {
    foreach ($user in $grp.users) {
    "  User: " + $user.name +
    "'t User Email: "+ $user.Email

    } }
    $site.Dispose()

    Can anyone help me on that?

    Thanks,


    Kunal

    Friday, May 12, 2017 3:18 PM

Answers

  • Hi Kunal.

    Add the following lines at the beginning of the script

    [string]$FileName = ".\UsersList.csv"
    $FileHeader = '"UserName", "Email"'
    Add-Content -path $FileName -value $FileHeader

    This will declare the CSV file, create an header for the file and write the header to the file. Pay attention to the simple quote (') at the beginning and at the end of the string value assigned to the $FileHeader variable.
    Then add the following lines as the last instructions in the body of the ForEach loop

    $UserEntry = '"'+ $user.name + '", + '"' + $user.Email + '"'
    Add-Content -path $FileName -value $UserEntry

    Bye.


    Luigi Bruno
    MCP, MCTS, MOS, MTA

    • Edited by Luigi BrunoMVP Friday, May 12, 2017 4:31 PM
    • Proposed as answer by romeo donca Friday, May 12, 2017 7:00 PM
    • Marked as answer by Kunal Basu Saturday, May 13, 2017 6:58 AM
    Friday, May 12, 2017 4:31 PM

All replies

  • Hi Kunal.

    Add the following lines at the beginning of the script

    [string]$FileName = ".\UsersList.csv"
    $FileHeader = '"UserName", "Email"'
    Add-Content -path $FileName -value $FileHeader

    This will declare the CSV file, create an header for the file and write the header to the file. Pay attention to the simple quote (') at the beginning and at the end of the string value assigned to the $FileHeader variable.
    Then add the following lines as the last instructions in the body of the ForEach loop

    $UserEntry = '"'+ $user.name + '", + '"' + $user.Email + '"'
    Add-Content -path $FileName -value $UserEntry

    Bye.


    Luigi Bruno
    MCP, MCTS, MOS, MTA

    • Edited by Luigi BrunoMVP Friday, May 12, 2017 4:31 PM
    • Proposed as answer by romeo donca Friday, May 12, 2017 7:00 PM
    • Marked as answer by Kunal Basu Saturday, May 13, 2017 6:58 AM
    Friday, May 12, 2017 4:31 PM
  • Hi Luigi Bruno,

    Thanks for the help. It worked.

    Thanks,


    Kunal

    Saturday, May 13, 2017 6:59 AM
  • Hi Luigi Bruno,

    Thanks for the help. It worked.

    Thanks,


    Kunal

    You're welcome, thanks for the feedback.

    Bye.


    Luigi Bruno
    MCP, MCTS, MOS, MTA

    Saturday, May 13, 2017 5:14 PM