title: Invoke-SqlCmd with either Windows Authentication OR SQL Authentication
body: <p>This code does what I need. But I am trying to replace a call to Invoke-SqlCmd with either Windows Authentication or SQL Authentication on the same line using some kind of switch.  Can someone help me with a more elegant way? I was thinking about Invoke-Expression but I don't get any good result out of it.</p>
  
  <pre><code>Function MyFunction{
      Param
      (
          [string]$S = "MyServer",
          [string]$U,
          [string]$P
      )
      # Find the SQL Engine version
      $Q = "select serverproperty('ProductVersion')"
  
      if($U)
      {
          $R = Invoke-Sqlcmd -ServerInstance $S -Query $Q -Username $U -Password $P -Verbose
          Write-Host "SQL Athenticated"
      }
      else
      {
          $R = Invoke-Sqlcmd -ServerInstance $S -Query $Q -Verbose
          Write-Host "Windows Athenticated"
      }
      return $R.column1
  }
  </code></pre>
  
  <p>Here is my Invoke-Expression. It just doesn't work...</p>
  
  <pre><code>Invoke-Expression "$R = Invoke-Sqlcmd -ServerInstance $S -Query $Q $(if($true){""-Username $U -Password $P""})"
  </code></pre>
  
  <p>Here is the elegant solution I was looking for. Thanks to Mike:</p>
  
  <pre><code>Function MyFunction{
      Param
      (
          [string]$S = "xps15",
          [string]$U,
          [string]$P
      )
      # Find the SQL Engine version
      $Q = "select serverproperty('ProductVersion')"
      $auth=@{}
      if($U){$auth=@{UserName=$U;Password=$P}}
      $R = Invoke-Sqlcmd -ServerInstance $S -Query $Q -Verbose @Auth
      return $R.column1
  }
  </code></pre>