问题
I have imported a CSV file and created an array out of the data. I need to split off the domain names which used split, however some of the names are IP addresses, so it is split those as well.
How can I add some logic to do my normal split? But if it's a number like a IP address, ignore and print it.
Below is my sample data, the "Client Name' is what I'm trying to work with.
$NewCSV = $a | ForEach-Object {
$Record = @{
'Client Name' = $_."Name".Split('.')[0]
'Policy Name' = $_."AgentServerType"
'Backup State' = $_."BackupStatus"
'logon' = $_."LogonAccountTestStatus"
'account' = $_."LogonAccount"
}
New-Object PSObject -Prop $Record
} | Select "Client Name","Policy Name","Backup State","logon","account"
回答1:
Instead of using the .split() method you could use the
RegEx based -split operator with a negative lookahead to inhibit splitting if a digit follows.
BTW the $Record isn't meccessary.
$NewCSV = $a | ForEach-Object {
New-Object PSObject -Prop @{
'Client Name' =($_.Name -split '\.(?!\d{1,3}(\.|$))')[0]
'Policy Name' = $_.AgentServerType
'Backup State' = $_.BackupStatus
'logon' = $_.LogonAccountTestStatus
'account' = $_.LogonAccount
}
} | Select "Client Name","Policy Name","Backup State",logon,account
回答2:
You can use the IPAddress.TryParse method to determine if a String
represents an IP address...
$Record = @{
'Client Name' = if ([IPAddress]::TryParse($_.Name, [Ref] $null)) {
$_.Name
} else {
$_.Name.Split('.')[0]
}
# ...
}
A type accelerator exists for the IPAddress class so we do not need to specify the namespace, too (i.e. [System.Net.IPAddress]
). The second parameter of TryParse
is used to return an IPAddress
instance parsed from the first parameter, if successful. We don't need this IPAddress
instance, so we just pass $null
instead.
Also, just a stylistic note, you don't need to and it's not typical to surround property names with quotes (e.g. $_."AgentServerType"
) unless the property name contains whitespace.
来源:https://stackoverflow.com/questions/53348002/adding-logic-to-array-in-powershell