分割字符串,然后分配分割
我有一个文本文件,在文本文件中有两个名称,完全像这样。
I have a text file, in the text file are two names, exactly like this.
Tom Hardy
Tom Hardy
Brad Pitt
Brad Pitt
我用它来从文件中提取名称并将其分割。
I use this, to take the names from the file and split them.
$Names = gc C:\Temp\Name.txt
ForEach-Object {-Split $Names}
然后如何将每个名字分配给$ FirstName和每个姓氏分配给$ LastName?
How do I then assign each first name to $FirstName and each last name to $LastName?
其背后的想法是再往下走,对于每个$ FirstName,我将使用每个名称创建一个特定的单独项目。
The idea behind this is that further down the line, for each $FirstName I will be creating a specific individual item with each name.
我了解在执行上述操作后,名称的每个部分都分配给$ _,所以我可以对每个部分执行相同的操作,即
I understand that after I run the above, each section of the name is assigned to $_ so I can do the same thing with each section i.e
$Names = gc C:\Temp\Name.txt
$SplitNames = ForEach-Object {-Split $Names}
ForEach ($_ in $SplitNames) {Write-Host 'Name is' $_}
Name is Tom
Name is Hardy
Name is Brad
Name is Pitt
Hop e这很有意义,请让我知道是否需要进一步说明。
Hope this makes sense, please let me know if more clarification is needed.
与@Paxz相同,但有一些解释和建议:
Same as @Paxz but with some explanation and suggestions:
$Names = @(
'Brad Pitt',
'Tom Hardy',
'Daniel Craig Junior'
)
# the .ForEAch method is used as it's faster then piping data to Foreach-Object
$result = $Names.ForEach({
# we use the second argument of -Split to indicate
# we're only interested in two values
$tmpSplit = $_ -split ' ', 2
# we then create an object that allows us to
# name things propertly so we can play with it later withoout hassle
[PSCustomObject]@{
Input = $_
FirstName = $tmpSplit[0]
LastName = $tmpSplit[1]
}
})
# here we show the result of all our objects created
$result
# enable verbose text to he displayed
$VerbosePreference = 'Continue'
$result.ForEach({
# here we can easily address the object by its property names
Write-Verbose "Input '$($_.Input)' FirstName '$($_.FirstName)' LastName '$($_.LastName)'"
})
# disable verbose messages, because we don't need this in production
$VerbosePreference = 'SilentlyContinue'