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

Selecting Strings to be used in ForEach-Object

到目前为止我有这个:

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

我希望能够select All User Profile : 之后的字符串并将其放入一个数组中,但它只是select 一个字母。我如何 select 代替字符串?我希望每个数组都是一个不同的字符串,不一定是8个,可以多也可以少。

在“:”处拆分所选字符串。 (注意 space。)然后您将配置文件名称作为数组元素的值。

$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

您使用 $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
}