I am new to powershell scripts and not sure how to achieve the below:
$finalArray = #()
$tempArray0 = 'A'
$tempArray1 = 'B'
$tempArray2 = 'C'
FOR (i=0; i -eq 5; i++) {$finalArray += $tempArray[i]}
$finalArray
Output Should be:
A
B
C
If the variable name is itself variable, you'll have to use the Get-Variable cmdlet to retrieve its value:
$finalArray = #()
$tempArray0 = 'A'
$tempArray1 = 'B'
$tempArray2 = 'C'
for($i=0; $i -le 2; $i++) {
$finalArray += (Get-Variable "temparray$i" -ValueOnly)
}
$finalArray
If you want to create variables with variable names, use the New-Variable cmdlet:
$Values = 'A','B','C'
for($i = 0; $i -lt $Values.Count; $i++){
New-Variable -Name "tempvalue$i" -Value $Values[$i]
}
which would result in:
PS C:\> $tempvalue1
B
Although the above will solve the example you've presented, I can think of very few cases where you wouldn't be better of using a [hashtable] instead of variable variable names - they're usually an over-complication, and you'll end up with unnecessary code anyways because you need to calculate the variable names at least twice (during creation and again when reading the value).
From the comments, it sounds like you're trying to generate input for a password generator. This can be simplified grossly, without resorting to variable variable names:
# Create a hashtable and generate the characters
$CharArrays = #{
Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
Numbers = 0..9
}
# Generate some letters for the password
$PasswordChars = $CharArrays['Letters'] |Get-Random -Count 10
# Generate a few digits
$PasswordChars += $CharArrays['Numbers'] |Get-Random -Count 4
# Shuffle them around a bit
$PasswordChars = $PasswordChars |Sort-Object {Get-Random}
# Create your password
$Password = $PasswordChars -join ''
Related
I have created a GUI with 5 Textboxes. I call them $textboxHost1 - 5.
Now I have an array in which I'm gonna save up to 5 values and then write each value according to the order into the textboxes. The first value in the array should be written into the first $textboxHost1 box.
To do that, I would like to make a for loop and have written this code
#$hostnameneingabe: Array, in which the values are saved.
$hostnameneingabeCount = $hostnameneingabe.Count
for($i = 0; $i -le $hostnameneingabeCount; $i++) {
#code here
}
Now, I'm looking for a way to go down the order, so that the first $textboxHost1 comes firstly and so on.
To be accurate, the variable $textboxHost should be incrementally increased in the loop and the values at the position $i in the array should be written into that textbox.
sth like
for($i = 0; $i -le $hostnameneingabeCount; $i++) {
$textboxHost$i =
}
I suppose you would be liking something like this?
$textboxHosts = Get-Variable | ? {$_.Name -match "textBoxHost[0-9]" -and $_.Value -ne $null} | sort Name
After this you can process that var with eg. a foreach:
foreach ($textboxHost in $textboxHosts) {<# Do some stuff #>}
You have to use an array, because otherwise you can't loop through them:
$textboxHost = #(0..4)
#Textbox 0
$textboxHost[0] = New-Object System.Windows.Forms.TextBox
$textboxHost[0].Text = "test"
#Textbox 1
$textboxHost[1] = New-Object System.Windows.Forms.TextBox
$textboxHost[1].Text = "test"
foreach ($textbox in $textboxHost){
#Do whatever you want with the textbox
$textbox =
}
How can I use Powershell to choose a random letter based on the given count and dynamically assign each to a unique variable?
I have this below code, but I am not sure how to go about doing the above, any ideas, please?
$Count =3
$a = Get-Random -InputObject 'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n' -Count $Count
I expect the output of each letters to be stored in 3 different variables like Ar1, Ar2 and Ar3 ( and so on Arn if the $Count = n)
If you truly need distinct variables ($Ar1, $Ar2, ... $Ar<n>), here's the most concise solution:
$iref = [ref] 1
$Count = 3
Get-Random -InputObject ([char[]] (([char] 'a')..([char] 'n'))) -Count $Count |
New-Variable -Force -Name { 'Ar' + $iref.Value++ }
Note: ([char[]] (([char] 'a')..([char] 'n'))) is short for
'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n'.
In PowerShell Core, you could simply use ('a'..'n').
Also note how the -Name argument - the name of the variable to create - is calculated dynamically, via a script block.
In this so-called delay-bind usage of a script block, it runs in a child variable scope, hence the need to use a [ref] instance to refer to the sequence number $iref in the caller's scope.
By contrast, script blocks you pass to the ForEach-Object and Where-Object cmdlets run directly in the caller's scope.
This surprising discrepancy is discussed in this GitHub issue.
try Something like this
$Count =3
$a = Get-Random -InputObject 'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n' -Count $Count
for ($i = 0; $i -lt $a.Count; $i++)
{
#Traitment with element in $i posoition
$Current=$a[$i]
#use $Current for your traitment
$Current
}
Firts of all, I agree with Lee_Dailey that creating variables like this is NOT a good idea..
However, it can be done like so:
$Count = 3
$a = Get-Random -InputObject 'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n' -Count $Count
for ($i = 0; $i -lt $a.Count; $i++) {
$varname = "Ar$($i + 1)"
Remove-Variable $varname -ErrorAction SilentlyContinue
New-Variable -Name $varname -Value $a[$i]
}
Note that for this to work, you must first remove the possible
already existing variable with that name, which can lead to unforeseen
problems in the rest of your code.
To see what is created, you can use Get-Variable 'Ar*' which will display something like this:
Name Value
---- -----
Ar1 m
Ar2 d
Ar3 j
args {}
i'm new around here but I manage to create a script that returns a random char from a list of characters, if want to return multiple characters you can also select more values from it. the Get-Random built-in function from powershell makes it a lot easier
$select = 1
$Mood = Get-Random -InputObject 'b', 'd','g','p','s','y' -Count $select
Write-Output $Mood
I am new to powershell. I am stuck with a problem, can you please help me out?
I have the following:
$firstname = #("Harris", "Robin", "Jack", "Ryan")
$lastname = #("Brown", "Amber", "Layton", "Hatvani")
from this 2 array I have to create a password and the criteria is take the first letter from first and lastname then 5 random numbers with them. example: hb69248 (in this case h is the first letter of Harris, b is the first letter of Brown). This has to be done for each of the names. I tried the following:
[string]$p = for ($i=0; $i -lt $firstname.count; $i++)
{ $firstname[$i].substring(0,1)}
[string]$n = for ($r=0; $r -lt 4; $r++)
{ get-random -minimum 0 -maximum 9)
$password = "$p", "$n" -join ""
The output should be like HRJR2876 (the numbers are creating randomly). But I am getting H R J R2 8 7 6. can you guys tell me why I am having the space in between them??in this case I just worked with the firstname not with the last name
When you cast an array to a string (like you do $p and $n), PowerShell uses the output field separator - represented by the $OFS automatic variable - as a delimiter. $OFS defaults to a space.
You can produce the passwords in a single loop, like this:
$passwords = for($i = 0; $i -lt $firstname.Length; $i++){
$first = $firstname[$i].Substring(0,1)
$last = $lastname[$i].Substring(0,1)
$number = Get-Random -Min 10000 -Max 100000
$first,$last,$number -join ''
}
$passwords is now an array of all 4 new passwords
What I'm trying to do is create array variable names dynamically, and then with a loop, add the object to its relevant array based on the hash table value being equal to the counter variable.
$hshSite = #{} # Values like this CO,1 NE,2 IA,3
$counter = $hshSite.count
For($i = $counter; $i -gt 0; $i--) {
New-Variable -Name "arr$i" -Value #()
}
If $counter = 3, I would create arrays $arr1, $arr2, $arr3
$csv = Import-CSV....
ForEach ($x in $csv) {
#if $hshSite.Name = $x.location (ie CO), look up hash value (1),
and add the object to $arr1. If $hshSite.Name = NE, add to $arr2
I tried creating the dynamic arrays with New-Variable, but having issues trying to add to those arrays. Is it possible to concatenate 2 variables names into a single variable name? So taking $arr + $i to form $arr1 and $arr2 and $arr3, and then I can essentially just do $arr0 += $_
The end goal is to group things based on CO, NE, IA for further sorting/grouping/processing. And I'm open to other ideas of getting this accomplished. Thanks for your help!
Just make your hash table values the arrays, and accumulate the values to them directly:
$Sites = 'CO','NE','IA'
$hshSite = #{}
Foreach ($Site in $Sites){$hshSite[$Site] = #()}
ForEach ($x in $csv)
{
$hshSite[$x.location] += <whatever it is your adding>
}
If there's a lot of entries in the csv, you might consider creating those values as arraylists instead of arrays.
$Sites = 'CO','NE','IA'
$hshSite = #{}
Foreach ($Site in $Sites){ $hshSite[$Site] = New-Object Collections.Arraylist }
ForEach ($x in $csv)
{
$hshSite[$x.location].add('<whatever it is your adding>') > $nul
}
You could quite easily do add items to a dynamically named array variable using the Get-Variable cmdlet. Similar to the following:
$MyArrayVariable123 = #()
$VariableNamePrefix = "MyArrayVariable"
$VariableNameNumber = "123"
$DynamicallyRetrievedVariable = Get-Variable -Name ($VariableNamePrefix + $VariableNameNumber)
$DynamicallyRetrievedVariable.Value += "added item"
After running the above code the $MyArrayVariable123 variable would be an array holding the single string added item.
I'm new to powershell and trying to get the length of a HashTable (to use in a for loop), but I can't seem to get the length of the HashTable to output anything.
$user = #{}
$user[0] = #{}
$user[0]["name"] = "bswinnerton"
$user[0]["car"] = "honda"
$user[1] = #{}
$user[1]["name"] = "jschmoe"
$user[1]["car"] = "mazda"
write-output $user.length #nothing outputs here
for ($i = 0; $i -lt $user.length; $i++)
{
#write-output $user[0]["name"]
}
#{} declares an HashTable whereas #() declares an Array
You can use
$user.count
to find the length of you HashTable.
If you do:
$user | get-member
you can see all the methods and properties of an object.
$user.gettype()
return the type of the object you have.
$user is a hash table, so you should user$user.count instead.
That's not an array but a hashtable. Use .count instead:
write-output $user.count