Windows 从作为系统运行的Powershell中设置用户环境变量
背景(操作系统:Windows 10):Windows 从作为系统运行的Powershell中设置用户环境变量,windows,powershell,environment-variables,Windows,Powershell,Environment Variables,背景(操作系统:Windows 10): 我有一个Powershell脚本,它作为SYSTEM 通过Powershell脚本,我需要设置机器和登录的用户环境变量 使用[Environment]:SetEnvironmentVariable('NAME','Value','Machine')设置机器变量,并按预期工作 使用[Environment]:SetEnvironmentVariable('NAME1','Value1','User')设置的用户变量不适用于最终用户帐户,因为进程作为系统运
- 我有一个Powershell脚本,它作为
SYSTEM
- 通过Powershell脚本,我需要设置机器和登录的用户环境变量
- 使用
设置机器变量,并按预期工作[Environment]:SetEnvironmentVariable('NAME','Value','Machine')
- 使用
[Environment]:SetEnvironmentVariable('NAME1','Value1','User')设置的用户变量不适用于最终用户帐户,因为进程作为系统运行
- Powershell脚本执行需要至少一个用户登录,并且运行正常
$current\u user=(获取WmiObject-Class Win32\u ComputerSystem)。UserName.Split('\')[1]
我尝试使用注册表更新来设置登录的用户变量,但这无法按预期工作:
Set ItemProperty-Path'HKCU:\Environment'-Name'NAME2'-Value'Value2'-Force
如何从作为系统运行的powershell脚本中设置登录用户环境变量?要为当前登录的用户(不是运行代码的用户)设置注册表值,需要找到用户SID 试试这个:
# get the domain and username for the currently logged on user
$domain, $userName = (Get-WmiObject -Class Win32_ComputerSystem).UserName -split '\\', 2
# next, get the SID for that current user
$user = [System.Security.Principal.NTAccount]::new($domain, $userName)
$sid = $user.Translate([System.Security.Principal.SecurityIdentifier]).Value
# set the registry value for this user.
Set-ItemProperty -Path "Registry::HKEY_USERS\$sid\Environment" -Name 'NAME2' -Value 'Value2' -Type String
# See: https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registryvaluekind?redirectedfrom=MSDN
# for other RegistryValueKind values for parameter Type
有关在系统帐户下运行的脚本的疑难解答,建议使用,请参阅:。
如果尚未加载用户的注册表配置单元,则需要加载(完成后卸载),请参阅: 要查找用户的配置单元(路径由用户的SID标识)并设置环境变量:
$UserHive = Get-ChildItem -Path 'Registry::\HKEY_USERS' |
Where-Object {(Test-Path "Registry::$_\Volatile Environment") -and (Get-ItemProperty "Registry::$_\Volatile Environment").USERNAME -eq $Username}
Set-ItemProperty -Path "Registry::$UserHive\Environment" -Name 'NAME2' -Value 'Value3' -Force
搜索“powershell模拟用户”,这可能会使您走上正轨。我认为您不需要模拟,只需将用户配置单元加载到当前注册表中,请参见例如:。确保完成后也卸载蜂箱!。有关系统帐户下的疑难解答,请参阅。还要注意,您可能必须重新加载用户会话才能应用所做的更改。