Saving Persistent Data

by Feb 25, 2016

Sometimes a script needs to save information in a persistent way. Maybe you have a list of computers that you'd want to contact, but only some are online. Then your script should report which computers could be contacted, so when you run the script later again, these computers can be skipped.

CSV files are a perfect way for this. Let's create a simple CSV file like this:

$data = @'
ComputerName, Status, Date,,

$Path = "$env:temp\network.csv"
$data | Set-Content -Path $Path

Next, a script should try and ping the computers in this list, but only if they did not respond before. Here is how a script can update the CSV accordingly:

#requires -Version 2
(Import-CSV -Path $Path) |
ForEach-Object {
    $pc = $_.ComputerName

    if ($_.Status -ne $true)
        Write-Warning "Checking $PC..."
        $_.Status = Test-Connection -Count 1 -ComputerName $pc -ErrorAction SilentlyContinue -Quiet
        $_.Date = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
        Write-Warning "Skipping $PC..."
} | Export-CSV -Path $Path -Encoding UTF8 -NoTypeInformation

When you run the script, it tries to contact all computers in the CSV list. If it can contact a computer, this is reported back to the CSV list. So if you run the script a second time, it will only try and contact the remaining computers that did not answer before.

Twitter This Tip! ReTweet this Tip!