I am trying to find a way to stop the script from continuing to run when in lockdown mode or any other circumstances This script I'm using now does stop the script from continuing to run, however it only stops if the wrong credential or IP address is stated, it doesn't stop if the vSphere host is in lockdown mode. It will give this error (picture below) and still continuining to run the script with errors.
So this is the code I am using:
param (
[Parameter(Mandatory=$true)][string]$s,
[Parameter(Mandatory=$true)][string]$u,
[Parameter(Mandatory=$true)][string]$p
)
function connect-server {
#Connecting to server
Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue
$serverin = $s
$userin = $u
$passin = $p
$error.clear()
Connect-VIServer -Server $serverin -User $userin -Password $passin
$serverlist = $global:DefaultVIServer
if($serverlist -eq $null) {
write-host "No connected servers."
BREAK
} else {
foreach ($server in $serverlist) {
$serverName = $server.Name
if($serverName -eq $serverin){
write-Host "Connected"
scoringsystem
} else {
write-host "Something did not work right. Please try again"
}
}
}
}
Even if the server is not connected, the $global:defaultviserver will never be equal to empty.
It's a predefined variable, that exists when the PowerCLI modules or PSSnapin are loaded.
Try testing the IsConncted property, like this
if($global:DefaultVIServer.IsConnected){
Write-Host "Server connected"
}
else{
Write-Host "Server not connected"
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Even if the server is not connected, the $global:defaultviserver will never be equal to empty.
It's a predefined variable, that exists when the PowerCLI modules or PSSnapin are loaded.
Try testing the IsConncted property, like this
if($global:DefaultVIServer.IsConnected){
Write-Host "Server connected"
}
else{
Write-Host "Server not connected"
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
It works fine for wrong credentials/lockdown mode but when I plug out the LAN Cable, so it's not connected to the server physically, the script still runs.
Did you try combining the solution with a Try-Catch construct.
Try{
Connect-VIServer -Server MyVC -ErrorAction Stop
if($global:DefaultVIServer.IsConnected){
Write-Host "Server connected"
}
else{
Write-Host "Server not connected"
}
}
Catch{
Write-Host "Cannot connect to server"
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
