Powershell - 如何按 ping 响应时间对 UNC 路径进行排序
我正在尝试编写一个脚本,给出 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
}
I'm trying to make a script that would given a list of UNC shares order them by their ping response time.
I've managed to come up with something that feels quite like a hack and I'm wondering if anyone has any better idea how to do it purely in "powershell spirit"?
This is my ugly solution:
$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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您只想排序时,只需使用 ScriptBlock 来排序:
或者,您可以使用平均值:
确实,当您想要向对象添加数据时,您应该使用 Add-Member。在这种情况下,您可以添加一个包含 ping 结果的
NoteProperty
,但更有趣的是添加名为 ping 的脚本属性(或方法),该属性将实际执行 ping 。也就是说,当您调用 ping 成员时,它将执行 ping:您也可以通过此方法使用平均值:
作为 Add-Member 的替代方案(当您不想每次都重新 ping 时),您可以建立使用 Select-Object 对象,因此您可以创建一个 Ping 对象,然后将共享名称添加回其中,如下所示:
这允许您获得截然不同的输出,因为您将多个对象组合在一起......
When all you want to do is sort, just use a ScriptBlock to sort by:
Or, you could use an average:
It's true that when you want to add data to an object, you should use Add-Member. In this case, you could add a
NoteProperty
with the result of the ping, but it's more interesting to add script property (or method) called ping that would actually execute the ping. That is, it will do the ping when you call the ping member:You can use the average with this method too:
As an alternative to Add-Member (when you do NOT want to re-ping every time), you can build up objects using Select-Object, so you could create a Ping object, and then add the Share name back to it like so:
That allows you to have drastically different output because you're combining multiple objects together...
这是一个“折叠”的单行:
如果您想保存并显示响应时间,请将最后一行替换为:
Here's a "folded" one-liner:
If you want to save and display the ResponseTimes, replace that last line with: