Selecting Strings to be used in ForEach-Object

烈酒焚心 提交于 2019-12-11 05:21:56

问题


So far I have this:

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

I want to be able to select the string after All User Profile : and put it into an array, but it is only selecting a single letter. How do I select the strings instead? I want each array to be a different string, and there doesn't have to be 8 there can be more or less.


回答1:


You are right to use the $matches variable.

$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
}



回答2:


Split the selected string at ": ". (Note the space.) Then you get the profile name as the value of an array element.

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

Here's one way to think about how to extract the profile.

# 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


来源:https://stackoverflow.com/questions/45244903/selecting-strings-to-be-used-in-foreach-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!