如何循环Excel单元格

时间:2015-08-13 01:44:42

标签: excel loops powershell

我一直在使用PowerShell脚本从Excel单元格中使用net user /add添加用户。我认为它运作得很好。

cls
$FilePath = Read-Host 'Enter the file path to the Excel document'
$SheetName = Read-Host 'Enter the sheet name for the Excel document'

$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($FilePath)
$WorkSheet = $WorkBook.sheets.item($SheetName)

$AddUsers = {
  $Cell1 = Read-Host 'Enter the cell of the username'
  $Cell2 = Read-Host 'Enter the cell of the password'
  $Username = $WorkSheet.Range($Cell1).Text
  $Password = $WorkSheet.Range($Cell2).Text

  $correct = Read-Host 'Add user' $Username 'with password' $Password'?'

  if ($correct -contains 'yes') {
    cls
    net user $Username $Password /add /passwordchg:no
    $end2 = Read-Host "Continue adding users?"
    if ($end2 -contains 'yes') {
      cls
      &$AddUsers
    } else {
      cls
      Write-Host "End."
      Write-Host "Press any key to continue ..."
      $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
  }
  if ($correct -contains 'no') {
    cls
    $end = Read-Host "End Script?"
    if ($end -contains 'yes') {
      cls
      Write-Host "End."
      Write-Host "Press any key to continue ..."
      $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    } else {
      cls
      &$AddUsers
    }
  }
}

&$AddUsers

现在,我想自动化它。我不是每次都为usr和psword选择每个单元格,而是要说明要从哪个单元格开始,以及结束什么。

看起来有点像这样:

A1 B1

A2 B2

A3 B3

我希望能够说:从A1 B1开始,转到A3,B3。但是,我有一些问题。我正在考虑使用loop until,但我不知道如何使用单元格。这可能吗?如何将其设置为使用A1 B1,然后转到A2 B2?我知道如何做到这一点,但我不完全确定如何循环细胞。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这应该给你一个起点。替代方案是将AddUsers的这一方面,并​​将$ Username和$ Password作为参数传递给AddUsers函数。

$startAt = Read-Host 'Enter starting ROW (as in 1, Not A1)...? '
$endAt = Read-Host 'Enter ending ROW (again, not Cell just the row number)...? '

while ($startAt -le $endAt) {
   $Username = $WorkSheet.Cells.Item($statAt,1).Text
   $Password = $WorkSheet.Cells.Item($startAt,2).Text 
   # Add user or write to screen if you want to check the values
   $startAt++
}