Read Excel sheet in Powershell

后端 未结 4 1296
有刺的猬
有刺的猬 2020-11-29 09:22

The below script reads the sheet names of an Excel document....

How could I improve it so it could extract all the contents of column B (starting from row 5 - so row

4条回答
  •  半阙折子戏
    2020-11-29 10:04

    This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.

    $lastCell = 11 
    $startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7
    
    $excel = New-Object -ComObject excel.application
    $wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
    $sh = $wb.Sheets.Item(1)
    $endRow = $sh.UsedRange.SpecialCells($lastCell).Row
    
    $phoneData = for ($i=1; $i -le $endRow; $i++)
                {
                    $pModel = $sh.Cells.Item($startRow,$model).Value2
                    $pMAC = $sh.Cells.Item($startRow,$mac).Value2
                    $nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
                    $extension = $sh.Cells.Item($startRow,$ext).Value2
                    New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
                    $startRow++
                }
    

    I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

提交回复
热议问题