Fix PowerShell scripts to support StrictMode (#1789)
Add `Set-StrictMode -Version latest` to PowerShell scripts. Initialize
`$EMSDK_PY` to `$null` and use `-ErrorAction SilentlyContinue` when
removing environment variables so execution under strict mode does not
fail on uninitialized variables or missing env items.
Fixes: #1337
diff --git a/emsdk.ps1 b/emsdk.ps1
index 111047f..835b1df 100644
--- a/emsdk.ps1
+++ b/emsdk.ps1
@@ -1,5 +1,9 @@
+Set-StrictMode -Version 3.0
+
$ScriptDirectory = Split-Path -parent $PSCommandPath
+$EMSDK_PY = $null
+
$PythonLocations = $(
"python\3.13.3_64bit\python.exe",
"python\3.9.2_64bit\python.exe",
@@ -32,9 +36,9 @@
# to set up the environment variables
if ($ExitCode -eq 0 -and (Test-Path $ScriptDirectory/emsdk_set_env.ps1)) {
& $ScriptDirectory/emsdk_set_env.ps1
- Remove-Item $ScriptDirectory/emsdk_set_env.ps1
+ Remove-Item $ScriptDirectory/emsdk_set_env.ps1 -ErrorAction SilentlyContinue
}
-Remove-Item Env:\EMSDK_POWERSHELL
+Remove-Item Env:\EMSDK_POWERSHELL -ErrorAction SilentlyContinue
exit $ExitCode
diff --git a/emsdk.py b/emsdk.py
index 9fda3a2..1137d97 100644
--- a/emsdk.py
+++ b/emsdk.py
@@ -2764,7 +2764,7 @@
def unset_env(key):
if POWERSHELL:
- return 'Remove-Item env:%s\n' % key
+ return 'Remove-Item env:%s -ErrorAction SilentlyContinue\n' % key
if CMD:
return 'set %s=\n' % key
if CSH:
diff --git a/emsdk_env.ps1 b/emsdk_env.ps1
index ab5fc4d..73fde17 100644
--- a/emsdk_env.ps1
+++ b/emsdk_env.ps1
@@ -1,2 +1,4 @@
+Set-StrictMode -Version 3.0
+
$ScriptDirectory = Split-Path -parent $PSCommandPath
& "$ScriptDirectory/emsdk.ps1" construct_env
diff --git a/test/test_activation.ps1 b/test/test_activation.ps1
index 31a2c8e..351912a 100644
--- a/test/test_activation.ps1
+++ b/test/test_activation.ps1
@@ -2,6 +2,8 @@
# and checks if the environment variables and PATH are correctly updated. Set $env:SYSTEM_FLAG and $env:PERMANENT_FLAG to test each.
# If no flag is provided the process/shell values are tested. See the CI file for an example.
+Set-StrictMode -Version 3.0
+
refreshenv
$repo_root = [System.IO.Path]::GetDirectoryName((resolve-path "$PSScriptRoot"))
diff --git a/test/test_bazel.ps1 b/test/test_bazel.ps1
index dc0393a..ab9439c 100644
--- a/test/test_bazel.ps1
+++ b/test/test_bazel.ps1
@@ -1,4 +1,5 @@
$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version 3.0
Set-Location bazel
diff --git a/test/test_path_preservation.ps1 b/test/test_path_preservation.ps1
index 0391b63..b13f08f 100644
--- a/test/test_path_preservation.ps1
+++ b/test/test_path_preservation.ps1
@@ -2,6 +2,8 @@
# and checks if parts of PATH are lost or overwritten. Set $env:SYSTEM_FLAG and $env:PERMANENT_FLAG to test each.
# If no flag is provided the process/shell values are tested. See the CI file for an example.
+Set-StrictMode -Version 3.0
+
refreshenv
$repo_root = [System.IO.Path]::GetDirectoryName((resolve-path "$PSScriptRoot"))