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.
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
}
Here is my Invoke-Expression. It just doesn't work...
Invoke-Expression "$R = Invoke-Sqlcmd -ServerInstance $S -Query $Q $(if($true){""-Username $U -Password $P""})"
Here is the elegant solution I was looking for. Thanks to Mike:
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
}
Invoke-Expressionbit at the end. If the later then why even mention the first blob? "It just doesn't work.." - in what way does it "just doesn't work?", do you get any error messages, if so why not post them. If you want folks to help you here then please learn how to ask a question because quite frankly I have no idea what you're asking: codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question - please don't waste our time.