从文本文件

时间:2017-03-08 08:21:11

标签: powershell object text

我们有以下文本文件:

[UserA]
;Path1 in comment
Path 2
Path 3

[UserB]
Path 1
[UserC]
Path 1
Path 2

我们尝试使用属性SamAccountNamePath为每个用户创建一个对象。以下代码执行此操作但它无法捕获最后一个对象:

Param (
    [String]$File = 'S:\Test\Brecht\Input_Test\files.ini'
)

#<# TEST
    $VerbosePreference = 'Continue'
#>

$Hash = @{}
$Path = @()

$FileContent = Get-Content $File | where {$_ -notlike ';*'} 

$Objects = $FileContent | ForEach-Object {
    Write-Verbose "Text line '$_'"

    if ($_ -match '\[') {
        if ($Path.Length -ne 0) {
            $Hash.Path = $Path
            New-Object –TypeName PSObject -Property $Hash
        }

        $Hash = @{}
        $Path = @()
        $Hash.SamAccountName = $_.Split('[,]')[1]
    }
    else {
        Write-Verbose "Add path '$_'"
        $Path += [PSCustomObject]@{
            Original = $_
            Test     = $null
        }
    }    
}

有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

要获得快速解决方案,您可以使用-End cmdlet中的Foreach-Object参数:

$Objects = $FileContent | ForEach-Object {
    Write-Verbose "Text line '$_'"

    if ($_ -match '\[') {
        if ($Path.Length -ne 0) {
            $Hash.Path = $Path
            New-Object –TypeName PSObject -Property $Hash
        }

        $Hash = @{}
        $Path = @()
        $Hash.SamAccountName = $_.Split('[,]')[1]
    }
    else {
        Write-Verbose "Add path '$_'"
        $Path += [PSCustomObject]@{
            Original = $_
            Test     = $null
        }
    }    
} -End {
 if ($Path.Length -ne 0) {
            $Hash.Path = $Path
            New-Object –TypeName PSObject -Property $Hash
        }
}

答案 1 :(得分:1)

最终我选择使用for循环来完成它。它让我更有控制力:

$FileContent = (Get-Content $File | where {($_ -notlike ';*') -and $_}) -split '\['

$Objects = for ($i=0; $i -lt $FileContent.Length; $i++) {
    if ($FileContent[$i] -eq '') {
        $SpaceIndex = $i
        Write-Verbose "Initiate object"
        $Object = [PSCustomObject]@{
            SamAccountName = $null
            Path           = @()
        }
    }
    if ($FileContent[$i -1] -eq '') {
        Write-Verbose "SamAccountName '$($FileContent[$i])'"
        $Object.SamAccountName = $FileContent[$i].TrimEnd(']')
    }
    if (($i -ne $SpaceIndex) -and ($i -ne $SpaceIndex +1)) {
        Write-Verbose "Path '$($FileContent[$i])'"
        $Object.Path += [PSCustomObject]@{
            Original = $FileContent[$i]
            Test     = $null
        }  
    }
    if (($FileContent[$i+1] -eq '') -or ($i -eq $FileContent.Length -1)) {
        Write-Verbose "Create object"
        $Object
    }
}