My job seems to be hanging when opening an SQL connection. An example that reproduces the issue is as follows:
$myJob = start-job -ScriptBlock {
$connection_string = [string]::Format("Data Source={0};Initial Catalog={1};User ID={2}; Password={3};Connection Timeout=5", "my_sql_server", "my_database", "my_user", "my_password");
$connection = New-Object System.Data.SqlClient.SqlConnection -ArgumentList $connection_string;
Write-Output "Opening Connection...";
$connection.Open();
Write-Output "Connection Opened!";
}
When I look at $myJob, it is always in the state of Running, with the output “Opening Connection…”. If I run the same code outside of a job block, it runs fine.
How do I correctly open SqlConnection inside of a job?
EDIT:
Here are the properties of $myJob:
PS C:\Documents and Settings\agprax>>> $myJob
Id Name State HasMoreData Location Command
-- ---- ----- ----------- -------- -------
3 Administrator Running True localhost ...
Here is the job’s output:
PS C:\Documents and Settings\agprax>>> Receive-Job $myJob
Opening Connection...
What OS are you running this job from? It is worth noting there is a bug submitted on Connect that appears to be related to the issue you are having.
https://connect.microsoft.com/PowerShell/feedback/details/499499/adding-a-snapin-add-pssnapin-from-within-a-job-start-job-causes-job-to-hang-indefinitely