2017-05-26 59 views
2

我想使用EPPlus根據屬性值查找範圍內的所有單元格。假設我需要在現有的電子表格中查找所有含粗體文本的單元格。我需要創建將接受一個可配置的性能參數的功能,但我使用存儲在一個變量屬性有問題:Powershell:存儲在變量中的屬性

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

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

這些工作都沒有,並導致調用深度溢出。

如果這種方式不行,我可以使用庫中的東西嗎?

編輯:爲了證明我更新與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' 
+0

你嘗試'$ cellobject.properties'? – Moerwald

+0

@Moerwald先生,我試過了。但重點是保持屬性在函數中可配置,所以這就是爲什麼我需要將屬性存儲在變量中。那有意義嗎? – Mack

+0

問題似乎是字符串$ properties中的句點。 – Mack

回答

3

點走進性能並沒有真正用字符串工作。您需要分離屬性的圖層。以下是三層屬性的對象示例。

# 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' 
+0

感謝您的回覆。你會提供一個功能的例子嗎?問題在於'$ cellobject'中的單元格編號是在循環中自動計算的,我需要添加這些屬性作爲參數並返回正確的對象。這是有道理的? 所以你說沒有辦法加入所有三個屬性作爲一個通過,是嗎? – Mack

+0

哎呀,我剛剛看到你編輯了答案。 – Mack

+0

增加了另一個具有函數的例子。 – HanShotFirst