I want to add a column and a value to an existing array generated from a CSV.
This is my code:
$mycsv = "C:\Users\test\Documents\serveurs.csv"
$servers = Import-Csv $mycsv
This is the result:
ServerName Ip ---------- -- Castor 172.22.0.64 Pollux 172.22.0.67
I want to add new column with value for each ServerName, like this:
ServerName Ip Available ---------- -- --------- Castor 172.22.0.64 Yes Pollux 172.22.0.67 No
I tried the code below:
$item = New-Object PSObject
$item | Add-Member -Type NoteProperty -Name 'Available' -Value 'Yes'
$servers += $item
But it's actually not working, can anyone help me?
The final idea is to have value assigned if the server is reachable or not over the network, using Test-Connection
cmdlet.
You could use a calculated property for determining the availability of each server:
$csv1 = 'C:\Users\test\Documents\serveurs.csv'
$csv2 = 'C:\Users\test\Documents\serveurs2.csv'
Import-Csv $csv1 |
Select-Object ServerName, Ip,
@{n='Available';e={[bool](Test-Connection -Count 1 $_.Ip 2>$null)}} |
Export-Csv $csv2 -NoType
Note, however, that even when limiting the test to a single probe per server this may take some time, since all items are processed sequentially. If you have a lot of servers to test, you may want to run the checks as parallel jobs:
$csv = 'C:\Users\test\Documents\serveurs.csv'
$servers = Import-Csv $csv
# clear job queue
Remove-Job *
# load job queue with test jobs
$servers | ForEach-Object {
Start-Job -ScriptBlock {
$args[0]
[bool](Test-Connection -Count 1 $args[0] 2>$null)
} -ArgumentList $_.Ip
}
# wait for jobs to finish
do {
Start-Sleep -Milliseconds 100
} while (Get-Job -State 'Running')
# gather job results into hashtable
$availability = @{}
Get-Job | ForEach-Object {
$result = Receive-Job -Id $_.Id
$availability[$result[0]] = $result[1]
Remove-Job -Id $_.Id
}
# add availability column to server data and export back to CSV
$servers |
Select-Object ServerName, Ip, @{n='Available';e={$availability[$_.Ip]}} |
Export-Csv $csv -NoType
Populating the field value aside, another option for getting the property added is to use Select-Object.
$csv = 'C:\Users\test\Documents\serveurs.csv'
$servers = Import-Csv $csv | select *,Availability
Then populate availability however you choose.
If you're going to use background jobs to multithread I think you'd be better off breaking the server names up into groups and setting a background job to work on each group. It takes about 5 seconds to set up and tear down a background job, and using them for trivial tasks like pinging a single computer can be counter-productive.
It's more work to code, but if you want to multi-thread that I think a runspace pool would produce results much faster than background jobs in this application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With