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

如何在Excel中循环以将GPOs列表应用于Powershell中的OU,powershell,gpo,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

我需要遍历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
我建议:

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

代码中没有循环。循环类似于($i=0;$i-lt$sheet.Cells.Count;$i++){#的
,但这里的代码类似于$destine=blablabla}
,您不需要增加$i,它已经在循环中定义了。只需谷歌如何在PowerShell中执行for循环谢谢,但我已经测试了一些,我被卡住了,我在没有任何循环的情况下展示了代码,但对我希望实现的目标发表了评论。非常感谢Benoit,我能够在您的帮助下使其正常工作。非常感谢您的帮助:-)祝您有愉快的一天