Reputation: 316
Modifying certain aspects in PowerShell scripts seem to modify the running shell. This would be expected if I source the script instead of running it.
script.ps1
[cultureinfo]::currentculture = [cultureinfo]::InvariantCulture
Set-PSDebug -Trace 1
> [cultureinfo]::currentculture
LCID Name DisplayName
---- ---- -----------
1031 de-DE Deutsch (Deutschland)
> .\script.ps1
> [cultureinfo]::currentculture
DEBUG: 1+ >>>> [cultureinfo]::currentculture
LCID Name DisplayName
---- ---- -----------
127 Unveränderliche Sprache (Unveränderliches Land bzw. unveränderliche Region)
So obviously debug tracing is active and cultural change persisted...
Upvotes: 3
Views: 526
Reputation: 437803
From the docs for [cultureinfo]::currentculture]
(emphasis added):
Gets or sets the CultureInfo object that represents the culture used by the current thread.
That is, a change by design takes effect for the entire thread, not just your script, and it persists throughout the thread's lifetime (after your script exits) or until you change it again.
Therefore, if you want your culture changes to be scoped, you must manually:
Caveat:
In Windows PowerShell, the culture is automatically reset to the startup value, but only at the command prompt, after every invocation of a command or script - see this answer for background information and a workaround; by contrast, if one script calls another and the callee changes the current culture, that change stays in effect for the calling script.
By contrast, PowerShell Core behaves consistently, and never resets the current culture automatically.
Note that the behavior is similar to using Set-Location
(cd
) to change the current location (directory), which also affects the entire thread, as it does in a cmd.exe
batch file (except if you use setlocal
) - but not in a Bash script, for instance.
In PowerShell, script files (*.ps1
) run in-process, as do batch files (*.cmd
, *.bat
) in cmd.exe
, whereas POSIX-like shells such as Bash run scripts in a child process, which implicitly and invariably scopes environment changes to such scripts.
Upvotes: 6