Foreach Output to CSV

Hi developer,

I have a written a script but i have no idea how to the foreach output loop to csv file.

Script is below:

$regex = "([A-Za-z])\w+|\d+"
$matchInfo = @((Get-Content \test.txt) |Select-String -Pattern  $regex -AllMatches))

$output = foreach($minfo in $matchInfo)
{
    foreach($match in @($minfo.Matches | Foreach {$_.Groups[0].value}))
    {
        Write-host -NoNewline "$match,"
    }
    Write-Host ""
}

$output | ???????

I tried this:
$output | Out-File -FilePath Test.csv -Encoding OEM

So i opened the Test.csv and no data. it is empty.

Any Idea?
Thanks




  • Edited by IamGuy84 21 hours 38 minutes ago
May 20th, 2015 3:46am

Hi,

do you get any console output from the Write-Host when the script is running?

I have no idea why your code is not running.

Try this:

$regex = .......
$matchInfo = @((Get-Content \.text.txt) |Select-String -Pattern  $regex -AllMatches))

foreach($minfo in $matchInfo)
{
    foreach($match in @($minfo.Matches | Foreach {$_.Groups[0].value}))
    {
        "$match," | Out-File -FilePath Test.csv -Encoding OEM -Append
    }
    "" | Out-File -FilePath Test.csv -Encoding OEM -Append
}


Free Windows Admin Tool Kit Click here and download it now
May 20th, 2015 5:33am

Here is my sample complete Script:

$regex = "([A-Za-z])\w+|\d+"
$matchInfo = @(Get-Content .\test.txt|Select-String -Pattern  $regex -AllMatches)

$output= foreach($minfo in $matchInfo)
{
    foreach($match in @($minfo.Matches | Foreach {$_.Groups[0].value}))
    {
        Write-host -NoNewline "$match,"
    }
    Write-Host ""
}
Where test.txt:
aa bb cc 12
cc dd ee 13
ff gg hh 15
ii jj kk 22
ll mm nn 56

Output in powershell command:
aa,bb,cc,12,
cc,dd,ee,13,
ff,gg,hh,15,
ii,jj,kk,22,
ll,mm,nn,56,

i tried this as below are not working:
$Output | out-file -FilePath test.csv -Encoding OEM
$Output | out-file -FilePath test.txt
$Output | out-gridview

May 20th, 2015 6:05am

When you use the command Write-Host,it does only write the text on the shell console... And the variable $output is $null !

You must store the result in the variable before displaying and saving it. 

Below a very simple example:

 

# Store the result in a variable.

$output= foreach($i in 1..20)

{

    "value $i";

}

 

# Display the result in the "Shell Console"

$output

 

# Store the result in a text file.

$output | Out-File C:\output.txt 

Free Windows Admin Tool Kit Click here and download it now
May 20th, 2015 9:05am

How to avoid no new line without write-host?

For example:
value 1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9

To
value 1 value 2 value 3 value 4 value 5 value 6 value 7 value 8 value 9

  • Edited by IamGuy84 2 hours 18 minutes ago
May 21st, 2015 12:47am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics