Listing 6.1 contains a bug.
if($Username -and $Password)
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password }
else
{ $connection = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver }
The $con variable is never used and should be changed to $connection.