Search code examples
powershellif-statementregistryscriptblock

If Else within an Invoke-Command Powershell


I am trying to run the below command to say if this registry key exists then Get-ItemProperty Else Do nothing or Display Text for Testing.

"SQL Server Product Name" = Invoke-Command -ComputerName $Computer -ScriptBlock {If (Test-Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names") { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object -FilterScript { (($_.Publisher -like "Microsoft*") -and ($_.DisplayName -like "Microsoft SQL Server*(*-bit)")) } | Select-Object -first 1 -ExpandProperty DisplayName } else {Write-Host "Blah"}}

The Else doesn't seem to do anything because right now if the reg key does not exist, it puts in {} to the results instead of Blah. I am not exactly sure if the If statement is working at all since I think it may just be running the Get-ItemProperty no matter what since if that path exists, I get the expected results.


Solution

  • The issue with your example is that the Else scriptblock uses Write-Host. When you execute this on a remote machine, the Host is a PowerShell session on that remote computer. You're writing the text to a session with no GUI on a remote machine.

    To fix this, just remove the Write-Host cmdlet. The quoted text will be passed back to your local session along with anything else output by the scriptblock when it is executed on the remote session.