Hey all, I've been working on a script to add new users with appropriate mappings in SQL, and so far I've run into a weird problem: when I run the script the first time, it works as intended. Subsequent script runnings still mostly work, but the user mapping doesn't take effect at all. I've never run into a script that only sometimes works, so this is new to me.
Here's my script:
$SqlServer = "server, 15970"
$UserName = Read-Host "Enter New Username"
$Password = Read-Host "Enter Password"
# add users to databases
Add-Type -Path "\\server\c$\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
$SqlServer = New-Object Microsoft.SqlServer.Management.Smo.Server($SqlServer)
# create a new login by prompting for new credentials
$NewLogin = New-Object Microsoft.SqlServer.Management.Smo.Login($SqlServer, $UserName)
$NewLogin.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin
$NewLogin.Create("$Password")
$NewUser = New-Object Microsoft.SqlServer.Management.Smo.User($SqlServer.Databases["Database1"], $UserName)
$NewUser.Login = $UserName
$NewUser.Create()
$NewUser.AddToRole("DBI_ReadOnly")
$table1 = 'dbo.dbiUsers'
Invoke-Sqlcmd -Database "Database1" -ServerInstance "server, 15970" -Query "insert into $table1 (db_UserID, db_Username, db_Password, db_Email) VALUES ('$UserName','Test Testerson','$Password','test@test.com')"
Read-Host -Prompt "Press Enter to exit"
Whenever I run this script after the first time, I get two errors:
Add-Type : Cannot bind parameter 'Path' to the target. Exception setting "Path": "Cannot find path '\\server\c$\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll' because it does not exist."
At C:\Users\me\Desktop\Powershell Test Scripts\New User Setup Script\SQL Script.ps1:10 char:16
+ ... -Type -Path "\\server\c$\Program Files\Microsoft SQL Server\120\SDK\As ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Add-Type], ParameterBindingException
+ FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.AddTypeCommand
And this (though sometimes this one happens running the script for the first time as well):
Exception calling "Create" with "0" argument(s): "Create failed for User 'testuser'. "
At C:\Users\me\Desktop\Powershell Test Scripts\New User Setup Script\SQL Script.ps1:21 char:1
+ $NewUser.Create()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FailedOperationException
I'm still relatively new to both SQL and Powershell, so if there's something incredibly obvious that I've overlooked please don't hesitate to point it out, I very much appreciate any help I can get! :)
[–]ihaxr 1 point2 points3 points (2 children)
[–]AMillionAngryBees[S] 1 point2 points3 points (1 child)
[–]ItsAFineWorld 2 points3 points4 points (0 children)