Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

powershell - Script environment affects parent shell

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  • save the previously current culture beforehand
  • restore that culture afterwards.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...