I am using Poweshell to view the status of specific SQL job. I want to pass job name as input like read-host or pass through variable. The script works fine when job name is static string in qoutes(Script 1) .In case I pass it through variable, it does not work.
If I loop through each job in Jobs and compare the job name with where-object comparison to string it works fine. That's not good way as we have 100s of jobs with second script I am getting error. Error-
Cannot index into a null array. At C:\Check status test.ps1:22 char:31 + $job = $server.JobServer.Jobs[ <<<< $job_to_check]
+ CategoryInfo : InvalidOperation: (CDSMaint:String) [], RuntimeException + FullyQualifiedErrorId : NullArray
Can anyone guide how I can have $job variable containing the object for job with name $job_to_check Any hint,guidance is highly appreciated.
Script 1:
$sqlserver="server1"
#$job_to_check='Job1'
$script:username='user1'
$script:pass_word='password'
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver;
$srv.ConnectionContext.LoginSecure=$false
$srv.ConnectionContext.set_login($username)
$srv.ConnectionContext.set_password($pass_word)
if ( $job_to_check -eq $null)
{
Write-Host "Job is null"
}
$job = $server.JobServer.Jobs["Job1"]
echo $job.Name
Script2:
$sqlserver="server1"
$job_to_check='Job1'
$script:username='user1'
$script:pass_word='password'
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver;
$srv.ConnectionContext.LoginSecure=$false
$srv.ConnectionContext.set_login($username)
$srv.ConnectionContext.set_password($pass_word)
if ( $job_to_check -eq $null)
{
Write-Host "Job is null"
}
$job = $server.JobServer.Jobs[$job_to_check]
echo $job.Name