问题
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