I am running a PowerShell GUI that calls different scripts. I'm currently using hardcoded paths such as:
function start-jobhere([scriptblock]$block) {
Start-Job -ArgumentList (Get-Location),$block {
Set-Location $args[0];
Invoke-Expression $args[1]
}
}
$handler_button1_Click = {
$job1 = start-jobhere {& K:\Uploader\Import\DataUploader.ps1} -Name "Uploader"
}
I tried to avoid it using:
$LocalPath = ($MyInvocation.MyCommand.Path).ToLower().Replace("datauploader.ps1", "")
$handler_button1_Click = {
$job1 = start-jobhere {& $LocalPath\DataUploader.ps1} -Name "Uploader"
}
But it doesn't seem to work. I have some scripts in the same folder and some are on a different harddrive. Is there a way to avoid the hardcoded paths?
You're passing a scriptblock to the function. The code inside the scriptblock doesn't know anything about variables in the rest of the script unless you make them known via the using
scope modifier:
$job1 = start-jobhere {& "$using:LocalPath\DataUploader.ps1"} -Name "Uploader"
With that said, if you want to run scripts anyway, why aren't you passing their path as a string to your function?
function start-jobhere([string]$Name, [string]$Script) {
Start-Job -Name $Name -ScriptBlock {
Set-Location $args[0]
& $args[1]
} -ArgumentList (Get-Location), $Script
}
$handler_button1_Click = {
$job1 = start-jobhere "$LocalPath\DataUploader.ps1" -Name "Uploader"
}