stat-job to call a function not working when run from parent script

Iain Barnetson 106 Reputation points
2020-11-17T22:55:35.307+00:00

I'm trying to add a step to a script, that starts a backup job in a separate process, so the parent script will move onto the next step and not wait for the backup to complete.
When I run the step, see below, using the same uid that the parent runs under, the process works as expected and teh backup is done. But when the parent runs as a scheduled task, using the same uid, the step creates the job, as a job id is returned, but the backup is not done.
Any ideas why that would be?

$Func = {
Function DBRefresh-Backup
{
    param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$DestSrv,
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$DestDB
    )

    $SrvDest = $DestSrv.Split('\')[0]    
    $InstDest = $DestSrv.Split('\')[1]
    $SqlSafeCmd = "DECLARE @ResultCode  INT
    EXEC @ResultCode = [master].[dbo].[xp_ss_backup] 
        @database = N'$DestDB', 
        @filename = N'\\txdf2-nas-01\SQLBackups_No_IR\$SrvDest\$InstDest\$DestDB\%instance%_%database%_%backuptype%_%timestamp%.safe', 
        @backupname = N'`Full backup for policy $SrvDest\$InstDest > $InstDest`', 
        @compressionlevel = N'3', 
        @retrywrites = N'10 300 180', 
        @server = N'$SrvDest', 
        @instancename = N'$InstDest', 
        @bckdsttype = N'0', 
        @encryptedbackuppassword = N'<removed>', 
        @encryptiontype = N'AES256', 
        @includelogins = N'1', 
        @checksum = N'1', 
        @backupfiletype = N'0'

    IF(@ResultCode != 0)
        RAISERROR('One or more operations failed to complete.', 16, 1);"

        try {
            Invoke-SqlCmd -ServerInstance $DestSrv -Query $SqlSafeCmd -querytimeout 65535
        } catch {
            $ErrorMessage = $_.Exception.Message
            LogWrite $ErrorMessage
            Break
        }
}
}


Start-Job -Name "$($Ticket)_Backup" -InitializationScript $Func -ScriptBlock { param($DestSrv, $db) DBRefresh-Backup -DestSrv $DestSrv -DestDB $db } -ArgumentList($DestSrv,$db ) 
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,504 questions
{count} votes

Accepted answer
  1. Iain Barnetson 106 Reputation points
    2020-11-18T22:04:12.59+00:00

    I've found a work around, problem solved.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.