How to make the Powershell code dynamic

Sara 421 Reputation points
2024-08-24T12:42:46.0533333+00:00

I have a below line of code where, I want the MSSQL16 should be made dynamic I.e., it should be able to accept any other values ex: test.MSSQLSERVER

$Targetresource.Productkey = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL16.MSSQLSERVER\productkey’

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,504 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 46,551 Reputation points
    2024-08-24T15:27:22.1633333+00:00

    The easiest way would be to change those single quotes to double quotes and use variable interpolation.

    $targetname = "test"
    $Targetresource.Productkey = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$targetname.MSSQLSERVER\productkey"
    

    A more readable way might be to use the format operator "-f".

    $targetname = test
    $target = 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\{0}.MSSQLSERVER\productkey' -f $targetname
    $Targetresource.Productkey = Get-ItemProperty $target
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.