将多个字符串命令组合成一行
Combining Multiple String Commands Into One Line
我正在使用 PowerShell 和 运行 一种工具来提取 Lenovo 硬件 RAID 控制器信息以识别控制器编号,以便稍后在另一个命令行中使用(这是 SCCM 服务器构建任务序列的一部分) .该工具输出大量数据,我正试图从输出中分离出我需要的数据。
我已经能够分离出我需要的东西,但我认为必须有一种更有效的方法来寻找优化。关于使用字符串,我仍在学习中。
我正在寻找的工具的行输出如下所示:
0 0 0 252:0 17 DRIVE Onln N 557.861 GB dsbl N N dflt -
我正在尝试获取 :0 左侧的 3 个字符(252,但在其他型号上可能是 65 或其他一些 2 位或 3 位数字)
我现有的代码是:
$ControllerInfo = cmd /c '<path>\storcli64.exe /c0 show'
$forEach ($line in $ControllerInfo) {
if ($line -like '*:0 *') {
$ControllerNum = $line.split(':')[0] # Get everything left of :
$ControllerNum = $ControllerNum.Substring($ControllerNum.Length -3) # Get last 3 chars of string
$ControllerNum = $ControllerNum.Replace(' ', '') # Remove blanks
Write-Host $ControllerNum
break #stop looping through output
}
}
上面的方法有效,但我想知道是否有一种方法可以将以 $ControllerNum = 开头的三行组合起来,这样我就可以只用一个 $ControllerNum = (commands) 行来设置变量,而不用做它分 3 行。基本上想将 Split、Substring 和 Replace 命令组合成一行。
谢谢!
如果您只想要第一个 :
之前的最后一个数字,没有任何空格,您可以使用一个或两个正则表达式来实现:
$line -replace '^.*\b(\d+):.*$',''
正则表达式解释:
^ # start of string
.* # any number of any characters
\b # word boundary
( # start capture group
\d+ # 1 or more strings
) # end capture group
: # a literal colon (:)
.* # any number of any characters
$ # end of string
替换:
# Value captured in the capture group above
还有一个选项:
$ControllerNum = ([regex]'(\d{2,3}):0').Match($line).Groups[1].Value
用于您的示例0 0 0 252:0 17 DRIVE Onln N 557.861 GB dsbl N N dflt -
$ControllerNum 中的结果将是 252
我正在使用 PowerShell 和 运行 一种工具来提取 Lenovo 硬件 RAID 控制器信息以识别控制器编号,以便稍后在另一个命令行中使用(这是 SCCM 服务器构建任务序列的一部分) .该工具输出大量数据,我正试图从输出中分离出我需要的数据。
我已经能够分离出我需要的东西,但我认为必须有一种更有效的方法来寻找优化。关于使用字符串,我仍在学习中。
我正在寻找的工具的行输出如下所示:
0 0 0 252:0 17 DRIVE Onln N 557.861 GB dsbl N N dflt -
我正在尝试获取 :0 左侧的 3 个字符(252,但在其他型号上可能是 65 或其他一些 2 位或 3 位数字)
我现有的代码是:
$ControllerInfo = cmd /c '<path>\storcli64.exe /c0 show'
$forEach ($line in $ControllerInfo) {
if ($line -like '*:0 *') {
$ControllerNum = $line.split(':')[0] # Get everything left of :
$ControllerNum = $ControllerNum.Substring($ControllerNum.Length -3) # Get last 3 chars of string
$ControllerNum = $ControllerNum.Replace(' ', '') # Remove blanks
Write-Host $ControllerNum
break #stop looping through output
}
}
上面的方法有效,但我想知道是否有一种方法可以将以 $ControllerNum = 开头的三行组合起来,这样我就可以只用一个 $ControllerNum = (commands) 行来设置变量,而不用做它分 3 行。基本上想将 Split、Substring 和 Replace 命令组合成一行。
谢谢!
如果您只想要第一个 :
之前的最后一个数字,没有任何空格,您可以使用一个或两个正则表达式来实现:
$line -replace '^.*\b(\d+):.*$',''
正则表达式解释:
^ # start of string
.* # any number of any characters
\b # word boundary
( # start capture group
\d+ # 1 or more strings
) # end capture group
: # a literal colon (:)
.* # any number of any characters
$ # end of string
替换:
# Value captured in the capture group above
还有一个选项:
$ControllerNum = ([regex]'(\d{2,3}):0').Match($line).Groups[1].Value
用于您的示例0 0 0 252:0 17 DRIVE Onln N 557.861 GB dsbl N N dflt -
$ControllerNum 中的结果将是 252