簡體   English   中英

從 Powershell 設置用戶環境變量以 SYSTEM 身份運行

[英]Set User Environment Variable from Powershell running as SYSTEM

背景(操作系統:Windows 10):

  • 我有 Powershell 腳本作為SYSTEM運行(在后台)

  • 通過 Powershell 腳本我需要設置機器和登錄的用戶環境變量

  • 機器變量使用[Environment]::SetEnvironmentVariable('NAME', 'Value', 'Machine')設置並按預期工作

  • 使用[Environment]::SetEnvironmentVariable('NAME1', 'Value1', 'User')設置的用戶變量不適用於最終用戶帳戶,因為進程以 SYSTEM 身份運行

  • Powershell 腳本執行需要至少一個用戶登錄,這工作正常

我能夠找到登錄用戶: $current_user = (Get-WmiObject -Class Win32_ComputerSystem).UserName.Split('\')[1]

我嘗試使用注冊表更新來設置登錄的用戶變量,但這不能按預期工作: Set-ItemProperty -Path 'HKCU:\Environment' -Name 'NAME2' -Value 'Value2' -Force

如何從以 SYSTEM 身份運行的 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

對於在 SYSTEM 帳戶下運行的故障排除腳本,我建議使用PSExec ,請參閱: this answer
如果您用戶的注冊表配置單元尚未加載,則需要加載在完成后卸載它),請參閱: Powershell REG LOAD 命令不起作用

要查找用戶的 hive(路徑由用戶的 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 

除了接受的答案之外,如果您想知道如何獲取本地系統帳戶之一(如SYSTEM )的 SID,請參閱下表或點擊 此鏈接以獲取Well Known SID的完整列表:

SID 姓名 描述
S-1-5-18 本地系統 操作系統使用的服務帳戶 (SYSTEM)。
S-1-5-19 北領地管理局 本地服務
S-1-5-20 北領地管理局 網絡服務

要為本地SYSTEM用戶創建用戶變量,命令如下:

# set environment variable 'NAME2' for the local SYSTEM user
Set-ItemProperty -Path "Registry::HKEY_USERS\S-1-5-18\Environment" -Name 'NAME2' -Value 'Value2' -Type String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM