dimanche 3 janvier 2021

Check if PowerShell Drive has been set with if else statement

I'm trying to make a PowerShell script to modify the Registry values that set the default application for the .ps1 file extension. Sadly I wasn't able to get very far with the script because the PSDrive didn't have a path for HKEY_CLASSES_ROOT didn't exist.

After finding the solution on the Microsoft website using:

New-PSDrive -PSProvider registry -Root 'HKEY_CLASSES_ROOT' -Name 'HKCR'

I then thought about including a bit of code to check if this PSDrive path had been set before continuing, and so now it appears at the top of the script as shown below:

#####
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

Unfortunately I can't get the IF statement to work.

Aucun commentaire:

Enregistrer un commentaire