Adding logic to array in powershell

拟墨画扇 提交于 2019-12-25 01:05:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!