【问题标题】:Import multiples data of column from xlsx to a powershell cmd将列的倍数数据从 xlsx 导入到 powershell cmd
【发布时间】:2020-08-22 20:53:17
【问题描述】:

在输入: 我有一个 \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)"

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

非常感谢。

【问题讨论】:

  • 如果将 Excel 文件保存为 CSV(逗号分隔值)文件会容易得多,因此您可以使用 PowerShell 的 Import-Csv cmdlet。
  • 这是我在这里求助的原因:)

标签: excel powershell variables store xls


【解决方案1】:

我建议首先将列标题更改为与您打算用于 New-ADUser cmdlet 的参数相同。
拥有匹配的标题将大大有助于不犯错误。

接下来,将您的 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
}

【讨论】:

    猜你喜欢
    • 2020-07-24
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多