Skip to content

Invoke-VMScript

VMware: Runs a script in the guest OS of the specified virtual machine

#Requires -Version 5.1
#Requires -Modules VMware.VimAutomation.Core
[CmdletBinding(DefaultParameterSetName = "byName")]
Param(
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$VIServer,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [pscredential]$VICredential,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [string]$VMId,
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$VMName,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$ScriptText,
    [Parameter(ParameterSetName = "byID")]
    [Parameter(ParameterSetName = "byName")]
    [pscredential]$GuestCredential,
    [Parameter(ParameterSetName = "byID")]
    [Parameter(ParameterSetName = "byName")]
    [ValidateSet('PowerShell', 'Bat', 'Bash')]
    [string]$ScriptType = "PowerShell",
    [Parameter(ParameterSetName = "byID")]
    [Parameter(ParameterSetName = "byName")]
    [int32]$ToolsWaitSecs = 20
)
Process {
    $vmServer = $null
    try {
        $vmServer = Connect-VIServer -Server $VIServer -Credential $VICredential -ErrorAction Stop
        $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        if ($PSCmdlet.ParameterSetName -eq "byID") {
            $machine = Get-VM -Server $vmServer -Id $VMId -ErrorAction Stop
        }
        else {
            $machine = Get-VM -Server $vmServer -Name $VMName -ErrorAction Stop
        }
        if ($null -eq $GuestCredential) {
            $result = Invoke-VMScript -VM $machine -Server $vmServer -ScriptText $ScriptText -ScriptType $ScriptType -ToolsWaitSecs $ToolsWaitSecs -Confirm:$false -ErrorAction Stop
        }
        else {
            $result = Invoke-VMScript -VM $machine -Server $vmServer -ScriptText $ScriptText -ScriptType $ScriptType -GuestCredential $GuestCredential -ToolsWaitSecs $ToolsWaitSecs -Confirm:$false -ErrorAction Stop
        }
        $result | Add-Member -NotePropertyName 'Timestamp' -NotePropertyValue $timestamp -Force
        Write-Output $result
    }
    catch { throw }
    finally { if ($null -ne $vmServer) { Disconnect-VIServer -Server $vmServer -Force -Confirm:$false -ErrorAction SilentlyContinue } }
}

IP address or DNS name of the vSphere server

PSCredential object for authenticating with the server

ID of the virtual machine

Name of the virtual machine

Text of the script to run

PSCredential for authenticating with the guest OS

Type of the script: PowerShell, Bat, or Bash

Seconds to wait for VMware Tools connection

An interactive directory of PowerShell scripts.