永久 PowerShell 变量

问题描述:

有没有办法在 PowerShell 中定义一个变量,这样当我打开一个新的 PowerShell 窗口时,它会保持相同的值?

Is there a way to define a variable in PowerShell so when I open up a new PowerShell window, it'll keep the same value?

我需要这个变量来保持它的值,因为我需要时不时地重新启动我的服务器,而且我不想丢失这些值.

I'll need this variable to keep its value, because I'll be needing to reboot my server every now and then, and I don't want to lose these values.

您是否考虑过其他替代来源来存储变量?PowerShell 中的变量通常仅在 PowerShell 会话本身期间持续存在.但是,PowerShell 可以轻松查询其他几个源,这些源旨在持续更长时间.特别是注册表和文件系统.

Have you considered other alternate sources for storing the variable? Variables in PowerShell are generally meant to persist only as long as the PowerShell session itself. However there are several other sources that PowerShell can easily query that are meant to persist longer. In particular the registry and file system.

对于一个在重启后持续存在的变量,我会将其存储在注册表中,然后使用 PowerShell 查询该值(可能缓存在会话变量中).

For a variable meant to persist across reboots I would store it in the registry and then use PowerShell to query that value (perhaps cache in a session variable).