1

UNC共有のリストをping応答時間で並べ替えるスクリプトを作成しようとしています。私はなんとかハックのように感じる何かを思いついたのですが、純粋に「PowerShell精神」でそれを行う方法について誰かがもっと良いアイデアを持っているかどうか疑問に思っていますか?

これは私の醜い解決策です:

$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

2 に答える 2

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 }

オブジェクトにデータを追加する場合は、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}}

これにより、複数のオブジェクトを組み合わせているため、大幅に異なる出力を得ることができます...

于 2011-01-17T15:09:21.767 に答える
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]}}
于 2011-01-17T03:30:45.637 に答える