Why is my $sqlResult variable acting like a global variable. I didn't expect that.
function Main
{
param([string] $arg1)
DoWork1 -arg1 $arg1
DoWork2
}
function DoWork1
{
param([string] $arg1)
$sqlResult = Invoke-Sqlcmd -Query 'select * from customer' -ServerInstance '(localdb)\MSSQLLocalDB' -Database 'Database1' -OutputAs DataTables
$sqlResult | Out-Host
}
function DoWork2
{
$sqlResult | Out-Host
}
Main -arg1 "Hello World"
CodePudding user response:
The only possible explanation for what you were experiencing was that $sqlResult
would be previously defined in the Parent Scope of your functions ($script:
scope), and DoWork2
was outputting said variable. In this case would be pretty confusing to see where the issue was because both $sqlResult
variables, the one in the script scope and the one receiving the output from your SQL query in DoWork1
function, happen to be objects with same properties and values.
In this example we can see the issue better:
function Main {
param([string] $arg1)
DoWork1 -arg1 $arg1; DoWork2
}
function DoWork1 {
param([string] $arg1)
$sqlResult = $arg1
$sqlResult
}
function DoWork2 { $sqlResult }
$sqlResult = 'something else'
Main -arg1 "Hello World"