0

I am trying to write a script that would create and maintain a csv spreadsheet. It would be ran on a schedule and if if didn't find any .csv file it should create it from scratch.

This is the way I go about it:

# === Paths
$ipsFileLocation = "C:\stuff\ips.txt"
$dbLocation = "C:\stuff\db.csv"

# === Actual script starts here

Write-Host "Importing the CSV File..."
Try 
{ 
    $db = Import-Csv $dbLocation
} 
Catch [System.IO.FileNotFoundException] 
{ 
    Write-Host "The database file is not found! Creating a new one..."
    $db = @()
}

$ipList = get-content $ipsFileLocation

Update-Ips $db $ipList

Export-Csv -InputObject $db -Path $dbLocation -NoTypeInformation

# === Helper methods
function Update-Ips($db, $ips) 
{
    foreach ($ip in $ips)
    {   
        $foundRow = $db | Where { $_.IP -eq $ip } #check if the particular ip exists in database
        if ($foundRow -eq $null)
        {
            #no ip found in database -> Create new entry
            $newRecord = "" | select IP,Host,Responds,LastLogon
            $newRecord.IP = $ip
            $db += $newRecord
        }
    }
}

The ips.txt file is just a text file containing IP addresses, each in a new line.

The script runs, however the export-csv method leaves me with a .csv file that looks like this:

"Count","Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized" "0","0","0","1","System.Object[]","False","True","False"

Not quite what I imagined.

Also, right at the end I would expect the $db object to looks like this: desired result

Instead, I get something that doesn't look like a table at all:

result that i get

Could someone please tell me that am I doing wrong and what is the difference between my desired result and the result that I actually get from running my script?

3
  • Is that the entire script? i see a reference to $csv which would be empty if not populated somewhere else Commented Jul 19, 2014 at 14:09
  • Good catch Matt, thanks. Fixed now, but the problem persists and my question stands. Commented Jul 19, 2014 at 14:48
  • 1
    As far as what the output of $db looks like, well that's just list view verse table view. It doesn't affect anything other than how you see it in the console. Commented Jul 19, 2014 at 15:56

1 Answer 1

3

You're trying to export the array itself (-InputObject $db) to CSV. That's why you get the properties of the array (count etc.).

Replace

Export-Csv -InputObject $db -Path $dbLocation -NoTypeInformation

with

$db | Export-Csv -Path $dbLocation -NoTypeInformation
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.