Data for comparisons

A question on the forum asked about storing data used in comparisons, The example was based on a list if IP addresses where some were known to be good and the questioner wanted to filter out the known good ones so he just had to investigate the rest.

You could put the data in your script

Remove-Item -Path C:\TestScripts\unknownip.txt -Force
$safe = ‘127.0.0.1’,
‘10.10.54.199’,
‘10.10.54.200’,
‘192.168.0.1’

$ips = ‘127.0.0.1’, ‘10.10.54.199’, ‘172.16.5.1’, ‘192.168.0.47’, ‘10.10.54.200’

foreach ($ip in $ips){
if ($ip -notin $safe) {
   Out-File -InputObject $ip -FilePath C:\TestScripts\unknownip.txt -Append
}
}

cat C:\TestScripts\unknownip.txt

The advantage is that you only maintain one file. The disadvantage come sif you want to use the data in another script.

Another approach is to put the data in  a file

127.0.0.1
10.10.54.199
10.10.54.200
192.168.0.1

I saved it as safeips.txt

The script changes to

Remove-Item -Path C:\TestScripts\unknownip.txt -Force
$safe = Get-Content -Path C:\TestScripts\safeips.txt

$ips = ‘127.0.0.1’, ‘10.10.54.199’, ‘172.16.5.1’, ‘192.168.0.47’, ‘10.10.54.200’

foreach ($ip in $ips){
if ($ip -notin $safe) {
   Out-File -InputObject $ip -FilePath C:\TestScripts\unknownip.txt -Append
}
}

cat C:\TestScripts\unknownip.txt

In production you’d obviously read the IPs to test from a file of some kind rather than hard code in the script.

The second approach involves maintaining 2 files but gives greater flexibility – its the approach I prefer

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s