Home > database >  export in csv when for each in powershell
export in csv when for each in powershell

Time:12-10

I m starting with Powershell and i dont arrive to export in csv with my loop foreach.

With help i have a fonctionnal script without export csv :(

$computers= Get-ADComputer -Filter  * -Properties * | Select Description  
foreach($computer in $computers)
{
    if ($computer.Description -ne $null)
    {
        $descriptions = $computer.Description -split "\(" 
        # Write-Host $descriptions
        $accountname = $descriptions[0]
        $pcinfos = $descriptions[1] -split ";"
        $serial = $pcinfos[0]
        Write-Host "$accountname;$serial" 
    }
}

#| Export-Csv -Encoding UTF8 -Delimiter "," -Path "**********\exportaddesciption.csv" -NoTypeInformation

Can you help me please ?

Thks

CodePudding user response:

Use the ForEach-Object and Where-Object cmdlets, and make sure you create an object with two properties instead of attempting to construct the CSV row manually:

$computers |Where-Object { -not [string]::IsNullOrEmpty($_.Description) } |ForEach-Object { 
    $descriptions = $computer.Description -split "\(" 
    $accountname = $descriptions[0]
    $pcinfos = $descriptions[1] -split ";"
    $serial = $pcinfos[0]

    [pscustomobject]@{
        AccountName = $accountname
        Serial      = $serial
    }
} |Export-Csv -Encoding UTF8 -Delimiter ";" -Path "**********\exportaddesciption.csv" -NoTypeInformation

CodePudding user response:

You have a few problems. Your answer will be like the following. I took the liberty of making your code like I learned reading and asking here. Good luck!

$computers = Get-ADComputer -Filter  * -Properties * | Select-Object Description

$result = $computers | ForEach-Object {
    if ($null -ne $computer.Description) {
        $descriptions = $computer.Description -split "\(" 
        # Write-Host $descriptions
        $accountname = $descriptions[0]
        $pcinfos = $descriptions[1] -split ";"
        $serial = $pcinfos[0]
        Write-Host "$accountname;$serial" 
        [PSCustomObject]@{
            Name = (Enter what you want to export here with variable name)
        }
    }
}
$result | Export-Csv (Path to report in quotes) -NoTypeInformation

Look carefully at the other answer you get some expanded answers I did not provide.

CodePudding user response:

Thks for you answers !!

I know pratice it's the way but not in one day :p

it's an hard way ^^

i'm learning all day

Thks

  • Related