Reputation: 1781
Code shortened for brevity:
Function Add-DatabaseUser
{
Param(
[Parameter(Mandatory=$true, Position = 0)]
[string] $samaccountname
,[Parameter(Position = 1)]
[string] $username = $null
)
if ($samaccountname -notmatch "[a-z0-9]*\\[a-z0-9]")
{
throw new [System::ArgumentException] "SAMAccountName was not in the correct format."
}
if($username -eq $null)
{
$username = $samaccountname
}
# Code omitted...
Try
{
Write-Host "Creating user..."
$user = New-Object ("Microsoft.SqlServer.Management.Smo.User") $database, $username
$user.Login = $login.Name
$user.Create() # Exception thrown.
}
Catch
{
# Code omitted.
}
The exception I get is as follows:
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
This is happening because the value of $username is null. Yet I have a if-statement at the very beginning of the script to check if it it's null, and if so, assign a value to it. But apparently the debugger evaluates $username -eq $null
to False.
Why is this?
Edit: Should probably mention this is how I'm calling the function in PowerShell:
Add-DatabaseUser -samaccountname "mycomputer\username"
Upvotes: 3
Views: 570
Reputation: 351
I believe this is because you are typecasting the username variable as a string, and then setting it to $null as a default value. The typecasting is causing it to become a null string, or "", which is different than $null.
Get rid of your typecast, or also evaluate :
if( [string]::IsNullOrEmpty($username) )
{
$username = $samaccountname
}
Edit:
Original answer was the following, but there is a better way:
if($username -eq $null -or $username -eq "" )
{
$username = $samaccountname
}
Upvotes: 3