
powershell 使用

When you need a data set for testing or demonstration, and that set needs to represent Personally Identifiable Information (PII), you generally don’t want to use real data that represents actual people. Here, we’ll walk you through how you can use PowerShell to generate a list of random names and phone numbers for just such an occasion.
当您需要用于测试或演示的数据集,并且该数据集需要表示个人身份信息(PII)时 ,通常您不希望使用表示实际人员的真实数据。 在这里,我们将引导您逐步了解如何使用PowerShell生成此类情况下的随机名称和电话号码列表。
你需要什么 (What You Need)
Before you get started, there’s some tools and information you should have:
在开始之前,您应该拥有一些工具和信息:
电源外壳 (PowerShell)
This script was developed using PowerShell 4.0, and has also been tested for compatibility with PowerShell 2.0. PowerShell 2.0 or later has been built-in to Windows since Windows 7. It is also available for Windows XP and Vista as part of the Windows Management Framework (WMF). Some further details, and links for downloads, are below.
该脚本是使用PowerShell 4.0开发的,并且已经过测试与PowerShell 2.0的兼容性。 自Windows 7以来,PowerShell 2.0或更高版本已内置于Windows。它还可以作为Windows管理框架(WMF)的一部分用于Windows XP和Vista。 以下是一些更多详细信息以及下载链接。
PowerShell 2.0 comes with Windows 7. Windows XP SP3 and Vista (SP1 or later) users can download the appropriate WMF version from Microsoft in KB968929. It is not supported on XP SP2 or below, or Vista without SP1.
PowerShell 2.0随Windows 7一起提供。Windows XP SP3和Vista(SP1或更高版本)用户可以从Microsoft的KB968929中下载适当的WMF版本。 XP SP2或更低版本或不带SP1的Vista不支持此功能。
PowerShell 4.0 comes with Windows 8.1. Windows 7 SP1 users can upgrade to it as part of a WMF update from the Microsoft Download Center. It is not available for XP or Vista.
PowerShell 4.0随Windows 8.1一起提供。 Windows 7 SP1用户可以从Microsoft下载中心将其升级为WMF更新的一部分。 它不适用于XP或Vista。
名字 (Names)
You’ll need some lists of names to feed into the random generator. A great source for a lot of names, and information regarding their popularity (though that will not be used for this script), is the United States Census Bureau. The lists available at the links below are very large, so you might want to trim them down a bit if you plan to be generating a lot of names and numbers at once. On our test system, each name/number pair took about 1.5 seconds to generate using the full lists but your mileage will vary depending on your own system specs.
您将需要一些名称列表以馈入随机生成器。 美国人口普查局(US Census Bureau )是许多名称的一个很好的来源,并提供了有关其受欢迎程度的信息(尽管此脚本不会使用)。 下面的链接上可用的列表很大,因此,如果您打算一次生成大量名称和数字,则可能需要对它们进行一些缩小。 在我们的测试系统上,使用完整列表生成每个名称/数字对大约需要1.5秒,但您的里程会因您自己的系统规格而异。
Regardless of the source you use, you will need to generate three text files that the script can use as pools for its name selection. Each file should contain only names, and only one name per line. These need to be stored in the same folder as your PowerShell script.
无论使用哪种源,都将需要生成三个文本文件,脚本可以将其用作名称选择的池。 每个文件应仅包含名称,每行仅包含一个名称。 它们需要与PowerShell脚本存储在同一文件夹中。
Surnames.txt should contain the surnames you want the script to select from. Example:
Surnames.txt应包含您希望脚本从中选择的姓氏。 例:
Smith Johnson Williams Jones Brown
Smith Johnson Williams Jones Brown
Males.txt should contain the male first names you want the script to select from. Example:
Males.txt应该包含您希望脚本从中选择的男性名字。 例:
James John Robert Michael William
Females.txtshould contain the female first names you want the script to select from. Example:
Females.txt应包含您要脚本选择的女性名字。 例:
Mary Patricia Linda Barbara Elizabeth
Mary Patricia Linda Barbara Elizabeth
电话号码规则 (Rules for Phone Numbers)
If you want to be sure your phone numbers don’t match up with anyone’s real phone number, the easiest way is to use the well-known “555” Exchange Code. But if you’re going to be showing a data set with a lot of phone numbers, that 555 will start to look pretty monotonous real fast. To make things more interesting, we’ll generate other phone numbers that violate the North American Numbering Plan (NANP) rules. Below are some sample invalid phone numbers, representing each class of number that will be generated by this script:
如果要确保您的电话号码与任何人的真实电话号码都不匹配,最简单的方法是使用众所周知的“ 555”交换代码 。 但是,如果您要显示包含大量电话号码的数据集,那么555将会开始显得非常单调。 为了使事情变得更有趣,我们将生成其他违反北美编号计划 (NANP)规则的电话号码。 下面是一些无效的电话号码示例,代表此脚本将生成的每种号码:
(157) 836-8167This number is invalid because Area Codes cannot begin with a 1 or 0.
(157)836-8167 该数字无效,因为区号不能以1或0开头。
(298) 731-6185This number is invalid because the NANP is not assigning area codes with 9 as the second digit.
(298)731-6185 该号码无效,因为NANP并未分配以9作为第二位的区号。
(678) 035-7598This number is invalid because Exchange Codes cannot begin with a 1 or 0.
(678)035-7598 该数字无效,因为交换代码不能以1或0开头。
(752) 811-1375This number is invalid because Exchange Codes cannot end with two 1s.
(752)811-1375 该数字无效,因为交换代码不能以两个1结尾。
(265) 555-0128This number is invalid because the Exchange Code is 555, and the Subscriber ID is within the range reserved for fictitious numbers.
(265)555-0128 该号码无效,因为交换代码为555, 并且订户ID在为虚拟号码保留的范围内。
(800) 555-0199This number is the only 800 number with a 555 Exchange Code which is reserved for use as a fictitious number.
(800)555-0199 该号码是唯一带有555交换代码的800号码,保留用作虚拟号码。
Note that the above rules are subject to change and may vary by jurisdiction. You should do your own research to verify the current rules which are applicable to the locale for which you will be generating phone numbers.
请注意,以上规则可能会有所更改,并且可能会因管辖权而异。 您应该进行自己的研究,以验证适用于将为其生成电话号码的语言环境的当前规则。
常用命令 (Common Commands)
There are some fairly common commands that are going to be used throughout this script, so you should get a basic idea of what these mean before we dive into actually writing it.
在此脚本中将使用一些相当常见的命令,因此在深入学习实际编写命令之前,您应该基本了解这些命令的含义。
ForEach-Object takes an array, or list, of objects and performs the specified operation on each of them. Within a ForEach-Object script block, the $_ variable is used to refer to the current item being processed.
ForEach-Object接受对象的数组或列表,并对每个对象执行指定的操作。 在ForEach-Object脚本块中,$ _变量用于引用正在处理的当前项目。
if … else statements allow you to perform an operation only if certain conditions are met, and (optionally) specify what should be done when that condition is not met.
if…else语句仅在满足某些条件时才允许您执行操作,并且(可选)指定在不满足该条件时应执行的操作。
switch statements are like if statements with more choices. Switch will check an object against several conditions, and run whatever script blocks are specified for conditions that the object matches. You can also, optionally, specify a default block which will only run if no other conditions are matched. Switch statements also use the $_ variable to refer to the current item being processed.
switch语句就像if语句有更多选择。 Switch将根据多个条件检查对象,并为该对象匹配的条件运行指定的任何脚本块。 您还可以选择指定一个默认块,该块仅在没有其他条件匹配时才运行。 Switch语句还使用$ _变量来引用当前正在处理的项目。
while statements allow you to continuously repeat a script block so long as a certain condition is met. Once something happens that causes the condition to no longer be true when the script block is finished, the loop exits.
while语句允许您在满足特定条件的情况下连续重复执行脚本块。 一旦脚本块完成时发生某种情况导致条件不再成立,则循环退出。
try … catch statements help with error handling. If anything goes wrong with the script block specified for try, the catch block will run.
尝试…catch语句有助于错误处理。 如果指定要尝试的脚本块出现任何问题,则catch块将运行。
Get-Content does what it says on the tin. It gets the contents of a specified object – usually a file. This can be used to display the contents of a text file at the console or, as in this script, pass the contents along the pipeline to be used with other commands.
Get-Content会按提示说。 它获取指定对象(通常是文件)的内容。 这可以用于在控制台上显示文本文件的内容,也可以像在此脚本中一样,将内容沿管道传递以与其他命令一起使用。
Write-Host puts stuff in the console. This is used to present messages to the user, and is not included in the script’s output if the output gets redirected.
Write-Host将内容放入控制台。 它用于向用户显示消息,如果重定向输出,则不包含在脚本的输出中。
Write-Output actually generates output. Normally, this is dumped to the console but it can also be redirected by other commands.
Write-Output实际上生成输出。 通常,它会转储到控制台,但也可以通过其他命令重定向。
There are other commands in the script, but we’ll explain those as we go.
脚本中还有其他命令,但是我们将在后面解释这些命令。
构建脚本 (Building the Script)
Now it’s time to get our hands dirty.
现在是时候弄脏我们的手了。
第1部分:准备出发 (Part 1: Getting Ready to Go)
If you like your script to start running from a clean console, here’s the first line you want in it.
如果您希望脚本从一个干净的控制台开始运行,这是您要在其中添加的第一行。
Clear-Host
Now that we have a clean screen, the next thing we want to do is have the script check to make sure everything it needs is in place. To do that, we need to start by telling it where to look, and what to look for.
现在我们有了一个干净的屏幕,接下来我们要做的是检查脚本,以确保所需的一切都就绪。 为此,我们需要先告诉它在哪里寻找以及寻找什么。
$ScriptFolder = Split-Path $MyInvocation.MyCommand.Definition -Parent $RequiredFiles = ('Males.txt','Females.txt','Surnames.txt')
$ScriptFolder = Split-Path $MyInvocation.MyCommand.Definition -Parent $RequiredFiles = ('Males.txt','Females.txt','Surnames.txt')
The first line there is very useful for any script. It defines a variable that points to the folder containing the script. This is essential if your script needs other files that are located in the same directory as itself (or a known relative path from that directory), because you will otherwise encounter errors if and when you try to run the script while you’re in another working directory.
第一行对于任何脚本都非常有用。 它定义了一个变量,该变量指向包含脚本的文件夹。 如果您的脚本需要与自身位于同一目录(或该目录的已知相对路径)中的其他文件,则这是必不可少的,因为如果在其他位置尝试运行脚本时,否则会遇到错误。工作目录。
The second line creates an array of file names that are required for the script to run properly. We’ll use this, along with the $ScriptFolder variable, in the next piece where we check to be sure those files are present.
第二行创建一个脚本正常运行所需的文件名数组。 在下一部分中,我们将使用它与$ ScriptFolder变量一起使用,以检查这些文件是否存在。
$RequiredFiles | ForEach-Object { if (!(Test-Path "$ScriptFolder\$_")) { Write-Host "$_ not found." -ForegroundColor Red $MissingFiles++ } }
This chunk of script sends the $RequiredFiles array into a ForEach-Object block. Within that script block, the if statement uses Test-Path to see if the file we’re looking for is where it belongs. Test-Path is a simple command that, when given a file path, returns a basic true or false response to tell us if the path points to something that exists. The exclamation point in there is a not operator, which reverses the response of Test-Path before passing it on to the if statement. So if Test-Path returns false (that is, the file we’re looking for does not exist), it will be converted to true so that the if statement will execute its script block.
此脚本块将$ RequiredFiles数组发送到ForEach-Object块中。 在该脚本块中,if语句使用Test-Path来查看我们要查找的文件是否属于该文件。 Test-Path是一个简单的命令,当给定文件路径时,它会返回基本的true或false响应,以告诉我们该路径是否指向存在的内容。 感叹号中有一个not运算符,它在将Test-Path的响应传递给if语句之前将其反转。 因此,如果Test-Path返回false(即我们正在查找的文件不存在),它将被转换为true,以便if语句将执行其脚本块。
Another thing to note here, which will be used often in this script, is the use of double-quotes instead of single-quotes. When you put something in single-quotes, PowerShell treats it as a static string. Whatever is in the single quotes will be passed along exactly as-is. Double-quotes tells PowerShell to translate the variables and some other special items within the string before passing it along. Here, the double-quotes mean that instead of running Test-Path ‘$ScriptFolder\$_’ we’ll actually be doing something more like Test-Path ‘C:\Scripts\Surnames.txt’ (assuming your script is in C:\Scripts, and ForEach-Object is currently working on ‘Surnames.txt’).
在此脚本中经常要注意的另一件事是使用双引号而不是单引号。 当您将某些内容放在单引号中时,PowerShell会将其视为静态字符串。 无论单引号中的内容是什么,都将照原样传递。 双引号告诉PowerShell在传递字符串之前先翻译字符串中的变量和其他一些特殊项目。 在这里,双引号表示我们实际上不是在运行Test-Path'$ ScriptFolder \ $ _',而是在做类似Test- Path'C :\ Scripts \ Surnames.txt'的操作 (假设您的脚本在C语言中) :\ Scripts,并且ForEach-Object当前正在使用'Surnames.txt')。
For each file not found, Write-Host will post an error message in red to tell you which file is missing. Then it increments the $MissingFiles variable which will be used in the next piece, to error and quit if there were any files missing.
对于找不到的每个文件,Write-Host将以红色显示错误消息,告诉您缺少哪个文件。 然后,它将增加将在下一部分中使用的$ MissingFiles变量,如果缺少任何文件,将出错并退出。
if ($MissingFiles) { Write-Host "Could not find $MissingFiles source file(s). Aborting script." -ForegroundColor Red Remove-Variable ScriptFolder,RequiredFiles,MissingFiles Exit }
if ($MissingFiles) { Write-Host "Could not find $MissingFiles source file(s). Aborting script." -ForegroundColor Red Remove-Variable ScriptFolder,RequiredFiles,MissingFiles Exit }
Here’s another neat trick you can do with if statements. Most guides you’ll see about if statements will tell you to use an operator to check for a matching condition. For example, here we could use if ($MissingFiles -gt 0) to see if $MissingFiles is greater than zero. However, if you’re already using commands that return a boolean value (as in the previous block where we were using Test-Path) that’s not necessary. You can also do without it in cases like this, when you’re just testing to see if a number is non-zero. Any non-zero number (positive or negative) gets treated as true, while zero (or, as may happen here, a non-existent variable) will be treated as false.
这是您可以使用if语句完成的另一个巧妙技巧。 您将看到的大多数指南都是有关语句是否会告诉您使用运算符来检查匹配条件的。 例如,在这里我们可以使用if($ MissingFiles -gt 0)来查看$ MissingFiles是否大于零。 但是,如果您已经在使用返回布尔值的命令(如在我们使用Test-Path的上一个块中一样),则没有必要。 在仅测试数字是否为非零的情况下,也可以在没有这种情况的情况下执行此操作。 任何非零数字(正数或负数)都将被视为true,而零(或可能在此处发生的不存在的变量)将被视为false。
If $MissingFiles exists, and is non-zero, Write-Host will post a message telling you how many files were missing and that the script will abort. Then, Remove-Variable will clean up all the variables we’ve created and Exit will quit the script. At the regular PowerShell console, Remove-Variable is not really needed for this particular purpose because variables set by scripts are normally discarded when the script exits. However, the PowerShell ISE behaves a bit differently so you may want to keep this in if you plan on running the script from there.
如果$ MissingFiles存在并且不为零,Write-Host将发布一条消息,告诉您缺少了多少个文件,脚本将中止。 然后,Remove-Variable将清除我们创建的所有变量,而Exit将退出脚本。 在常规的PowerShell控制台上,出于此特定目的实际上并不需要Remove-Variable,因为通常在脚本退出时会丢弃由脚本设置的变量。 但是,PowerShell ISE的行为略有不同,因此,如果您打算从那里运行脚本,则可能需要保留此功能。
If all things are in order, the script will continue on. One more preparation to make is an alias that we’ll be really glad to have later on.
如果一切正常,脚本将继续。 还有一个准备工作就是别名,我们以后将非常高兴能使用它。
New-Alias g Get-Random
Aliases are used to create alternate names for commands. These can be useful to help us get acquainted with the new interface (e.g.: PowerShell has built-in aliases like dir -> Get-ChildItemand cat -> Get-Content) or to make short-hand references for commonly-used commands. Here, we’re making a very short-hand reference for the Get-Random command which is going to be used a lot later on.
别名用于创建命令的备用名称。 这些对帮助我们熟悉新界面(例如,PowerShell具有内置的别名,如dir-> Get-ChildItem和cat- > Get-Content )或为常用命令进行简要引用很有用。 在这里,我们为Get-Random命令提供了非常简明的参考,该参考将在以后大量使用。
Get-Random pretty much does what its name implies. Given an array (like a list of names) as input, it picks a random item from the array and spits it out. It can also be used to generate random numbers. The thing to remember about Get-Random and numbers though is that, like many other computer operations, it starts counting from zero. So instead of Get-Random 10 meaning the more natural “give me a number from 1 to 10” it really means “give me a number from 0 to 9.” You can be more specific about the number selection, so that Get-Random behaves more like you’d naturally expect, but we won’t need that in this script.
Get-Random几乎可以实现其名称所暗示的功能。 给定一个数组(如名称列表)作为输入,它将从数组中选择一个随机项并将其吐出。 它也可以用于生成随机数。 关于Get-Random和数字,要记住的事情是,与许多其他计算机操作一样,它从零开始计数。 因此,与Get-Random 10相比 ,它更自然地表示“给我一个从1到10的数字”,实际上意味着“给我一个从0到9的数字”。 您可以更具体地选择数字,以使Get-Random的行为更像您自然期望的那样,但是在此脚本中我们不需要这样做。
第2部分:获取用户输入并开始工作 (Part 2: Getting User Input and Getting to Work)
While a script that generates just one random name & phone number is great, it is much better if the script allows the user to specify how many names & numbers they want to get in one batch. Unfortunately, we can’t really trust users to always give valid input. So, there’s a tiny bit more to this than just $UserInput = Read-Host.
虽然只生成一个随机名称和电话号码的脚本非常有用,但是如果脚本允许用户指定要在一批中获得多少个名称和电话号码,则更好。 不幸的是,我们不能真正相信用户总是提供有效的输入。 因此,这不仅仅是$ UserInput = Read-Host 。
while (!$ValidInput) { try { [int]$UserInput = Read-Host -Prompt 'Items to be generated' $ValidInput = $true } catch { Write-Host 'Invalid input. Enter a number only.' -ForegroundColor Red } }
while (!$ValidInput) { try { [int]$UserInput = Read-Host -Prompt 'Items to be generated' $ValidInput = $true } catch { Write-Host 'Invalid input. Enter a number only.' -ForegroundColor Red } }
The while statement above checks for, and negates, the value of $ValidInput. So long as $ValidInput is false, or does not exist, it will keep looping through its script block.
上面的while语句检查并否定$ ValidInput的值。 只要$ ValidInput为false或不存在,它将一直循环遍历其脚本块。
The try statement takes user input, via Read-Host, and attempts to convert it to an integer value. (That’s the [int] before Read-Host.) If it’s successful, it will set $ValidInput to true so that the while loop can exit. If not successful, the catch block posts an error and, because $ValidInput didn’t get set, the while loop will come back around and prompt the user again.
try语句通过Read-Host获取用户输入,并尝试将其转换为整数值。 (这是Read-Host之前的[int] 。)如果成功,它将把$ ValidInput设置为true,以便退出while循环。 如果未成功,则catch块将发布错误,并且由于未设置$ ValidInput,因此while循环将重新出现并再次提示用户。
Once the user has properly given a number as input, we want the script to announce that it’s about to start actually doing its work and then get about doing it.
用户正确输入数字后,我们希望脚本宣布它将开始实际开始工作,然后开始进行工作。
Write-Host "`nGenerating $UserInput names & phone numbers. Please be patient.`n" 1..$UserInput | ForEach-Object { <# INSERT RANDOM NAME & NUMBER GENERATOR HERE #> }
Don’t worry, we’re not going to leave you on your own to figure out the random name & number generator code. That’s just a placeholder comment to show you where the next section (where the real work gets done) is going to fit.
不用担心,我们不会让您自己找出随机的名称和数字生成器代码。 这只是一个占位符注释,用于向您显示下一部分(完成实际工作的位置)的合适位置。
The Write-Host line is pretty straightforward. It simply says how many names and phone numbers the script is going to generate, and asks the user to be patient while the script does its work. The`n at the start and end of the string is to insert a blank line before and after that output, just to give it some visual separation between the input line and the list of names & numbers. Be aware that that’s a back-tick (AKA “grave accent” – usually the key above tab, to the left of 1) and not an apostrophe or single-quote in front of each n.
Write-Host行非常简单。 它只是说出脚本将要生成多少个名称和电话号码,并要求用户在脚本执行工作时耐心等待。 字符串开头和结尾的`n分别是在输出之前和之后插入空白行,只是为了使输入行与名称和数字列表之间有一些视觉上的分隔。 请注意,这是一个反引号(也就是“重音符”,通常是制表符上方的键,位于1的左侧),而不是每个n前面的撇号或单引号。
The next part shows a different way you can use a ForEach-Object loop. Typically, when you want a script block to run a certain number of times, you’ll set up a regular for loop like for ($x = 1; $x -le $UserInput; $x++) {<# INSERT SCRIPT HERE #>}. ForEach-Object lets us simplify this by feeding it a list of integers and, instead of telling it to actually do anything with those integers, we just give it a static script block to run until it runs out of integers to do it for.
下一部分显示了使用ForEach-Object循环的另一种方法。 通常,当您希望脚本块运行一定次数时,您将设置一个常规for循环,例如for($ x = 1; $ x -le $ UserInput; $ x ++){<#INSERT SCRIPT HERE# >}。 ForEach-Object使我们可以通过为其提供一个整数列表来简化此过程,而不是告诉它实际使用这些整数执行任何操作,我们只是给它提供一个静态脚本块来运行,直到它用完整数为止。
第3部分:生成随机名称 (Part 3: Generating a Random Name)
Generating the name is the simplest bit of the rest of this process. It only consists of three steps: Picking a surname, picking a gender, and picking a first name. Remember that alias we made for Get-Random awhile back? Time to start putting that to use.
生成名称是此过程其余部分中最简单的部分。 它仅包括三个步骤:选择一个姓氏,一个性别和一个名字。 还记得我们之前为Get-Random做的别名吗? 是时候开始使用它了。
$Surname = Get-Content "$ScriptFolder\Surnames.txt" | g $Male = g 2 if ($Male) {$FirstName = Get-Content "$ScriptFolder\Males.txt" | g} else {$FirstName = Get-Content "$ScriptFolder\Females.txt" | g}
$Surname = Get-Content "$ScriptFolder\Surnames.txt" | g $Male = g 2 if ($Male) {$FirstName = Get-Content "$ScriptFolder\Males.txt" | g} else {$FirstName = Get-Content "$ScriptFolder\Females.txt" | g}
The first line takes our list of surnames, feeds it into the random picker, and assigns the chosen name to $Surname.
第一行获取我们的姓氏列表,将其输入到随机选择器中,然后将所选名称分配给$ Surname。
The second line picks our person’s gender. Remember how Get-Random starts counting from zero, and how zero is false and everything else is true? That’s how we’re using Get-Random 2 (or the much shorter g 2thanks to our alias – both result in a choice between zero or one) to decide whether our person is male or not. The if/else statement afterwards randomly chooses a male or female first name accordingly.
第二行选择我们这个人的性别。 还记得Get-Random如何开始从零开始计数,零如何为假,其他一切都为真? 这就是我们使用Get-Random 2 (或者更短的g 2,这要归功于我们的别名–两者都导致零或一的选择)来决定我们的人是否是男性的方式。 之后,if / else语句会相应地随机选择一个男性或女性的名字。
第4部分:生成随机电话号码 (Part 4: Generating a Random Phone Number)
Here’s the really fun part. Earlier on, we showed you how there’s several ways you can make an invalid or fictitious phone number. Since we don’t want all our numbers looking too similar to each other, we’ll randomly pick an invalid number format every time. The randomly chosen formats will be defined by their Area Code and Exchange Code, which will collectively be stored as $Prefix.
这是真正有趣的部分。 较早前,我们向您展示了如何通过多种方法来创建无效或虚构的电话号码。 由于我们不希望所有数字看起来都过于相似,因此每次都会随机选择一个无效的数字格式。 随机选择的格式将由它们的区号和交换码定义,它们将一起存储为$ Prefix。
$NumberFormat = g 5 switch ($NumberFormat) { 0 {$Prefix = "($(g 2)$(g 10)$(g 10)) $(g 10)$(g 10)$(g 10)"} 1 {$Prefix = "($(g 10)9$(g 10)) $(g 10)$(g 10)$(g 10)"} 2 {$Prefix = "($(g 10)$(g 10)$(g 10)) $(g 2)$(g 10)$(g 10)"} 3 {$Prefix = "($(g 10)$(g 10)$(g 10)) $(g 10)11"} 4 {$Prefix = "($(g 10)$(g 10)$(g 10)) 555"} }
The first line is a straightforward random number generation to pick which format we’re going to follow for the phone number. Then, the switch statement takes that random choice and generates a $Prefix accordingly. Remember that list of invalid phone number types? The $NumberFormat values 0-3 correspond to the first four in that list. Value 4 can generate one of the last two, since both use the “555” Exchange Code.
第一行是简单明了的随机数生成,用于选择电话号码遵循的格式。 然后,switch语句采用该随机选择并相应地生成$ Prefix。 还记得无效电话号码类型列表吗? $ NumberFormat值0-3对应于该列表中的前四个。 值4可以生成后两个值之一,因为两者都使用“ 555”交换代码。
Here, you can also see we’re using another trick with double-quotes. Double-quotes don’t just let you interpret variables before a string gets output – they also let you process script blocks. To do that, you wrap the script block like this: “$(<#SCRIPT HERE#>)”. So what you have above is a lot of individually randomized digits, with some of them either limited in their range or set statically according to the rules we need to follow. Each string also has parenthesis and spacing as you’d normally expect to see in an Area Code and Exchange Code pair.
在这里,您还可以看到我们正在使用另一个带有双引号的技巧。 双引号不仅可以让您在输出字符串之前解释变量,还可以让您处理脚本块。 为此,您可以像这样包装脚本块: “ $(<#SCRIPT HERE#>)” 。 因此,您上面有很多单独的随机数字,其中一些数字范围有限,或者根据我们需要遵循的规则进行静态设置。 正如您通常希望在区号和交换代码对中看到的那样,每个字符串还具有括号和间距。
The last thing we need to do before we’re ready to output our name & phone number is to generate a Subscriber ID, which will be stored as $Suffix.
准备输出我们的姓名和电话号码之前,我们需要做的最后一件事是生成一个订户ID,该ID将存储为$ Suffix。
switch ($NumberFormat) { {$_ -lt 4} {$Suffix = "$(g 10)$(g 10)$(g 10)$(g 10)"} 4 { switch ($Prefix) { '(800) 555' {$Suffix = '0199'} default {$Suffix = "01$(g 10)$(g 10)"} } } }
switch ($NumberFormat) { {$_ -lt 4} {$Suffix = "$(g 10)$(g 10)$(g 10)$(g 10)"} 4 { switch ($Prefix) { '(800) 555' {$Suffix = '0199'} default {$Suffix = "01$(g 10)$(g 10)"} } } }
Because of the special rules for 555 numbers, we can’t just generate four random digits for the end of every phone number our script is going to make. So, the first switch checks to see if we’re dealing with a 555 number. If not, it generates four random digits. If it is a 555 number, the second switch checks for the 800 area code. If that matches, there’s only one valid $Suffix we can use. Otherwise, it’s allowed to pick from anything between 0100-0199.
由于有555个号码的特殊规定,我们不能只为脚本要制作的每个电话号码的末尾生成四个随机数字。 因此,第一个开关将检查我们是否正在处理555号。 如果不是,它将生成四个随机数字。 如果是555号,第二个开关将检查800区号。 如果匹配,则只能使用一个有效的$ Suffix。 否则,允许从0100-0199之间的任何内容中进行选择。
Note that there are a few different ways this block could have been written, instead of the way it is. Both switch statements could have been replaced with if/else statements, since they each only handle two choices. Also, instead of specifically calling out “4” as an option for the first switch statement, “default” could have been used similar to how it was done in the second since it was the only option left. The choice between if/else vs. switch, or where to use the default keyword instead of specific values, often comes down to a matter of personal preference. So long as it works, use whatever you’re most comfortable with.
请注意,本块可能有几种不同的写入方式,而不是原来的方式。 可以将两个switch语句替换为if / else语句,因为它们每个都只能处理两种选择。 此外,与其专门在第一个switch语句中选择“ 4”作为选项,还可以像在第二个语句中那样使用“默认”,因为它是剩下的唯一选项。 在if / else与switch之间进行选择,或者在何处使用default关键字而不是特定值,通常取决于个人喜好。 只要有效,请使用最舒适的方式。
Now, it’s time for output.
现在,该输出了。
Write-Output "$FirstName $Surname $Prefix-$Suffix" }
This one’s pretty much as simple as it gets in the script. It just outputs the first and last name separated by spaces, then another space before the phone number. Here’s where the standard dash between Exchange Code and Subscriber ID gets added as well.
这个脚本和脚本中的代码一样简单。 它仅输出名字和姓氏,并用空格分隔,然后在电话号码之前输出另一个空格。 这也是在Exchange代码和订户ID之间添加标准破折号的地方。
That closing bracket at the bottom is the end of the ForEach-Object loop from earlier – omit this if you’ve already got it.
底部的结束括号是ForEach-Object循环(从较早开始)的结尾-如果已经有了,请忽略它。
第5部分:清理和运行脚本 (Part 5: Cleanup and Running the Script)
After all the work is done, a good script knows how to clean up after itself. Again, the variable removal below isn’t really needed if you’re only going to run the script from the console but you will want it if you ever plan to run it in the ISE.
完成所有工作后,一个好的脚本会知道如何自行清理。 同样,如果仅打算从控制台运行脚本,则实际上并不需要下面的变量删除,但是如果您打算在ISE中运行它,则将需要它。
Remove-Item alias:\g Remove-Variable ScriptFolder,RequiredFiles,Surname,Male,FirstName,NumberFormat,Prefix,Suffix,ValidInput,UserInput
Remove-Item alias:\g Remove-Variable ScriptFolder,RequiredFiles,Surname,Male,FirstName,NumberFormat,Prefix,Suffix,ValidInput,UserInput
After you’ve got it all done, save the script with a “.ps1” extension in the same folder as your names files. Make sure your ExecutionPolicy is set so that the script can run, and give it a whirl.
完成所有步骤后,将扩展名为“ .ps1”的脚本保存在名称文件所在的文件夹中。 确保设置了ExecutionPolicy ,以便脚本可以运行,并对其进行旋转。
Here’s a screenshot of the script in action:
这是运行中的脚本的屏幕截图:

You can also download a ZIP file containing this PowerShell script, and text files with name lists, from the link below.
您还可以从下面的链接下载包含此PowerShell脚本的ZIP文件以及带有名称列表的文本文件。
Random Name & Phone Number Generator for PowerShell
翻译自: https://www.howtogeek.com/190088/how-to-generate-random-names-phone-numbers-with-powershell/
powershell 使用