Как выполнить цикл в Excel, чтобы применить список объектов групповой политики к подразделениям в Powershell - PullRequest
0 голосов
/ 14 мая 2019

Мне нужно перебрать файл Excel для подразделений и объектов групповой политики, а затем применить их к консоли управления объектами групповой политики. Я застрял для понимания процесса цикла.

get-module activedirectory,grouppolicy
#Open Excel and read info in file
$filepath = "C:\temp\AllGPOsLinkWin10toApply-report date 13-05-2019.xlsx"
$sheetname = "AllGPOsWin10 date 13-05"
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($filepath)
$WorkSheet = $WorkBook.Sheets.Item($sheetname)
$OU = @{}
$destinationOU = @{}
$i = 1
$j= 2

#Read the OU cells (A,$i) column 1, row 1 to 13
$destinationOU = $WorkSheet.Cells.Item($i, 1).Text

#Read the GPO cells (all cells to the right of the OU cell)
#then loop and apply each GPO to the OU until cells are empty
$GPO = $WorkSheet.Cells.Item($i+1, $j).Text

set-GPLink -Name $GPO -Target $destinationOU -LinkEnabled yes
i = i + 1
#Loop all OUs cells in column A and start again the process

1 Ответ

1 голос
/ 14 мая 2019

Я предлагаю это:

#Loop from row 1 to 13
for ($row = 1; $row -le 13; $row++) {

$destinationOU = $WorkSheet.Cells.Item($row, 1).Text 

#Read all the cells to right of column 2 (until an empty cell is found)
$col = 2   
while (($WorkSheet.Cells.Item($row, $col).Text) -ne "") {
    $GPO = $WorkSheet.Cells.Item($row, $col).Text
    set-GPLink -Name $GPO -Target $destinationOU -LinkEnabled yes
    $col++  
    }
}

Может быть безопаснее пройти через используемый диапазон:

for ($row = 1; $row -le $WorkSheet.UsedRange.Row.Count; $row++) {

$destinationOU = $WorkSheet.Cells.Item($row, 1).Text 

for ($col = 2; $col -le $WorkSheet.UsedRange.Columns.Count; $col++) {
    $GPO = $WorkSheet.Cells.Item($row, $col).Text
    set-GPLink -Name $GPO -Target $destinationOU -LinkEnabled yes
    }
}
...