如何在Excel中循环以将GPO列表应用于Powershell中的OU

时间:2019-05-14 08:21:42

标签: powershell gpo

我需要遍历OU和GPO的Excel文件,然后将它们应用于GPO管理控制台。我为了解循环过程而感到困惑。

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 个答案:

答案 0 :(得分:1)

我建议这样做:

#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
    }
}