Share via

How to make the Powershell code dynamic

Sara 441 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 for business | Windows Server | User experience | PowerShell
0 comments No comments

1 answer

Sort by: Most helpful
  1. Rich Matheisen 48,116 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
    

    Was this answer helpful?

    0 comments No comments

Your answer

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