简体   繁体   中英

Using '-replace' operator to delete text in Powershell

I have a list (array) of data which contain IP address and other information:

$example

@{IP=192.168.1.2; otherinfo=etc; moreinfo=etc}
@{IP=192.168.1.3; otherinfo=etc; moreinfo=etc}
@{IP=192.168.1.4; otherinfo=etc; moreinfo=etc}

I want to keep he IP address and strip all the other text. I have seen substring and split used but I haven't had luck, only errors, so I've been using -replace.

I've had success deleting text after the IP address:

$example = $example -replace '(.+?);.+','$1'
$example

@{IP=192.168.1.2
@{IP=192.168.1.3
@{IP=192.168.1.4

Quite frankly, I am having a hard time grasping what is happening here. I found copy/pasted this and replaced the symbol with ";". I have tried googling to understand but haven't understood it yet.

I am unsure how to delete the text before and including "=".

If $example is an array of hashtables like it appears, then simply pull the values you want from the specific property.

$example = @(
    @{IP='192.168.1.2'; otherinfo='etc'; moreinfo='etc'}
    @{IP='192.168.1.3'; otherinfo='etc'; moreinfo='etc'}
    @{IP='192.168.1.4'; otherinfo='etc'; moreinfo='etc'}
)

$example.ip

192.168.1.2
192.168.1.3
192.168.1.4

Per our discussion, this should get you the desired IPs

$iplist = import-xlsx -path "\\shared_server" -Sheet 4 -RowStart 2 -Header IP,QID,VendorID,Severity,Title |
    Where-Object title -match ‘HP Support’ | Select-Object -ExpandProperty IP

The Import-XLSX function returns an array of PSObjects, not a string, so you should not try to use a string method like -replace on it. Instead, filter the output using a Where-Object clause and finally select only the property or properties you need from the objects that passed the filter.

$iplist = (Import-XLSX -Path "\\shared_server" -Sheet 4 -RowStart 2 -Header IP,QID,VendorID,Severity,Title | `
           Where-Object {$_.Title -like '*HP Support*'}).IP

Variable $iplist should now be a string array with values

192.168.1.2
192.168.1.3
192.168.1.4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM