Permanent PowerShell variable

无人久伴 提交于 2019-12-04 03:38:21

问题


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.


回答1:


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.

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




回答2:


To store:

$variable|export-clixml -path $Location

To retrieve:

$variable = import-clixml -path $Location

Put that in a function if you want it, something like:

function LoadTHEvariable($location)
{
    $global:variable = import-clixml -path $Location
}

$location obviously contains the place in the filesystem where do you want to store the variable.




回答3:


You could store your data in your PowerShell Profile.




回答4:


Consider using an environment variable.




回答5:


A variable is a container and you can create tell powershell that you want that container to be a file. ${c:\variableToKeep.txt} = 'I want to keep this value'

Everytime you want to get the value inside just call the variable ${c:\variableToKeep.txt}

You can put this file in a share folder or copy it between machines, and you can read and write that variable on any machine.



来源:https://stackoverflow.com/questions/8854831/permanent-powershell-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!