I am somewhat new to PowerShell programming and have come accross something I can’t figure out.
I wrote the following script using ISE. It uses test-path to find out if a SQL database exists. If the database exists the code returns Yes, and No if the database does not exist.
This script executes just fine in the ISE environment and returns Yes no matter how many times it is run in the environment. However, when I run the exact same code in the console it returns Yes the first time, but then returns No every time after that.
If I close the console and reopen it I get the same behavior. Returns Yes the first time and No all other times.
What is interesting is if I comment out the lines in code that execute the 2 SQL snapins, the code returns No everytime. So its like in the console environment the second running of the code is ignoring the snapins.
I’ve also tried running the snappins without the if statements (ignoring the errors that result when they are exectuted the second and subsequant times) and I get the same results.
Further interesting is if I execute the same commands directly in the console without running any scipts it works as expected.
Any help from the Powershell gurus???
ScriptCode
#Add-PSSnapin “SqlServerCmdletSnapin100″
#Add-PSSnapin “SqlServerProviderSnapin100″
If ( (Get-PSSnapin -Name “SqlServerCmdletSnapin100″ -ErrorAction SilentlyContinue) -eq $null)
{ Add-PSSnapin “SqlServerCmdletSnapin100″ }
If ( (Get-PSSnapin -Name “SqlServerProviderSnapin100″ -ErrorAction SilentlyContinue) -eq $null)
{ Add-PSSnapin “SqlServerProviderSnapin100″ }
$dname = “test3″
$servername = “SP10SS-Test02″
$instance = “default”
$logicalName = $dbname
if(Test-Path “sqlserver:\sql\$servername\$instance\databases\$dbname”)
{
#Database Exists in SQL
“Yes”
}
else
{
#No database in SQL
“No”
}