RJ96
RJ96

Reputation: 313

what bad consequence could using an array have 'in this situation'?

My question is two fold I'm playing around with PS and trying new stuff, I wrote a small script that generates full names by exporting first names from a txt.file and last names from another txt.file and finally randomly combines the 2 to create a full name, this is the script:

$Firstnames = Get-Content -Path 'C:\Users\user\Desktop\Firstname.txt'
$Lastnames = Get-Content -Path 'C:\Users\user\Desktop\Lastnames.txt'
$feminine = $firstnames | ?{$_ -like "*;frau"} | %{$_.Split(';')[0]}
Write-Host "Random full name generator"
$numberofNames = 1..(Read-Host 'how many combination do you want to generate?')
$numberofNames | foreach {
    $f = $feminine[ (Get-Random $feminine.count)]
    $l = $Lastnames[ (Get-Random $Lastnames.count)]
$full =  $f+" "+$l 

 Write-output $full  
 }

1- now $numberofNames is an array 'a range operator', I would like to know what bad consequences could use this method have? is this the best approach for the users input?

2- what is the key difference between using for example $a = 100 and $a = 1..100?

in case you need to know: $firstnames looks something like this:

 Linda;frau
 Aline;frau
 Lisa;frau
 Katja;frau
 Karen;frau

and $lastnames:

  smith
  anderson
  müller
  klein
  Rex

thank you

Upvotes: 0

Views: 46

Answers (1)

Moerwald
Moerwald

Reputation: 11304

1- now $numberofNames is an array 'a range operator', i would like to know what bad consequences could using this method have? is this the best approach for the users input?

It's valid. Even if the user adds e.g. a string as input Powershell will throw an error that it could not cast the input to an int:

 1 .. "test" | % {Write-Host $_ }
 Cannot convert value "test" to type "System.Int32". Error: "Input string was not in a correct format."
 At line:1 char:1
 + 1 .. "test" | % {Write-Host $_ }
 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
     + FullyQualifiedErrorId : InvalidCastFromStringToInteger

Even a neg. int shouldn't be a problem since you're not using the array content for any indexing operations.

2- what is the key difference between using for example $a = 100 and $a = 1..100?

$a = 100 points to integer with the value 100. $a = 1..100 is an array with 100 entries.

Upvotes: 1

Related Questions