I am having an issue getting some code to work. I am creating a backup service that utilizes some custom objects. It is failing on the Start-Job line in the sense that it is not calling my custom BackupJob Start function. I’m assuming it’s a problem with context as I think Start-Job launches in a new context which would not know about BackupJob and thus would be unable to find the correct method to use. How can I use the current session’s context in subsequent jobs?
class Backup {
[BackupJob[]]$BackupJob
Backup([string] $configfile) {
Get-Content $configfile | Where-Object { $_ -notmatch "^#.*" } | ForEach-Object { $this.BackupJob += [BackupJob]::new($_) }
}
[void]Start() {
foreach ($job in $this.BackupJob) {
# The next line is where it's failing. I'm assuming because the new Job context doesn't include
# information it needs to know about the Backup and BackupJob objects.
Start-Job -Name $job.DisplayName -Scriptblock { $input.Start() } -InputObject $job
}
}
}
class BackupJob {
[string]$MountPoint
[string]$DisplayName
[string]$OutputPath
BackupJob([string] $configLine) {
$splitline = $configLine.split(";")
$this.MountPoint = $splitline[0]
$this.DisplayName = $splitline[1]
$this.OutputPath = $splitline[2]
}
[void]Start() {
# Do work here
}
}
So I did figure this out, but not sure if there might be a better way. This is what I came up with. Basically I’m importing this script into a variable $initscript and recreating the BackupJob object in the Start-Job context (the $script variable). Both of those variables are getting sent to Start-Process. Seems to work, but I wish there was a way to allow me to import the script as a scriptblock without having to remember to put semi-colons everywhere.
EDIT: I figured out the semicolon issue. When I load the backup script in to $initscript, I had to add -Raw so it preserved the newlines. Works perfectly now!