locked
Foreach with Export-csv - Blank file RRS feed

  • Question

  • Hi All,

    Trying to run this simple script but not able to export data in to the txt/csv file. Each script runs fine and shows results in PS console but out put file (test.csv) is always blank. Can some one share thoughts on what I am doing wrong here.

    Method 1:

    Add-PSSnapin microsoft.sharepoint.powershell
    $Sites=Get-SPWebApplication | Get-SPSite
    ForEach($site in $sites) {Write-Host $Site| Export-Csv -LiteralPath e:\test.csv -Append}


    Method 2:

    Add-PSSnapin microsoft.sharepoint.powershell
    $results=ForEach($site in $(Get-SPWebApplication | Get-SPSite)) {Write-Host $Site}
    $results= Out-File e:\test.csv

    Thanks in advance for help.


    Monday, January 8, 2018 10:17 PM

Answers

  • You cannot use Out-String to create a CSV,

    Get-SPWebApplication | Get-SPSite | Select Name, <... other properties> | Export-Csv filename.csv

    start by reading the entire help for all of these CmdLets.

    Here is a good p[lace to start learning PS: Learn PowerShell  


    \_(ツ)_/

    • Proposed as answer by BOfH-666 Tuesday, January 9, 2018 12:21 AM
    • Marked as answer by UmrG Tuesday, January 9, 2018 3:18 PM
    • Unmarked as answer by UmrG Tuesday, January 9, 2018 3:24 PM
    • Marked as answer by Richard MuellerMVP Tuesday, January 16, 2018 9:36 AM
    Monday, January 8, 2018 10:56 PM

All replies

  • On Method 1: Use

    Write-Output instead of Write-Host

    On Method 2:

    $results | Out-String | Out-File e:\test.csv

    $results | Out-File e:\test.csv

    • Marked as answer by UmrG Tuesday, January 9, 2018 3:20 PM
    • Unmarked as answer by UmrG Tuesday, January 9, 2018 3:20 PM
    Monday, January 8, 2018 10:48 PM
  • You cannot use Out-String to create a CSV,

    Get-SPWebApplication | Get-SPSite | Select Name, <... other properties> | Export-Csv filename.csv

    start by reading the entire help for all of these CmdLets.

    Here is a good p[lace to start learning PS: Learn PowerShell  


    \_(ツ)_/

    • Proposed as answer by BOfH-666 Tuesday, January 9, 2018 12:21 AM
    • Marked as answer by UmrG Tuesday, January 9, 2018 3:18 PM
    • Unmarked as answer by UmrG Tuesday, January 9, 2018 3:24 PM
    • Marked as answer by Richard MuellerMVP Tuesday, January 16, 2018 9:36 AM
    Monday, January 8, 2018 10:56 PM
  • Thanks jrv , 

    I was looking more some thing with "Foreach()" or "Foreach-Object " and export out put of that, but thanks for your reply it was helpful.



    • Marked as answer by UmrG Tuesday, January 9, 2018 3:19 PM
    • Unmarked as answer by UmrG Tuesday, January 9, 2018 3:20 PM
    • Edited by UmrG Tuesday, January 9, 2018 3:25 PM
    Tuesday, January 9, 2018 3:19 PM
  • Thanks Naw
    Tuesday, January 9, 2018 3:28 PM