循环浏览多个值

时间:2018-08-15 12:41:27

标签: powershell

Word Doc内容:[(7)] / [(8)] [安全代理1]作为被担保方(“安全代理”)的安全受托人;和

要提取的值为“安全代理1”

它将7提取为括号中的第一个。

下面的代码可以正常工作,但是在括号内仅给出第一个出现的值。需要在括号内的多个值之间循环,并在括号内给我第三个值

$FinalTable = Get-Content $SourceFile|
        select-string -pattern $SearchKeyword |
        Select -Property @{Name = 'Name'; Expression = {$_.Line}}, @{Name = 'LineNo'; Expression = {$_.LineNumber}}, @{Name='Criteria';Expression = {$_.Category}} |
        ForEach-Object {

        $str = $_.Name
        $LineNumber = $_.LineNo
        $Criteria = $_.Criteria
        $start = $str.indexOf("[") + 1
        $end = $str.indexOf("]", $start)
        $length = $end - $start
        $result = ($str.substring($start, $length)).trim()

        #Creating a custom object to display in table format
        $Obj = New-Object -TypeName PSCustomObject
        Add-Member -InputObject $Obj -MemberType NoteProperty -Name Category -Value $Category
        Add-Member -InputObject $Obj -MemberType NoteProperty -Name Description -Value $result

        $obj
    } 
 $FinalTable | Export-Csv -Path $DestinationFile -NoTypeInformation -Encoding ASCII

按照理论建议尝试该方法,但没有成功

$FinalTable = Get-Content $SourceFile|
        select-string -pattern $SearchKeyword |
        Select -Property @{Name = 'Name'; Expression = {$_.Line}}, @{Name = 'LineNo'; Expression = {$_.LineNumber}}, @{Name='Criteria';Expression = {$_.Category}} |
        ForEach-Object {

        $str = $_.Name
        $LineNumber = $_.LineNo
        $Criteria = $_.Criteria

        #$start = $str.indexOf("[") + 1
        #$end = $str.indexOf("]", $start)
        #$length = $end - $start
        #$result = ($str.substring($start, $length)).trim()
                #Write-host $str
        if ($str -match '(\[[^\]]+])\/(\[[^\]]+])\s*\[\s*([^\]]+)]') {
            # $matches[1] --> "(7)"
            # $matches[2] --> "(8)"
            $result = $matches[3]  # --> "Security Agent 1"
            } 
        Write-Host $result
        #Creating a custom object to display in table format
        $Obj = New-Object -TypeName PSCustomObject
        Add-Member -InputObject $Obj -MemberType NoteProperty -Name Category -Value $Category
        Add-Member -InputObject $Obj -MemberType NoteProperty -Name Description -Value $result

        $obj
    } 
 $FinalTable | Export-Csv -Path $DestinationFile -NoTypeInformation -Encoding ASCII

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式以[(7)]/[(8)] [ Security Agent 1] as security trustee for the Secured Parties (the "Security Agent")之类的字符串来获取括号之间的部分。

代替

$start = $str.indexOf("[") + 1
$end = $str.indexOf("]", $start)
$length = $end - $start
$result = ($str.substring($start, $length)).trim()

if ($str -match '\[([^\]]+)\]\/\[([^\]]+)\]\s*\[\s*([^\]]+)]') {
    # $matches[1] --> "(7)"
    # $matches[2] --> "(8)"
    $result = $matches[3]  # --> "Security Agent 1"
} 
else {
    $result = ''   # should not happen..
}