PowerShell for Windows Admins

Jul 21 2015   2:54PM GMT

Data for comparisons

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: