简体   繁体   English

运行脚本时Powershell不创建注册表项

[英]Powershell not creating registry key when script is run

I am currently creating a powershell script in which the technicians can run to help apply various registry edits to create certain PCs which have automatic logins. 我当前正在创建一个Powershell脚本,技术人员可以在其中运行以帮助应用各种注册表编辑来创建某些具有自动登录功能的PC。 However, whenever I run my script the powershell has no issue when changing values with pre-existing keys, yet it will not create keys when using the "new-item" command. 但是,无论何时运行脚本,PowerShell都不会在使用预先存在的键更改值时出现问题,但是在使用“ new-item”命令时它不会创建键。 I was wondering whether anyone would have any idea as to why this would not create the registry key given that I receive no errors when run. 我想知道是否有人对运行时没有收到错误的原因为什么不创建注册表项有任何想法。

Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" –Name AutoAdminLogon -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name DefaultUserName -Value domain\TEST
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name DefaultPassword -Value TEST123
Test-Path –Path "HKLM:\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\Winlogon\ForceAutoLogon"
if ( -Not (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"))
{
New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name ForceAutoLogon  -Value 1
}

Test-Path is not designed for registy values. Test-Path不适用于注册值。 What you can do it use a Try/Catch block. 您可以使用Try / Catch块执行此操作。 You also need to Get/Set the itemPropery. 您还需要获取/设置itemPropery。

$Path = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
Try {
    Get-ItemProperty -Path $Path | Select-Object -ExpandProperty ForceAutoLogon -ErrorAction Stop | Out-Null
    Set-ItemProperty -Path $Path -Name ForceAutoLogon -Value 1
} Catch {
    New-ItemProperty -Path $Path -Name ForceAutoLogon -Value 1
}

If the Get-ItemProperty fails the the key must not exist. 如果Get-ItemProperty失败,则密钥必须不存在。 Then we can create it! 然后我们可以创建它! If Get-ItemProperty succeeds then we can ensure the value is set properly. 如果Get-ItemProperty成功,则可以确保正确设置该值。 I might be using the registry keywords wrong but let the code speak for itself. 我可能使用了错误的注册表关键字,但让代码说明了一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM