Repository: hashicorp/packer (Go)

Issue:
New powershell wrapping is broken in 1.14.1, $result is undefined
<!--- Please keep this note for the community --->

#### Community Note

* Please vote on this issue by adding a 👍 [reaction](https://blog.github.com/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/) to the original issue to help the community and maintainers prioritize this request
* Please do not leave "+1" or other comments that do not add relevant new information or questions, they generate extra noise for issue followers and do not help prioritize the request
* If you are interested in working on this issue or have submitted a pull request, please leave a comment

<!--- Thank you for keeping this note for the community --->

When filing a bug, please include the following headings if possible. Any
example text in this template can be deleted.

#### Overview of the Issue

The new in `packer>1.13.0` introduced powershell wrapping uses a _pre and a post template_ which includes an undefined variable `$result`. This variable is written to stdout at the end of every inline script. If you set somewhere in your script `$ErrorActionPreference = "Stop"` this undefined `$result` variable will stop the script execution and mark the packer build as failed.

#### Reproduction Steps

Create a new packer file with a powershell provisioner:

```hcl
# ...

  provisioner "powershell" {
    inline = [
      "dir"
    ]
  }

# ...
```

It will wrap the script on the target machine in a file similar to `C:\Windows\Temp\script-script-689da6c8-5353-6d50-c1b9-7b6f0e47a796.ps1`, which contains:
```ps1
	if (Test-Path variable:global:ProgressPreference) {
	  set-variable -name variable:global:ProgressPreference -value 'SilentlyContinue'
	}
	
	$exitCode = 0
	try {
	$env:PACKER_BUILDER_TYPE="hyperv-iso"; $env:PACKER_BUILD_NAME="core"; $env:PACKER_HTTP_ADDR="172.26.96.1:0"; $env:PACKER_HTTP_IP="172.26.96.1"; $env:PACKER_HTTP_PORT="0"; 

        # START of your powershell inline snippet
        dir
        # END of your powershell inline snippet
	
	$exitCode = 0
	} catch {
	Write-Error "An error occurred: $_"
	$exitCode = 1
	}
	
	if ($LASTEXITCODE -ne $null -and $LASTEXITCODE -ne 0) {
		$exitCode = $LASTEXITCODE
	}
	
	Write-Host $result
	exit $exitCode
```

### Packer version

From `packer version>=1.13.1` I assume, but this error has been captured on `packer version 1.14.1`. 

### Simplified Packer Template

Use one from the `packer` docs and add the following `powershell provisioner`:

```hcl
# ...

  provisioner "powershell" {
    inline = [
      "dir"
    ]
  }

# ...
```

### Operating system and Environment details

Running on Windows and hyperv, building Windows. amd64, trying to run `packer build` for Windows 11 Enterprise Evaluation.

### Log Fragments and crash.log files

Crash.log does not help, it just tells you the script execution failed. But if you log into the machine itself and check what has been written to the powershell stderr, you'll find this: 

```
PS C:\Users\Administrator> $Error
The variable '$result' cannot be retrieved because it has not been set.
At C:\Windows\Temp\script-689da6c8-5353-6d50-c1b9-7b6f0e47a796.ps1:99 char:13
+     Write-Host $result
+                ~~~~~~~
    + CategoryInfo          : InvalidOperation: (result:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined
```

And this is true, the variable `$result` has never been defined or initialized. 

## Workaround

Define `$result=""` in your powershell inline script or set `$ErrorActionPreference = "Continue"`.


Discussion:
1.13.x issues have been reverted on 1.14.0, so there is no powershell re-wrapping. Can you confirm which packer version are you using?
I don't see anywhere that these changes have been rolled back in the [CHANGELOG](https://github.com/hashicorp/packer/blob/main/CHANGELOG.md), it is just mentioned the default behavior was restored back to how it was in version 1.12.0. 

This wrapping is clearly done in packer 1.14.1 and the problematic code fragment is here: 
https://github.com/hashicorp/packer/blob/v1.14.1/provisioner/powershell/provisioner.go#L41-L63. As you see, `$result` has not been defined anywhere.
Just seen, it has been addressed - just now in https://github.com/hashicorp/packer/commit/4dd1fef5585866b79b6827d854fcf3ec65975700
I'm going to lock this issue because it has been closed for _30 days_ ⏳. This helps our maintainers find and focus on the active issues.
If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.



Patch:
diff --git a/provisioner/powershell/provisioner.go b/provisioner/powershell/provisioner.go
index a74a790a7c3..ea54c7576ac 100644
--- a/provisioner/powershell/provisioner.go
+++ b/provisioner/powershell/provisioner.go
@@ -58,8 +58,6 @@ const wrapPowershellString string = `
 	if ($LASTEXITCODE -ne $null -and $LASTEXITCODE -ne 0) {
 		$exitCode = $LASTEXITCODE
 	}
-	
-	Write-Host $result
 	exit $exitCode
 
 `


Test patch:
diff --git a/provisioner/powershell/provisioner_test.go b/provisioner/powershell/provisioner_test.go
index 7c9069ee91f..67dc49f4518 100644
--- a/provisioner/powershell/provisioner_test.go
+++ b/provisioner/powershell/provisioner_test.go
@@ -36,7 +36,7 @@ func TestProvisionerPrepare_extractScript(t *testing.T) {
 
 	// File contents should contain 2 lines concatenated by newlines: foo\nbar
 	readFile, err := os.ReadFile(file)
-	expectedContents := " \n\tif (Test-Path variable:global:ProgressPreference) {\n\t  set-variable -name variable:global:ProgressPreference -value 'SilentlyContinue'\n\t}\n\t\n\t$exitCode = 0\n\ttry {\n\t$env:PACKER_BUILDER_TYPE=\"\"; $env:PACKER_BUILD_NAME=\"\"; \n\tfoo\n\tbar\n\t\n\t$exitCode = 0\n\t} catch {\n\tWrite-Error \"An error occurred: $_\"\n\t$exitCode = 1\n\t}\n\t\n\tif ($LASTEXITCODE -ne $null -and $LASTEXITCODE -ne 0) {\n\t\t$exitCode = $LASTEXITCODE\n\t}\n\t\n\tWrite-Host $result\n\texit $exitCode\n\n"
+	expectedContents := "if (Test-Path variable:global:ProgressPreference) {\n         set-variable -name variable:global:ProgressPreference -value 'SilentlyContinue'\n         }\n         \n         $exitCode = 0\n         try {\n         $env:PACKER_BUILDER_TYPE=\"\"; $env:PACKER_BUILD_NAME=\"\"; \n         foo\n         bar\n         \n         $exitCode = 0\n         } catch {\n         Write-Error \"An error occurred: $_\"\n         $exitCode = 1\n         }\n         \n         if ($LASTEXITCODE -ne $null -and $LASTEXITCODE -ne 0) {\n         $exitCode = $LASTEXITCODE\n         }\n         exit $exitCode"
 	normalizedExpectedContent := normalizeWhiteSpace(expectedContents)
 	if err != nil {
 		t.Fatalf("Should not be error: %s", err)