Problem replace constant with variable

This topic contains 2 replies, has 2 voices, and was last updated by  Ja Le 2 years, 8 months ago.

  • Author
  • #30549

    Ja Le

    I have two problems:

    I try to start a PERL program from a PowerShell. If I use a constant, it starts:

    $Job1 = Start-Job { & "C:/Temp/" 10 }

    If I try to construct my program name with a variable, it does not work:

    $Cmd = "C:/Temp/";
    $Job1 = Start-Job { & $Cmd 10 }

    My PERL program looks like this, it basically justs waits for the number of seconds received as a parameter:

    my $Delay = $ARGV[0];
    print "Start $Delay\n";
    sleep $Delay;
    print "End $Delai\n";

    When I start my PERL with this command, and I monitor the job's state, I would expect to see RUNNING for the duration of the execution of my PERL script, but the job indicates COMPETED after only 1-2 seconds:

    $Job1 = Start-Job { & "C:/Temp/" 10 }
    For ($i=1; $i -le 15; $i++)
    Start-Sleep -Seconds 1

    Why does it indicate completed right away, even when my jobs running a PERL program is still running?

  • #30558

    Sebastian Neumann

    The variable isn't inside the scriptblock "{ }". You need to pass the value with a param() block inside the scriptblock or use the $using: prefix.

  • #30562

    Ja Le

    OK, I am a newbie with PowerShell, I did not know { } created a new session where local variables where no longer available. Now I upgraded my program to this. It launches 3 instances of my PERL program, but it shows all 3 jobs as completed, while they are still running, SHY?

    Get-Job | Remove-Job

    $Cmd = "$PSScriptRoot\"
    Write-Host "Starting jobs`n";
    $Job1 = Start-Job { & $Using:Cmd 10 }
    $job2 = Start-Job { & $Using:Cmd 20 }
    $Job3 = Start-Job { & $Using:Cmd 30 }

    Write-Host "Waiting for jobs`n"
    for ($i=1; $i -le 15; $i++)
    Write-Host "— " $i
    Start-Sleep -Seconds 1

    Write-Host "Done`n"

You must be logged in to reply to this topic.