T
T
The0dium2020-03-24 19:02:42
PowerShell
The0dium, 2020-03-24 19:02:42

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

2 answer(s)
V
Vitaly Gatin, 2020-03-25
@The0dium

$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

M
MaxKozlov, 2020-03-25
@MaxKozlov

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 question

Ask a Question

731 491 924 answers to any question