Try catch block doesn't hit during Task Sequence

45 Views Asked by At

I have a peculiar situation where the try catch block doesn't hit in the script I have made.

Start-Transcript -Path C:\Trans.txt -Force -IncludeInvocationHeader
try
{
    $CDBJson = Get-Content -Path "C:\_SMSTaskSequence\CDB\CDB_Values.json1" -Raw | ConvertFrom-Json -ErrorAction Stop
    
    #Rename-Computer -NewName $CDBJson.DeviceName -Force
    
    $TSEnv = New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction Stop
    $TSEnv.Value("OSDComputerName") = $CDBJson.DeviceName
    
    Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Control\Computername\Computername" -name "Computername" -value $CDBJson.DeviceName -ErrorAction Stop
    Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Control\Computername\ActiveComputername" -name "Computername" -value $CDBJson.DeviceName -ErrorAction Stop
    Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" -name "Hostname" -value $CDBJson.DeviceName -ErrorAction Stop
    Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" -name "NV Hostname" -value $CDBJson.DeviceName -ErrorAction Stop

    $exitCode = 0
}
catch
{
    $exitCode = 1
}

Write-output $exitCode

exit $exitCode

Stop-Transcript

I made a typo in the $CDBJson = Get-Content -Path "C:\_SMSTaskSequence\CDB\CDB_Values.json1" -Raw | ConvertFrom-Json -ErrorAction Stop to force it to fail, but when I look in my Trans.txt, I can see that it fails to find the content, but doesn't actually trigger the catch block.

Funnily enough, if I press F8 during the Task Sequence to open the CMD and run the script manually from there, it does hit the catch block and does what I expect it to do.

I am not sure if I am doing something wrong here, so any advise is much appreciated

0

There are 0 best solutions below