Answer the question
In order to leave comments, you need to log in
Random list generation in Powershell?
Good afternoon.
I am just starting to learn Powershell. Until now, there was not much experience in programming, so it is tight. Perhaps someone can come up with the right idea. I will be very grateful!
The essence is that: The
list of computers is given. I need to display:
1. the number of computers in the list (for example: 10)
2. the number of computers in the new list (for example: 5)
3. a random list of computer names (names of 5 computers)
I don’t fully understand what I am writing in the script, but for now fulfilled the first condition. The script looks like this:
$ComputerList = "PC1, PC2, PC3, PC4, PC5, PC6, PC7, PC8, PC9, PC10"
$AllComputer = $computerList.Split(",")
Write-Host -ForegroundColor Magenta "Количество компьютеров:" $AllComputer.Length
$newList = @()
for ($i =0; $i -eq 4; $i++) {
$index = Get-Random -Maximum $AllComputer.Length
$newList[$i] = $ComputerList[$index]
}
Write-Host -ForegroundColor Green "Количество новых компьютеров:" $newList.Length
Write-Host -ForegroundColor Red "Список новых компьютеров:" $newList
Answer the question
In order to leave comments, you need to log in
$ComputerList = "PC1, PC2, PC3, PC4, PC5, PC6, PC7, PC8, PC9, PC10"
$AllComputer = $computerList.Split(",")
Write-Host -ForegroundColor Magenta "Number of computers:" $AllComputer. Length
$newList = @()
# for ($i =0; $i -eq 4; $i++) { "-eq" is a condition for executing the contents of the loop; "0=4" - False
for ($i =0; $i -le 4; $i++) {
$index = Get-Random -Maximum $AllComputer.Length
# $newList[$i] = $ComputerList[$index] - adding to the list at a non-existent index (initially the list is empty), $ComputerList is not a list, but a string that you convert to a list (line 2) and add to the variable $AllComputer
$newList += $AllComputer[$index]
}
Write-Host -ForegroundColor Green "Number of new computers:" $newList.Length
Write-Host -ForegroundColor Red "List of new computers:" $newList
Considering that this is still powershell, and not basic, I would write like this:
# Сразу используем массив, а не строку - можно обойтись без деления на части
$ComputerList = "PC1", "PC2", "PC3", "PC4", "PC5", "PC6", "PC7", "PC8", "PC9", "PC10"
Write-Host -ForegroundColor Magenta "Количество компьютеров:" $ComputerList.Length
# Get-Random Умеет сам выбирать нужное количество элементов, поданных на вход
# к тому же он выдаёт гарантированно неповторяющиеся элементы, ваш вариант потенциально может выдать, например, два пятых компа
$NewList = $ComputerList | Get-Random -Count 5
Write-Host -ForegroundColor Green "Количество новых компьютеров:" $newList.Length
Write-Host -ForegroundColor Red "Список новых компьютеров:" $newList
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question