选择要在ForEach-Object中使用的字符串

时间:2017-07-21 18:56:20

标签: powershell netsh wlan

到目前为止,我有这个:

netsh wlan show profiles | Select-String '^    All User Profile     : (.*)' | ForEach-Object {
  $array +=
  $_.Matches[0].Groups[1].Value
}
$array[0]
$array[1]
$array[2]
$array[3]
$array[4]
$array[5]
$array[6]
$array[7]
$array[8]
pause

我希望能够在All User Profile :之后选择字符串并将其放入数组中,但它只选择一个字母。如何选择字符串呢?我希望每个数组都是一个不同的字符串,并且不必是8,可以有更多或更少。

2 个答案:

答案 0 :(得分:2)

将所选字符串拆分为":"。 (注意空格。)然后,您将配置文件名称作为数组元素的值。

$array = @()
netsh wlan show profiles | Select-String '^    All User Profile     : (.*)' | `
ForEach-Object `
-Process {
  $profile = ($_ -split ": ")[1]
  $array += $profile
} `
-End {$array}

这是考虑如何提取个人资料的一种方法。

# A full string from netsh wlan show profiles
"    All User Profile     : WibbleCoffeeWiFi"

# Split it, and return the first element. There are leading and trailing spaces.
("    All User Profile     : WibbleCoffeeWiFi" -split ': ')[0] #     All User Profile     

# Split it, and return the second element.
("    All User Profile     : WibbleCoffeeWiFi" -split ': ')[1] #WibbleCoffeeWiFi

# Split it, and return the last element. Same as the second element in this case.
("    All User Profile     : WibbleCoffeeWiFi" -split ': ')[-1] #WibbleCoffeeWiFi

答案 1 :(得分:1)

您使用$ matches变量是正确的。

$array = netsh wlan show profiles |
    ForEach-Object {
        if ($_ -match "\s*All User Profile\s*:\s*(.*)") { $($matches[1]) }
    }
$array

foreach ($wn in $array) {
    netsh wlan show profile name=$wn
}
相关问题