我正在尝试制作一个 PowerShell 脚本来修改为.ps1
文件扩展名设置默认应用程序的注册表值。遗憾的是,由于 PSDrive 没有不存在的路径,所以我无法对脚本进行深入了解HKEY_CLASSES_ROOT
。
在 Microsoft 网站上使用以下方法找到解决方案后:
New-PSDrive -PSProvider registry -Root 'HKEY_CLASSES_ROOT' -Name 'HKCR'
然后我考虑在继续之前包含一些代码来检查是否已设置此 PSDrive 路径,因此现在它出现在脚本的顶部,如下所示:
#####
IF (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Host "Requesting administration privileges..."; Start-Sleep -s 2; Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
Write-Host "Administration privileges have been granted."
Start-Sleep -s 2
#####
Write-Host "Checking if 'HKEY_CLASSES_ROOT' path has been set...`n"
If (Get-PSDrive | Where{$_.Name -CMatch 'HKCR' -and $_.Root -CMatch 'HKEY_CLASSES_ROOT'}) {
Write-Output "Path has already been set"
} Else {
Write-Output "Path has not been set. Setting path now..."
New-PSDrive -PSProvider registry -Root 'HKEY_CLASSES_ROOT' -Name 'HKCR' >$Null 2>&1
}
Write-Host "`nDone"
Start-Sleep -s 2
Write-Host "Setting .PS1 (PowerShell scripts extension) file association with VS Code... " -NoNewLine
Set-ItemProperty -Path "HKCR:\Microsoft.PowerShellScript.1\Shell\Open\Command" -Name "(Default)" -Value {C:\Program Files\Microsoft VS Code\Code.exe "%1"}
Start-Sleep -s 2
Write-Host "Done"
Exit
不幸的是,我无法使以下 IF 语句起作用:
If (Get-PSDrive | Where{$_.Name -CMatch 'HKCR' -and $_.Root -CMatch 'HKEY_CLASSES_ROOT'}) {
Write-Output "Path has already been set"
} Else {
Write-Output "Path has not been set. Setting path now..."
New-PSDrive -PSProvider registry -Root 'HKEY_CLASSES_ROOT' -Name 'HKCR' >$Null 2>&1
}
在运行命令时,我总是会看到以下消息(“Else”语句),每次我重新运行脚本时,我都看不到“If”语句:
Path has not been set. Setting path now...
更新 1
第 2 行的一行代码是使用管理员权限提升 PowerShell 脚本。第 3 行和第 4 行是让用户知道脚本已被提升。
我尝试了你的代码Write-Output
而不是冗长的代码,但我仍然无法看到与“If”语句匹配的响应。
Write-Host "Checking if 'HKEY_CLASSES_ROOT' path has been set...`n"
If (Get-PSDrive |
Where {
($PSitem.Name -Match 'HKCR') -and
($PSitem.Root -Match 'HKEY_CLASSES_ROOT')
}
)
{Write-Output "Path has already been set"}
Else
{
Write-Output "Path has not been set. Setting path now..."
New-PSDrive -PSProvider registry -Root "HKEY_CLASSES_ROOT" -Name "HKCR" >$Null 2>&1
}
但是,如果我手动设置 PSDrive:
New-PSDrive -PSProvider registry -Root "HKEY_CLASSES_ROOT" -Name "HKCR" >$Null 2>&1
然后检查它是否存在:
PS D:\Users\Will> Get-PSDrive | Where{$_.Name -Match 'HKCR' -and $_.Root -Match 'HKEY_CLASSES_ROOT'}
Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
HKCR Registry HKEY_CLASSES_ROOT
这工作得很好。我只想让我的脚本检查这一点,如果尚未设置 PSDrive,请设置它。