PowerShell and MS Access database

余生颓废 提交于 2019-12-23 04:53:43

问题


We would like to create AD users with PowerShell. With CSV it's not a problem, it's easy with scripts. Next level we would like to create AD users with PowerShell and MS Access database. Now we have the following problem: we can read the Access database, we load it in an object, but when we start our script, it says it is a object and not a string.

So when we convert the object into a string, it loads all lines in the string and it creates one user with all names.

The PowerShell script is:

$DatabaseName = "c:\temp\Nordwind.mdb"
$Query = "SELECT * FROM Users "
$ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=$DatabaseName"
$Connection = New-Object System.Data.OleDb.OleDbConnection $ConnectionString
$Command  = New-Object System.Data.OleDb.OleDbCommand $Query, $Connection
$Connection.Open()
$Adapter = New-Object System.Data.OleDb.OleDbDataAdapter $Command
$Dataset = New-Object System.Data.DataSet
[void] $Adapter.Fill($DataSet)
$Connection.Close()
$x = Dataset.Tables
foreach ($u in $x) {
    New-ADUser -Name $u.name ...
}

This is the error in the PowerShell:

Cannot convert 'System Obejct[]' to the type 'System.String' required by Parameter 'String'.

We can convert with the lines

$Name = [string]u.name
New-ADUser -Name $Name ...

When we have 10 Users to add, it adds one user with the name from the ten. We need help to read and convert a single line from the Access database with PowerShell.


回答1:


A dataset contains a list of tables, so you're iterating over the tables in the dataset (even if it's just one table) when you need to iterate over the rows in the table(s).

Change this:

$x = Dataset.Tables
foreach ($u in $x) {
    New-ADUser -Name $u.name ...
}

into this:

$x = Dataset.Tables[0]
foreach ($u in $x) {
    New-ADUser -Name $u.name ...
}

and the problem should disappear.



来源:https://stackoverflow.com/questions/48259443/powershell-and-ms-access-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!