在这种情况下使用数组会有什么不良后果?

时间:2019-05-14 06:59:06

标签: arrays powershell

我的问题是我在PS上玩耍并尝试新东西时有两方面的内容,我编写了一个小脚本,该脚本通过导出txt.file中的名字和另一个txt.file中的名字来生成全名,并最终随机组合2.创建一个全名,这是脚本:

$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-现在$ numberofNames是一个数组“范围运算符”,我想知道使用此方法会有什么不良后果?这是用户输入的最佳方法吗?

2-使用$a = 100$a = 1..100之间的主要区别是什么?

如果您需要知道: $ firstnames看起来像这样:

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

和$ lastnames:

  smith
  anderson
  müller
  klein
  Rex

谢谢

1 个答案:

答案 0 :(得分:1)

  

1-现在$ numberofNames是一个数组'范围运算符',我想知道使用这种方法会带来什么不良后果?这是用户输入的最佳方法吗?

有效。即使用户添加例如字符串作为输入Powershell将抛出错误,无法将输入转换为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

甚至是一个否定词。 int应该没问题,因为您没有将数组内容用于任何索引操作。

  

2-使用$ a = 100和$ a = 1..100之间的主要区别是什么?

$a = 100指向值为100的整数。 $a = 1..100是一个包含100个条目的数组。