我有一个 PowerShell 脚本,我正在其中读取和编辑注册表。
我尝试手动运行它,从命令行调用它,使用
ps2exe
将其转换为 .exe,对于所有这些场景,它都按预期工作。但是,当我将其与安装程序一起打包(使用 MS Visual Studio 安装程序项目)并尝试以 Custom Actions/Commit/script.exe
运行它时,它突然找不到注册表项。
这是我的脚本片段。
## initializing new variables
$req_path = Get-Item -Path "HKCU:\SOFTWARE\Microsoft\Office\16.0\Excel\Options" |
Select-Object -ExpandProperty Property
echo $req_path
> ERROR: Get-Item : Cannot find path
> 'HKCU:\SOFTWARE\Microsoft\Office\16.0\Excel\Options' because it doesnot exist.
I have also tried this variation to no avail:
```ps
$req_path = Get-Item -Path Registry::HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Excel\Options |
Select-Object -ExpandProperty Property
由于这是安装程序的一部分,它以管理员身份运行,因此权限不是罪魁祸首。
那么,在将 PowerShell 脚本作为自定义操作运行时如何访问注册表项?
一些附加信息:
[Environment]::Is64BitProcess
返回True
WhoAmI
返回nt authority\system
考虑到我不是powershell方面的专家,很有可能有更好的方法或者至少我的实现不是最有效的,但我找到了一种方法。
## HKCU is not accessible when running the script from nt\ authority system
## Hence, accessing the HKU/SID for the current user
## finding current user's SID
## list of profiles
$profileIP =
(Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*") |
Select-Object ProfileImagePath
$profileIP = $profileIP.ProfileImagePath
## list of SIDs
$SIDs =
(Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\") |
Select-Object Name
$SIDs = (Split-Path $SIDs -Leaf).Trim("{}")
## finding the SID for the current user
$sid_index = 0
foreach ($entry in $profileIP) {
if ($entry.ToString().ToUpper().Contains($env:USERNAME)){break}
$sid_index += 1
}
$CU_SID = $SIDs[$sid_index]
## initiating HKU for this instance of powershell
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
## Get items under SOFTWARE\Microsoft\Office\16.0\Excel\Options
$req_ref = -join @("HKU:\",$CU_SID,"\SOFTWARE\Microsoft\Office\16.0\Excel\Options")
$req_path = Get-Item -Path $req_ref |
Select-Object -ExpandProperty Property