吐出随机命令问题的脚本[Powershell]

问题描述 投票:3回答:1
$k = get-command -all | measure | select-object count
$result = $k -replace "[{}@Count=]", ""
$rand = get-random -maximum $result
$minrand = $rand - 1
get-command -all -totalcount $rand | Select-Object -skip $minrand

这应该吐出一个命令,别名,cmdlet等等。我希望这对学习PowerShell有用。

问题是它一遍又一遍地吐出相同的命令。

powershell command cmdlet
1个回答
1
投票

你的代码非常复杂。你可以这样做:

$Commands = Get-Command -All

然后继续运行:

Get-Random $Commands

每次都要获得一个随机的不同命令。


关于你的代码,你不需要这样做(这会返回一个字符串结果):

$k = get-command -all | measure | select-object count
$result = $k -replace "[{}@Count=]", ""

你应该做这样的事情:

$k = get-command -all | measure | select-object count
$result = $k.count

通过它您可以访问$k的count属性并获取其整数值。

PowerShell返回具有属性的对象,因此当您经常在控制台中看到基于字符串的结果时,当您想要操作这些结果时,您应该使用对象属性。将对象管道化为Get-Member是发现对象属性(以及方法等)的好方法。例如尝试:

$k | Get-Member

要查看其属性。

Get-HelpGet-CommandGet-Member是从shell中发现和学习PowerShell的3个最有用的工具。

© www.soinside.com 2019 - 2024. All rights reserved.