将列的多个数据从 xlsx 导入到 powershell cmd

Import multiples data of column from xlsx to a powershell cmd

在输入中: 我有一个 \users\myself\desktop\test\file.xslx 包含这样的倍数列:

ColumnA ColumnB ... ColumnQ(总共 17 列)

每一列都有一些数据。

在输出中:

我想要这样的 cmd :

New-ADUser -Name $(columnAdata) -GivenName "$(columnBdata)" -Surname "$(columnCdata)" -DisplayName "$(columnDdata)" -SamAccountName "$(columnEdata)" ... etc until -blabla "$(ColumnQdata)"

是否可以将列数据存储在变量中以将它们插入到命令中?

非常感谢。

我建议首先将列 headers 更改为与您打算用于 New-ADUser cmdlet 的参数相同。
匹配 headers 将大大有助于避免出错。

接下来,将您的 Excel 文件保存为 CSV,假设文件名为 NewUsers.csv

这样代码就可以非常简单易维护了:

# import the CSV file using the same separator character as Excel uses on your system
Import-Csv -Path 'X:\NewUsers.csv' -UseCulture | ForEach-Object {
    # use Splatting: create a Hashtable with all properties needed taken from the CSV
    # see: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting
    $userProperties = @{
       Name           = $_.Name       # as opposed to $_.columnAdata
       GivenName      = $_.GivenName  # as opposed to $_.columnBdata
       Surname        = $_.Surname
       DisplayName    = $_.DisplayName
       SamAccountName = $_.SamAccountName

       # etcetera
    }
    New-ADUser @userProperties
}