I'm trying to create a new snapshot in a powershell script that is running on system(s) that don't have PowerCLI installed. My thought is to use a PSSession to connect to a server that does have PowerCLI installed and run the New-SnapShot command in an Invoke-Command scriptblock. (Note: this process works for running SQL, SCOM and other modules on remote servers)
The problem I'm having is that the New-Snapshot command successfully creates the new snapshot, but then the PowerShell connection/session just hangs and never processes the next script line.
The script section looks like:
Param (
[string]$VCenterName,
[string]$VMName,
[string]$PowerCLIServer
)
$VCsession = New-PSSession -ComputerName "$PowerCLIServer";
$VCblock = {Import-Module VMware.VimAutomation.Core -DisableNameChecking;
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false;
Connect-VIServer -Server $using:VCenterName -Protocol https;
New-Snapshot -VM $using:VMName -Name Test -Confirm:$false;
Return 1;
};
Invoke-Command -Session $VCsession -ScriptBlock $VCblock;
When I run the script, the snapshot is created, but the '1' is never returned and the PowerShell session just hangs (never returns to the prompt).
The return does return the value, but just not in the ExitCode property. It is part of the ScriptOutput property.
See the difference
return 1
'@
Invoke-VMScript -VM MyVM -ScriptType Powershell -ScriptText $code | select *
You should use the exit statement to pouplate the ExitCode property of the Invoke-VMScript cmdlet.
Like this
exit 1
'@
Invoke-VMScript -VM MyVM -ScriptType Powershell -ScriptText $code | select *
The reason for this is that a return statement will go back to the caller.
In this case the powershell.exe that calls the script.
An exit will immediately leave the current context.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
The return does return the value, but just not in the ExitCode property. It is part of the ScriptOutput property.
See the difference
return 1
'@
Invoke-VMScript -VM MyVM -ScriptType Powershell -ScriptText $code | select *
You should use the exit statement to pouplate the ExitCode property of the Invoke-VMScript cmdlet.
Like this
exit 1
'@
Invoke-VMScript -VM MyVM -ScriptType Powershell -ScriptText $code | select *
The reason for this is that a return statement will go back to the caller.
In this case the powershell.exe that calls the script.
An exit will immediately leave the current context.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thanks for that. Using Exit instead of Return after the snapshot command fixed the problem.