简体   繁体   中英

Powershell script start-job command error

I have the following powershell script:

#Executable and Argument
$command = "ExtractRunner.exe"
$argument = "-id 12"
#$argumentValue = "12"
#seconds the loop sleeps before launching next instance of above
$sleeptime = 0

$hour = get-date -UFormat “%H”
$hourstring = get-date -UFormat “%H”
$busystart = 8
$busyend = 16
$hour = [int]$hourstring

$currentpath = Get-Location
Set-Location -Path $currentpath
$currentpath = "$($currentpath)\$($command)"

Write-Host $currentpath

$block = {
  param($p1,$p2)
  start-process $p1 $p2
}
If (($hour -lt $busystart) -or ($hour -gt $busyend) ) {
  #run more frequently
  $sleeptime = 20

}
Else {
  #run less frequently
  $sleeptime = 40

} 


#counter
$i = 1

do {
  Write-Host $i
 #start-process $command $arguments -WindowStyle Hidden
  start-job $block -ArgumentList $currentpath, $argument
  get-job|Receive-Job
  Write-Host "sleeping $($sleeptime) Secs"
  Start-Sleep $sleeptime
  $i++
}
while ($i -le 50)
Write-Host "sleeping 600 secs"
Start-Sleep 600

The powershell start-job command executes an exe with parameters, this exe was coded in c#.

in the C# code (exe being executed in the start-job command) I have a line where I get the current path of the code which is currently in a bin folder. This works correctly when executing the exe manually by either clicking on it or with the exe name and parameters passed in a poweshell window.

C# code

 string assemblyPath = Path.Combine(Environment.CurrentDirectory, _dsSetup.EDI_MASTERS[0].ASSEMBLYNAME);
                Console.WriteLine( $"ASSEBMLY PATH ---- {assemblyPath}");
                Assembly testAssembly = Assembly.LoadFile(assemblyPath);

but once this is executed through the get-job command in poweshell, the Environment.CurrentDirectory is set to my document folder on my pc and not where the code is currently executing.

Why does this happen?

I've tried the Set-Location command but haven't had any luck with it, as I am new to powershell scripts I have no idea why this is happening.

"Current location" is not the same as "current directory". Look here .

What you can do is setting the current directory explicitly:

$block = {
  param($p1,$p2)
  [environment]::CurrentDirectory = (split-path $p1)
  start-process $p1 $p2
}

Or specify the WorkingDirectory parameter:

start-process $p1 $p2 -WorkingDirectry (Split-Path $p1)

Note: I would strongly recommend using more meaningful variable names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM