简体   繁体   English

如果在Invoke-Command Powershell中

[英]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. 我正在尝试运行以下命令,以说该注册表项是否存在,然后让Get-ItemProperty其他不执行任何操作或显示要测试的文本。

"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. Else似乎什么也没做,因为现在如果reg键不存在,它会将{}放到结果中,而不是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. 我不确定If语句是否可以正常工作,因为我认为不管该路径是否存在,它可能只是在运行Get-ItemProperty,因为我得到了预期的结果。

The issue with your example is that the Else scriptblock uses Write-Host . 您的示例的问题在于, Else脚本块使用Write-Host When you execute this on a remote machine, the Host is a PowerShell session on that remote computer. 在远程计算机上执行此操作时,主机是该远程计算机上的PowerShell会话。 You're writing the text to a session with no GUI on a remote machine. 您正在将文本写入到远程计算机上没有GUI的会话中。

To fix this, just remove the Write-Host cmdlet. 要解决此问题,只需删除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. 当在远程会话上执行脚本时,引用的文本将与脚本块输出的所有其他内容一起传递回本地会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM