並べ替えだけの場合は、ScriptBlockを使用して並べ替えます。
cat .\uncshares.txt | Sort { Test-Connection -Count 1 -CN $_.split('\')[2] }
または、平均を使用できます。
cat .\uncshares.txt | Sort { Test-Connection -Count 3 -CN $_.split('\')[2] | Measure ResponseTime -Average | Select -Expand Average }
オブジェクトにデータを追加する場合は、Add-Memberを使用する必要があるのは事実です。この場合、pingの結果にaを追加できますが、実際にpingを実行NoteProperty
するpingというスクリプトプロパティ(またはメソッド)を追加する方が興味深いです。つまり、pingメンバーを呼び出すとpingが実行されます。
$Shares = cat .\uncshares.txt | Add-Member ScriptProperty Ping -Passthru -Value {
Test-Connection $this.split('\')[2] -Count 1 |
Select -Expand ResponseTime }
# Each time you sort by it, it will re-ping, notice the delay:
$Shares | Sort Ping
この方法でも平均を使用できます。
$Shares = cat .\uncshares.txt | Add-Member ScriptProperty Ping -Passthru -Value {
(Test-Connection $this.split('\')[2] -Count 3 |
Measure ResponseTime -Average).Average }
# But this will take even longer:
$Shares | Sort Ping
Add-Memberの代わりに(毎回再pingを実行したくない場合)、Select-Objectを使用してオブジェクトを構築できるため、Pingオブジェクトを作成してから、そのように共有名を追加し直すことができます。 :
$unc = cat .\uncshares.txt
## Gotta love backslashes in regex. Not...
$unc -replace '\\\\([^\\]+)\\.*','$1' |
Test-Connection -Count 1 -CN {$_} |
Sort ResponseTime |
Select @{n='Server';e={$_.Address}},
@{n='Share'; e={$unc -match $_.Address}},
@{n='Ping'; e={$_.ResponseTime}}
これにより、複数のオブジェクトを組み合わせているため、大幅に異なる出力を得ることができます...