Skip to content

Instantly share code, notes, and snippets.

@mattvanstone
Created January 29, 2016 18:26
Show Gist options
  • Select an option

  • Save mattvanstone/7bd2be6385d2efcf1ce2 to your computer and use it in GitHub Desktop.

Select an option

Save mattvanstone/7bd2be6385d2efcf1ce2 to your computer and use it in GitHub Desktop.
Set-SSH PowerCLI Function - Start/Stop the ESXi SSH service from PowerCLI
<#
.SYNOPSIS
Start or stop SSH on an ESXi host
.DESCRIPTION
Takes a hostname or a piped Get-VMHost object starts or stops the SSH service depending on the value of the State parameter
.PARAMETER VMHost
The name of a host to start ssh on or a VMHost object
.PARAMETER State
State to set the SSH service to. Valid values are Start or Stop
.EXAMPLE
Start-SSH esx01.domain.com Start
.EXAMPLE
Start-SSH esx01.domain.com Stop
.EXAMPLE
Get-VMHost esx01.domain.com | Set-SSH -State Start
.EXAMPLE
Get-VMHost esx0* | Set-SSH -State Start
.EXAMPLE
$VMHost = Get-VMHost esx0*
Set-SSH $VMHost -State Stop
#>
Function Set-SSH {
[CmdletBinding()] Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]$VMHost,
[Parameter(Mandatory=$True)][ValidateSet("Start","Stop")][String]$State
)
Process {
# Check if VMHost input is a string, if so get VMHost Object then pipe to Set-SSH again so that process block is run for each item
if ($VMHost.GetType().Name -eq "String") {
$VMHostObj = Get-VMHost $VMHost -ErrorAction SilentlyContinue
if (!$VMHostObj) {
Write-Warning "Could not get host $VMHost"
break
} else {
$VMHostObj | Set-SSH -State $State
}
} else {
$VMHost = $_
$VMHost | Get-VMHostService | Where {$_.key -like "TSM-SSH"} | % {
if ($State -eq "Start") {
if (-not $_.running) {
$_ | Start-VMHostService -Confirm:$false | Select VMHost,Label,Running
} else {
$VMHost | Get-VMHostService | Where {$_.key -like "TSM-SSH"} | Select VMHost,Label,Running
}
}
if ($State -eq "Stop") {
if ($_.running) {
$_ | Stop-VMHostService -Confirm:$false | Select VMHost,Label,Running
} else {
$VMHost | Get-VMHostService | Where {$_.key -like "TSM-SSH"} | Select VMHost,Label,Running
}
}
}
}
}
}
@tonto22
Copy link

tonto22 commented Jul 19, 2016

I love this. Thanks for sharing. I had a SSH 1-liner I've used for years, but this is so clean and I can pipe it with other cmdlets. Did I say I love this function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment