2011-01-16 5 views
1

私は、UNC共有のリストにそれらのping応答時間を指定するスクリプトを作成しようとしています。 私は、ハックのようなものを思いつきました。純粋に「パワーシェルの精神」で誰かがそれをどうやってやっているのか、誰かが分かりましたか?Powershell - ping応答時間でUNCパスを並べ替える方法

これは私の醜いソリューションです:

$shares = Get-Content unc_shares.txt | where {Test-Path $_} 
$servers = $shares | ForEach-Object {$_.Substring(2, $_.IndexOf("\", 3) - 2)} 

$sortedServers = ($servers | 
    ForEach-Object -Process {(Get-WmiObject Win32_PingStatus -filter "Address='$_'")} | 
    sort ResponseTime | 
    select Address) 

foreach($server in $sortedServers) 
{ 
    $shares | where {$_.Contains($server.Address)} | Out-File $sortedListPath -append 
} 

答えて

4

ソートする場合は、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 } 

それはあなたがオブジェクトにデータを追加したいとき、あなたは追加-メンバーを使用する必要があることは事実です。この場合、NotePropertyにpingの結果を追加することができますが、が実際に pingを実行する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 

を-メンバーを追加する代わりに(あなたが行うとき、 、あなたはpingのオブジェクトを作成することができますので、セレクト・オブジェクトを使用してオブジェクトを構築して、そのようにそれに戻って共有名を追加することができます)再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}} 

あなたができること大幅に異なるあなたが複数のオブジェクトを一緒に組み合わせているので、レンタル出力...

0

ここで「折りたたまれた」ワンライナーです:

@(foreach ($unc in $list){ 
     test-connection $unc.split("\")[2] | 
     measure responsetime -average | 
     % {$_.average.tostring() + " $unc"}}) | 
     sort |% {$_.split()[1]} 

あなたがResponseTimesを保存し、表示したい場合は、との最後の行に置き換えます。

sort | select @{l="Share";e={$_.split()[1]}},@{l="ResponseTime";e={"{0:F2}" -f $_.split()[0]}} 
+0

残念ながら、これはトリックをしていないようです。それは、各共有のためのレスポンスタイムをうまく計算します(splitを使用してサーバ名を取得するのは良い考えです!)が、まだ入力リストに入力された順番でuncパスを返します。 – Newanja

+0

あなたに何を伝えるべきか分からない。このテストデータを実行します:$ list = "\\ www.google.com \ stuff \ otherstuff"、 "\\ www.stackoverflow.com \ knowlege"、 "\\ localhost \ test"並べ替えと再実行、すべてが逆の順序で出てきます。 – mjolinor

+0

入力リストの並び順を変えようとしましたが、出力順は同じです。あなたが記述した結果を再作成することはできません。 – mjolinor

関連する問題