我有一个文本文件,在文本文件中有两个名称,完全像这样。
Tom Hardy
Brad Pitt
我用它来从文件中提取名称并拆分它们。
$Names = gc C:\Temp\Name.txt
ForEach-Object {-Split $Names}
然后如何将每个名字分配给$ FirstName和每个姓氏给$ LastName?这背后的想法是,进一步讲,对于每个$ FirstName,我将使用每个名称创建一个特定的单独项。
我知道在执行上述操作后,名称的每个部分都分配给$ _,因此我可以对每个部分执行相同的操作,即
$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
希望这是有道理的,请让我知道是否需要进一步说明。
最佳答案
与@Paxz相同,但有一些解释和建议:
$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'
关于powershell - 分割字符串,然后分配分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51709291/