Powershell:属性 存储在变量中

Powershell: Property stored in a variable

我想使用 EPPlus 查找基于 属性 值的范围内的所有单元格。假设我需要在现有电子表格中查找所有带有粗体文本的单元格。我需要创建一个函数来接受可配置的属性参数,但我在使用存储在变量中的 属性 时遇到了问题:

$cellobject = $ws.cells[1,1,10,10]
$properties = 'Style.Font.Bold'

$cellobject.$properties
$cellobject.{$properties}
$cellobject.($properties)
$cellobject."$properties"

None 这些工作并导致调用深度溢出。

如果这种方式行不通,库中有我可以使用的东西吗?

已编辑:为了显示最终解决方案,我使用 HanShotFirst 提供的概念更新了函数...

function Get-CellObject($ExcelSheet,[string]$PropertyString,[regex]$Value){

    #First you have to get the last row with text, 
    #solution for that is not provided here...
    $Row = Get-LastUsedRow -ExcelSheet $ExcelSheet -Dimension $true

    while($Row -gt 0){
        $range = $ExcelSheet.Cells[$Row, 1, $Row, $ExcelSheet.Dimension.End.Column]

        foreach($cellObject in $range){

            if($PropertyString -like '*.*'){
                $PropertyArr = $PropertyString.Split('.')
                $thisObject = $cellObject

                foreach($Property in $PropertyArr){
                    $thisObject = $thisObject.$Property

                    if($thisObject -match $Value){
                        $cellObject
                    }
                }
            }
            else{
                if($cellObject.$PropertyString -match $Value){
                    $cellObject
                }
            }
        }
        $Row--
    }
}
#The ExcelSheet parameter takes a worksheet object
Get-CellObject -ExcelSheet $ws -Property 'Style.Font.Bold' -Value 'True'

进入属性的点并不真正适用于字符串。您需要分离属性层。这是具有三层属性的对象的示例。

# create object
$props = @{
    first = @{
        second = @{
            third = 'test'
        }
    }
}
$obj = New-Object -TypeName psobject -Property $props

# outputs "test"
$obj.first.second.third

# does not work
$obj.'first.second.third'

# outputs "test"
$a = 'first'
$b = 'second'
$c = 'third'
$obj.$a.$b.$c

在您的示例中,这将是这样的:

$cellobject = $ws.cells[1,1,10,10]
$p1 = 'Style'
$p2 = 'Font'
$p3 = 'Bold'

$cellobject.$p1.$p2.$p3

或者你可以做的有点动态。这应该产生相同的结果:

$cellobject = $ws.cells[1,1,10,10]    
$props = 'Style.Font.Bold'.Split('.')
$result = $cellobject
foreach ($prop in $props) {
    $result = $result.$prop
}
$result

从星期五开始,这里有一个功能:)

function GetValue {
    param (
        [psobject]$InputObject,
        [string]$PropertyString
    )

    if ($PropertyString -like '*.*') {
        $props = $PropertyString.Split('.')
        $result = $InputObject
        foreach ($prop in $props) {
            $result = $result.$prop
        }
    } else {
        $result = $InputObject.$PropertyString
    }

    $result
}

# then call the function
GetValue -InputObject $cellobject -PropertyString 'Style.Font.Bold'