nvoigt nvoigt - 1 year ago 109
Powershell Question

Why is the Logins property null?

I'm trying to add a Windows user to an SQL Server. This works fine. However, if the user is already there, I don't want to get an error. If it's already there, that's fine. So I thought I would just check before creating it:

$AccountName = $args[0]
$ComputerName = $args[1]
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$sqlSrv = New-Object 'Microsoft.SqlServer.Management.Smo.Server' ($ComputerName)


$login = $sqlSvr.Logins[$AccountName] # HERE .Logins IS NULL

if ($login -eq $null) {
$login = New-Object 'Microsoft.SqlServer.Management.Smo.Login' ($sqlSrv, $AccountName)
$login.Name = $AccountName
$login.LoginType = 'WindowsUser'
$login.PasswordPolicyEnforced = $false

I don't know why the
Property of the SQL Server class is null. I can see the existing logins in SQL Management Studio.

Can anybody tell me how to properly check if a login exists before creating it? With Roles and Databases, the Server's properties seem to be filled.

I'm using Sql Server Express Version 11.0.5058.0 (I think that's 2012) and Powershell Version is 5.0.10586.117.

Answer Source

Change this to this $sqlSvr.Logins to $sqlSrv.Logins

$sqlSvr.Logins to $sqlSrv.Logins
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download