<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>infile Archives - LucD notes</title>
	<atom:link href="https://www.lucd.info/tag/infile/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.lucd.info/tag/infile/</link>
	<description>My PowerShell ramblings</description>
	<lastBuildDate>Fri, 23 Sep 2022 16:32:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://www.lucd.info/wp-content/uploads/2018/12/cropped-120px-Tibetan_Dharmacakra-32x32.png</url>
	<title>infile Archives - LucD notes</title>
	<link>https://www.lucd.info/tag/infile/</link>
	<width>32</width>
	<height>32</height>
</image> 
<atom:link rel="hub" href="https://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="https://pubsubhubbub.superfeedr.com"/><atom:link rel="hub" href="https://websubhub.com/hub"/>	<item>
		<title>Invoke-VMScriptPlus v3</title>
		<link>https://www.lucd.info/2019/11/17/invoke-vmscriptplus-v3/</link>
					<comments>https://www.lucd.info/2019/11/17/invoke-vmscriptplus-v3/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sun, 17 Nov 2019 16:10:55 +0000</pubDate>
				<category><![CDATA[Invoke-VMScriptPlus]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[powershellv6]]></category>
		<category><![CDATA[powershellv7]]></category>
		<category><![CDATA[sudo]]></category>
		<category><![CDATA[infile]]></category>
		<category><![CDATA[outfile]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=6437</guid>

					<description><![CDATA[My InvokeVMScriptPlus function serves me well while interacting with the guest OS on [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>My <strong>InvokeVMScriptPlus</strong> function serves me well while interacting with the guest OS on a VM. And I&#8217;m apparently not the only one that uses the function. This post introduces <strong>Invoke-VMScriptPlus v3</strong>.</p>



<p>The original <a rel="noreferrer noopener" aria-label="Invoke-VMScriptPlus (opens in a new tab)" href="https://www.lucd.info/2017/09/14/invoke-vmscriptplus/" target="_blank">Invoke-VMScriptPlus</a> post, and the addition of PS Core support, described in the <a rel="noreferrer noopener" aria-label="Invoke-VMScriptPlus v2 (opens in a new tab)" href="https://www.lucd.info/2018/08/05/invoke-vmscriptplus-v2/" target="_blank">Invoke-VMScriptPlus v2</a> post, keep being some of my most read posts. Time for another update.</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="575" height="516" src="https://www.lucd.info/wp-content/uploads/2019/11/invoke-plus-v3-1.png" alt="" class="wp-image-6551" srcset="https://www.lucd.info/wp-content/uploads/2019/11/invoke-plus-v3-1.png 575w, https://www.lucd.info/wp-content/uploads/2019/11/invoke-plus-v3-1-300x269.png 300w" sizes="(max-width: 575px) 100vw, 575px" /></figure>



<p>In this <strong>v3</strong> version, I introduce some new features to the function.</p>



<ul class="wp-block-list"><li><strong>PSv6</strong> and <strong>PSv7</strong>  support</li><li>Use <strong>files</strong> (input and output) from within your scripts</li><li>improved <strong>sudo</strong> support</li></ul>



<p><span style="background-color: #fae100;"><strong>Update July 2nd 2021</strong></span></p>
<ul>
<li>Fixed incorrect variable <strong>NameHost</strong></li>
<li>Added tests to detect <strong>IP</strong> or <strong>FQDN</strong> in URI</li>
<li>Updated test to check if type <strong>TrustAllCertsPolicy</strong> exists or not</li>
</ul>



<p><span style="background-color: #fae100;"><strong>Update April 15th 2020</strong></span></p>
<ul>
<li>Added <strong>SkipCertificateCheck</strong> switch</li>
</ul>



<p><span style="background-color: #fae100;"><strong>Update January 16th 2020</strong></span></p>
<ul>
<li>Bug fix which occured when connected to an ESXi node</li>
</ul>



<p></p>



<p><span style="background-color: #fae100;"><strong>Update November 18th 2019</strong></span></p>
<ul>
<li>Added <strong>NoIPinCert</strong> switch</li>
</ul>



<span id="more-6437"></span>



<h2 class="wp-block-heading">The Code</h2>



<pre class="lang:ps decode:true ">class MyOBN:System.Management.Automation.ArgumentTransformationAttribute {
    [ValidateSet(
      'Cluster', 'Datacenter', 'Datastore', 'DatastoreCluster', 'Folder',
      'VirtualMachine', 'VirtualSwitch', 'VMHost', 'VIServer'
    )]
    [String]$Type
    MyOBN([string]$Type) {
      $this.Type = $Type
    }
    [object] Transform([System.Management.Automation.EngineIntrinsics]$engineIntrinsics, [object]$inputData) {
      if ($inputData -is [string]) {
        if (-NOT [string]::IsNullOrWhiteSpace( $inputData )) {
          $cmdParam = "-$(if($this.Type -eq 'VIServer'){'Server'}else{'Name'}) $($inputData)"
          $sCmd = @{
            Command = "Get-$($this.Type.Replace('VirtualMachine','VM')) $($cmdParam)"
          }
          return (Invoke-Expression @sCmd)
        }
      } elseif ($inputData.GetType().Name -match "$($this.Type)Impl") {
        return $inputData
      } elseif ($inputData.GetType().Name -eq 'Object[]') {
        return ($inputData | ForEach-Object {
            if ($_ -is [String]) {
              return (Invoke-Expression -Command "Get-$($this.Type.Replace('VirtualMachine','VM')) -Name <code>$_")
            } elseif ($_.GetType().Name -match "$($this.Type)Impl") {
              $_
            }
          })
      }
      throw [System.IO.FileNotFoundException]::New()
    }
  }
  function Invoke-VMScriptPlus {
    &lt;#
  .SYNOPSIS
  Runs a script in a Linux guest OS.
  The script can use the SheBang to indicate which interpreter to use.
  .DESCRIPTION
  This function will launch a script in a Linux guest OS.
  The script supports the SheBang line for a limited set of interpreters.
  .NOTES
  Author:  Luc Dekens
  Version:
  1.0 14/09/17  Initial release
  1.1 14/10/17  Support bash here-document
  2.0 01/08/18  Support Windows guest OS, bat &amp; powershell
  2.1 03/08/18  PowerShell she-bang for Linux
  2.2 17/08/18  Added ScriptEnvironment
  2.3 11/03/19  Resolve IP to FQDN to support certificate for ESXi node
  2.4 22/04/19  Switch to provide password inline to 'sudo' lines
  2.5 07/06/19  Switch WaitForToolsVersionChange to wait for a version change
  3.0 17/11/19  Added powershellv7 support, added InFile &amp; OutFile
  3.1 18/11/19  Added switch NoIPinCert
  3.2 15/04/20  Added switch SkipCertificateCheck
  3.3 02/07/21  Fixed issue with NameHost, added test for IP or FQDN, changed  type test TrustAllCertsPolicy
  .PARAMETER VM
  Specifies the virtual machines on whose guest operating systems
  you want to run the script.
  .PARAMETER GuestUser
  Specifies the user name you want to use for authenticating with the
  virtual machine guest OS.
  .PARAMETER GuestPassword
  Specifies the password you want to use for authenticating with the
  virtual machine guest OS.
  .PARAMETER GuestCredential
  Specifies a PSCredential object containing the credentials you want
  to use for authenticating with the virtual machine guest OS.
  .PARAMETER ScriptText
  Provides the text of the script you want to run. You can also pass
  to this parameter a string variable containing the path to the script.
  Note that the function will add a SheBang line, based on the ScriptType,
  if none is provided in the script text.
  .PARAMETER ScriptType
  The supported Linux interpreters.
  Currently these are bash,perl,python3,nodejs,php,lua,powershell,powershellv6,powershellv7
  .PARAMETER ScriptEnvironment
  A string array with environment variables.
  These environment variables are available to the script from ScriptText
  .PARAMETER GuestOSType
  Indicates which type of guest OS the VM is using.
  The parameter accepts Windows or Linux. This parameter is a fallback for
  when the function cannot determine which OS Family the Guest OS
  belongs to
  .PARAMETER CRLF
  Switch to indicate of the NL that is returned by Linux, shall be
  converted to a CRLF
  .PARAMETER Sudo
  Switch to convert all 'sudo' lines to an inline password 'sudo' line.
  Only taken into account when the GuestOSType is 'Linux'
  .PARAMETER KeepFiles
  Switch to indicate that the temporary files, the script and the output files,
  shall not be deleted.
  Only to be used for debugging purposes.
  .PARAMETER InFile
  One or more files that will be copied to the guest OS.
  These files will be copied to the directory from where the script will run
  and can be used from within the script.
  .PARAMETER InFile
  One or more files that will be copied from the guest OS after the script has ran.
  These files will be copied from the directory from where the script runs.
  .PARAMETER Server
  Specifies the vCenter Server systems on which you want to run the
  cmdlet. If no value is passed to this parameter, the command runs
  on the default servers. For more information about default servers,
  see the description of Connect-VIServer.
  .PARAMETER WaitForToolsVersionChange
  When the invoked code changes the version of the VMware Tools, this switch
  tells the function to wait till this version change is visible in the script
  .PARAMETER NoIPinCert
  When certificates are used that do not contain the IP address of the ESXi node
  as a Subject Alternative Name (SAN), this switch tells the function to convert
  the IP address in all URI used for file transfers, to a FQDN.
  .PARAMETER NoIPinCert
  When certificates are used that do not contain the IP address of the ESXi node
  as a Subject Alternative Name (SAN), this switch tells the function to convert
  the IP address in all URI used for file transfers, to a FQDN.
  .PARAMETER SkipCertificateCheck
  When a non-trusted certificate is used on the ESXi node that hosts the targetted
  VM, the transfer of files to and from the VM's Guest OS will fail.
  This switch tells the function to ignore invalid certificates on the ESXi node.
  .EXAMPLE
  $pScript = @'
  #!/usr/bin/env perl
  use strict;
  use warnings;
  print "Hello world\n";
  '@
  $sCode = @{
  VM = $VM
  GuestCredential = $cred
  ScriptType = 'perl'
  ScriptText = $pScript
  }
  Invoke-VMScriptPlus @sCode
  .EXAMPLE
  $pScript = @'
  print("Happy 10th Birthday PowerCLI!")
  '@
  $sCode = @{
  VM = $VM
  GuestCredential = $cred
  ScriptType = 'python3'
  ScriptText = $pScript
  }
  Invoke-VMScriptPlus @sCode
  .EXAMPLE
  $pScript = @'
  Get-Content -Path .\MyInput.txt | Set-Content -Path .\MyOutput.txt
  '@
  $sCode = @{
  VM = $VM
  GuestCredential = $cred
  ScriptType = 'powershellv7'
  ScriptText = $pScript
  InFile = 'C:\Test\MyInput.txt'
  OutFile = 'C:\Report\MyOutput.txt'
  }
  Invoke-VMScriptPlus @sCode
  #&gt;
    [cmdletbinding()]
    param(
      [parameter(Mandatory = $true, ValueFromPipeline = $true)]
      [MyOBN('VirtualMachine')]
      [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine[]]$VM,
      [Parameter(Mandatory = $true, ParameterSetName = 'TextScript')]
      [Parameter(Mandatory = $true, ParameterSetName = 'TextExe')]
      [String]$GuestUser,
      [Parameter(Mandatory = $true, ParameterSetName = 'TextScript')]
      [Parameter(Mandatory = $true, ParameterSetName = 'TextExe')]
      [SecureString]$GuestPassword,
      [Parameter(Mandatory = $true, ParameterSetName = 'CredScript')]
      [Parameter(Mandatory = $true, ParameterSetName = 'CredExe')]
      [PSCredential[]]$GuestCredential,
      [Parameter(Mandatory = $true, ParameterSetName = 'TextScript')]
      [Parameter(Mandatory = $true, ParameterSetName = 'CredScript')]
      [String]$ScriptText,
      [Parameter(Mandatory = $true, ParameterSetName = 'TextScript')]
      [Parameter(Mandatory = $true, ParameterSetName = 'CredScript')]
      [ValidateSet('bash', 'perl', 'python3', 'nodejs', 'php', 'lua', 'powershell',
        'powershellv6', 'powershellv7', 'bat', 'exe')]
      [String]$ScriptType,
      [Parameter(Mandatory = $true, ParameterSetName = 'TextExe')]
      [Parameter(Mandatory = $true, ParameterSetName = 'CredExe')]
      [string]$ExeName,
      [String[]]$ScriptEnvironment,
      [ValidateSet('Windows', 'Linux')]
      [String]$GuestOSType,
      [Switch]$CRLF,
      [Switch]$Sudo,
      [Switch]$KeepFiles,
      [MyOBN('VIServer')]
      [VMware.VimAutomation.ViCore.Types.V1.VIServer]$Server = $global:DefaultVIServer,
      [Switch]$WaitForToolsVersionChange,
      [String[]]$InFile,
      [String[]]$OutFile,
      [Switch]$NoIPinCert,
      [Switch]$SkipCertificateCheck
    )
    Begin {
      #region Helper functions
      function Send-GuestFile {
        [cmdletbinding()]
        param(
          [Parameter(Mandatory = $true)]
          [String]$File,
          [Parameter(Mandatory = $true, ParameterSetName = 'File')]
          [String]$Source,
          [Parameter(Mandatory = $true, ParameterSetName = 'Data')]
          [String]$Data
        )
        if ($PSCmdlet.ParameterSetName -eq 'File') {
          $Data = Get-Content -Path $Source -Raw
        }
        $attr = New-Object VMware.Vim.GuestFileAttributes
        $clobber = $true
        $fileInfo = $gFileMgr.InitiateFileTransferToGuest($moref, $auth, $File, $attr, $Data.Length, $clobber)
        if ($Server.ProductLine -eq 'embeddedEsx') {
          $fileInfo = $fileInfo.Replace('*', ([System.Uri]$server.ServiceUri).Host)
        }
        if ($NoIPinCert.IsPresent) {
          $ip = $fileInfo.split('/')[2].Split(':')[0]
          if ($ip -as [IPAddress]) {
            $hostName = Resolve-DnsName -Name $ip | Select-Object -ExpandProperty NameHost
            $fileInfo = $fileInfo.replace($ip, $hostName)
          }
        }
        $sWeb = @{
          Uri = $fileInfo
          Method = 'Put'
          Body = $Data
        }
        if ($SkipCertificateCheck.IsPresent) {
          if ($PSVersionTable.PSVersion.Major -lt 6) {
            [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
          } else {
            $sWeb.Add('SkipCertificateCheck', $true)
          }
        }
        Write-Verbose -Message "Copying $($PSCmdlet.ParameterSetName) to $File"
        $copyResult = Invoke-WebRequest @sWeb
        if ($copyResult.StatusCode -ne 200) {
          Throw "ScripText copy failed!</code>rStatus $($copyResult.StatusCode)<code>r$(($copyResult.Content | ForEach-Object{[char]$_}) -join '')"
        }
      }
      function Receive-GuestFile {
        [cmdletbinding()]
        param(
          [String]$Source,
          [String]$File
        )
        $fileInfo = $gFileMgr.InitiateFileTransferFromGuest($moref, $auth, $Source)
        if ($Server.ProductLine -eq 'embeddedEsx') {
          $fileInfo.Url = $fileInfo.Url.Replace('*', ([System.Uri]$server.ServiceUri).Host)
        }
        if ($NoIPinCert.IsPresent) {
          $ip = $fileInfo.Url.split('/')[2].Split(':')[0]
          if ($ip -as [IPAddress]) {
            hostName = Resolve-DnsName -Name $ip | Select-Object -ExpandProperty NameHost
            $fileInfo.Url = $fileInfo.Url.replace($ip, $hostName)
          }
        }
        $sWeb = @{
          Uri = $fileInfo.Url
          Method = 'Get'
        }
        if ($SkipCertificateCheck.IsPresent) {
          if ($PSVersionTable.PSVersion.Major -lt 6) {
            [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
          } else {
            $sWeb.Add('SkipCertificateCheck', $true)
          }
        }
        $fileContent = Invoke-WebRequest @sWeb
        if ($fileContent.StatusCode -ne 200) {
          Throw "Retrieve of script output failed!</code>rStatus $($fileContent.Status)<code>r$(($fileContent.Content | ForEach-Object{[char]$_}) -join '')"
        }
        if ($File) {
          $fileContent.Content | Set-Content -Path $File -Encoding byte -Confirm:$false
        } else {
          $fileContent.Content
        }
      }
      #endregion
      #region Set up guest operations
      $si = Get-View ServiceInstance -Server $Server
      $guestMgr = Get-View -Id $si.Content.GuestOperationsManager
      $gFileMgr = Get-View -Id $guestMgr.FileManager
      $gProcMgr = Get-View -Id $guestMgr.ProcessManager
      #endregion
      #region Set up shebang table
      $shebangTab = @{
        'bash' = '#!/usr/bin/env bash'
        'perl' = '#!/usr/bin/env perl'
        'python3' = '#!/usr/bin/env python3'
        'nodejs' = '#!/usr/bin/env nodejs'
        'php' = '#!/usr/bin/env php'
        'lua' = '#!/usr/bin/env lua'
        'powershellv6' = '#!/usr/bin/env pwsh'
        'powershellv7' = '#!/usr/bin/env pwsh-preview'
      }
      #endregion
      #region Handle SkipCertificateCheck (if used)
      if ($SkipCertificateCheck.IsPresent -and
        $PSVersionTable.PSVersion.Major -lt 6 -and
        -not ('TrustAllCertsPolicy' -as [Type])) {
        Add-Type @'
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
            return true;
        }
    }
'@
      }
      #endregion
    }
    Process {
      foreach ($vmInstance in $VM) {
        #region Test conditions for running script in guest OS
        if ($vmInstance.PowerState -ne 'PoweredOn') {
          Write-Error "VM $($vmInstance.Name) is not powered on"
          continue
        }
        $vmInstance.ExtensionData.UpdateViewData('Guest')
        if ($vmInstance.ExtensionData.Guest.ToolsRunningStatus -ne 'guestToolsRunning') {
          Write-Error "VMware Tools are not running on VM $($vmInstance.Name)"
          continue
        }
        if (-not $vmInstance.ExtensionData.Guest.GuestOperationsReady) {
          Write-Error "VM $($vmInstance.Name) is not ready to use Guest Operations"
          continue
        }
        $moref = $vmInstance.ExtensionData.MoRef
        #endregion
        #region Create Authentication Object (User + Password)
        if ('CredScript', 'CredExe' -contains $PSCmdlet.ParameterSetName) {
          $GuestUser = $GuestCredential.GetNetworkCredential().username
          $plainGuestPassword = $GuestCredential.GetNetworkCredential().password
        }
        if ('TextScript', 'TextExe' -contains $PSCmdlet.ParameterSetName) {
          $bStr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($GuestPassword)
          $plainGuestPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bStr)
        }
        $auth = New-Object VMware.Vim.NamePasswordAuthentication
        $auth.InteractiveSession = $false
        $auth.Username = $GuestUser
        $auth.Password = $plainGuestPassword
        #endregion
        #region Determine GuestOSType
        if (-not $GuestOSType) {
          Write-Verbose "No GuestOSType value provided. Trying to determine now."
          switch -Regex ($vmInstance.Guest.OSFullName) {
            'Windows' {
              Write-Verbose "It's a Windows guest OS"
              $GuestOSType = 'Windows'
              if (-not $ExeName -and 'bat', 'powershell', 'powershellv6', 'powershellv7' -notcontains $ScriptType) {
                Write-Verbose "Invalid scripttype provided"
                Write-Error "For a Windows guest OS the ScriptType can be Bat, PowerShell, PowerShellv6 or PowerShellv7"
                continue
              }
            }
            'Linux' {
              Write-Verbose "It's a Linux guest OS"
              $GuestOSType = 'Linux'
              if (-not $ExeName -and 'bat', 'powershell' -contains $ScriptType) {
                Write-Verbose "Invalid scripttype provided"
                Write-Error "For a Linux guest OS the ScriptType cannot be Bat"
                continue
              }
            }
            Default {
              Write-Verbose "Can't determine guest OS type."
              Write-Error "Unable to determine the guest OS type on VM $($vmInstance.Name)"
              Write-Error "Try using the GuestOSType parameter."
              continue
            }
          }
        }
        if ($GuestOSType -eq 'Linux') {
          Write-Verbose "Seems to be a Linux guest OS"
          # Test if code contains a SheBang, otherwise add it
          $targetCode = $shebangTab[$ScriptType]
          if ($ScriptText -notmatch "^$($targetCode)") {
            Write-Verbose "Add SheBang $targetCode"
            $ScriptText = "$($targetCode)</code>n<code>r$($ScriptText)"
          }
          # Take care of the 'sudo' switch
          if ($Sudo) {
            Write-Verbose "Setting up sudo usage"
            $ScriptText = ($ScriptText | ForEach-Object -Process {
                $_ -replace 'sudo', "echo $plainGuestPassword | sudo -S"
              })
          }
        }
        #endregion
        #region Create a temp directory
        $tempFolder = $gFileMgr.CreateTemporaryDirectoryInGuest($moref, $auth, "$($env:USERNAME)_$($PID)", $null, $null)
        Write-Verbose "Created temp folder in guest OS $tempFolder"
        #endregion
        #region Create temp file for script
        $suffix = ''
        if ('bat', 'exe' -contains $ScriptType) {
          $suffix = ".cmd"
        }
        if ('powershell', 'powershellv6', 'powershellv7' -contains $ScriptType) {
          $suffix = ".ps1"
        }
        Try {
          $tempFile = $gFileMgr.CreateTemporaryFileInGuest($moref, $auth, "$($env:USERNAME)_$($PID)", $suffix, $tempFolder)
          Write-Verbose "Created temp script file in guest OS $tempFile"
        } Catch {
          Write-Verbose "Encountered a problem creating the script file in the guest OS"
          Throw "$error[0].Exception.Message"
        }
        #endregion
        #region Create temp file for output
        Try {
          $tempOutput = $gFileMgr.CreateTemporaryFileInGuest($moref, $auth, "$($env:USERNAME)_$($PID)_output", $null, $tempFolder)
          Write-Verbose "Created temp output file in guest OS $tempOutput"
        } Catch {
          Write-Verbose "Encountered a problem creating the output file in the guest OS"
          Throw "$error[0].Exception.Message"
        }
        #endregion
        #region Copy script to temp file
        if ($ExeName) {
          Send-GuestFile -Data $ExeName -File $tempFile
          Write-Verbose "Copied ExeName to temp script file"
        } else {
          if ($GuestOSType -eq 'Linux') {
            $ScriptText = $ScriptText.Split("</code>r") -join ''
          }
          Send-GuestFile -Data $ScriptText -File $tempFile
          Write-Verbose "Copied scripttext to temp script file"
        }
        #endregion
        #region Get current environment variables
        $SystemEnvironment = $gProcMgr.ReadEnvironmentVariableInGuest($moref, $auth, $null)
        #endregion
        #region Copy InFiles to to guest OS
        if ($InFile) {
          $InFile | ForEach-Object -Process {
            $destinationFilePath = "$tempFolder/$(Split-Path -Path $_ -Leaf)"
            Write-Verbose "Upload InFile $_"
            Send-GuestFile -Source $_ -File $destinationFilePath
          }
        }
        #endregion
        #region Run script
        if ($WaitForToolsVersionChange) {
          $toolsVersion = $vmInstance.ExtensionData.Guest.ToolsVersion
        }
        switch ($GuestOSType) {
          'Linux' {
            # Make temp file executable
            $spec = New-Object VMware.Vim.GuestProgramSpec
            $spec.Arguments = "751 $tempFile"
            $spec.ProgramPath = '/bin/chmod'
            Try {
              $procId = $gProcMgr.StartProgramInGuest($moref, $auth, $spec)
              Write-Verbose "Make script file executable"
            } Catch {
              Write-Verbose "Encountered a problem making the script file executable in the guest OS"
              Throw "$error[0].Exception.Message"
            }
            # Run temp file
            $spec = New-Object VMware.Vim.GuestProgramSpec
            if ($ScriptEnvironment) {
              $spec.EnvVariables = $SystemEnvironment + $ScriptEnvironment
            }
            $spec.Arguments = " &gt; $($tempOutput) 2&gt;&amp;1"
            $spec.ProgramPath = "$($tempFile)"
            $spec.WorkingDirectory = $tempFolder
            Try {
              $procId = $gProcMgr.StartProgramInGuest($moref, $auth, $spec)
              Write-Verbose "Run script with '$($tempFile) &gt; $($tempOutput)'"
            } Catch {
              Write-Verbose "Encountered a problem running the script file in the guest OS"
              Throw "$error[0].Exception.Message"
            }
          }
          'Windows' {
            # Run temp file
            $spec = New-Object VMware.Vim.GuestProgramSpec
            $spec.WorkingDirectory = $tempFolder
            if ($ScriptEnvironment) {
              $spec.EnvVariables = $SystemEnvironment + $ScriptEnvironment
            }
            if ($ExeName) {
              $spec.ProgramPath = "cmd.exe"
              $spec.Arguments = " /s /c start """" ""$ExeName"""
            } else {
              switch ($ScriptType) {
                'PowerShell' {
                  $spec.Arguments = " /C powershell -NonInteractive -File $($tempFile) &gt; $($tempOutput)"
                  $spec.ProgramPath = "cmd.exe"
                }
                { 'PowerShellv6', 'PowerShellv7' -contains $_ } {
                  $psCmd = 'pwsh.exe'
                  if ($ScriptType -eq 'PowerShellv7') {
                    $psCmd = 'pwsh-preview.exe'
                  }
                  $spec.Arguments = " /C ""$psCmd"" -NonInteractive -File $($tempFile) &gt; $($tempOutput)"
                  $spec.ProgramPath = "cmd.exe"
                }
                'Bat' {
                  $spec.Arguments = " /s /c cmd &gt; $($tempOutput) 2&gt;&amp;1 /s /c $($tempFile)"
                  $spec.ProgramPath = "cmd.exe"
                }
              }
            }
            Try {
              $procId = $gProcMgr.StartProgramInGuest($moref, $auth, $spec)
              Write-Verbose "Run script with '$($spec.ProgramPath) $($spec.Arguments)'"
            } Catch {
              Write-Verbose "Encountered a problem running the script file in the guest OS"
              Throw "$error[0].Exception.Message"
            }
          }
        }
        if ($WaitForToolsVersionChange) {
          Write-Verbose "Waiting for VMware Tools version to change"
          while ($toolsVersion -eq $vmInstance.ExtensionData.Guest.ToolsVersion) {
            Start-Sleep -Seconds 1
            $vmInstance.ExtensionData.UpdateViewData('Guest')
          }
          Write-Verbose "VMware Tools version changed from $toolsVersion to $($vmInstance.ExtensionData.Guest.ToolsVersion)"
        }
        #endregion
        #region Wait for script to finish
        Try {
          $pInfo = $gProcMgr.ListProcessesInGuest($moref, $auth, @($procId))
          Write-Verbose "Wait for process to end"
          while ($pInfo -and $null -eq $pInfo.EndTime) {
            Start-Sleep 1
            $pInfo = $gProcMgr.ListProcessesInGuest($moref, $auth, @($procId))
          }
        } Catch {
          Write-Verbose "Encountered a problem waiting for the script to end in the guest OS"
          Throw "$error[0].Exception.Message"
        }
        #endregion
        #region Retrieve output from script
        Write-Verbose "Get output from $tempOutput"
        $scriptOutput = Receive-GuestFile -Source $tempOutput
        #endregion
        #region Copy OutFiles from guest OS
        if ($OutFile) {
          $OutFile | ForEach-Object -Process {
            $sourceFilePath = "$tempFolder/$_"
            Write-Verbose "Download OutFile $_"
            Receive-GuestFile -Source $sourceFilePath -File $_
          }
        }
        #endregion
        #region Clean up
        # Remove temporary folder
        if (-not $KeepFiles) {
          $gFileMgr.DeleteDirectoryInGuest($moref, $auth, $tempFolder, $true)
          Write-Verbose "Removed folder $tempFolder"
        }
        #endregion
        #region Package result in object
        New-Object PSObject -Property @{
          VM = $vmInstance
          ScriptOutput = &amp; {
            $out = ($scriptOutput | ForEach-Object { [char]$_ }) -join ''
            if ($CRLF) {
              $out.Replace("<code>n", "</code>n`r")
            } else {
              $out
            }
          }
          Pid = $procId
          PidOwner = $pInfo.Owner
          Start = $pInfo.StartTime
          Finish = $pInfo.EndTime
          ExitCode = $pInfo.ExitCode
          ScriptType = $ScriptType
          ScriptSize = $ScriptText.Length
          ScriptText = $ScriptText
          OutFiles = $OutFile
          GuestOS = $GuestOSType
        }
        #endregion
      }
    }
  }
</pre>



<h2 class="wp-block-heading">Annotations</h2>



<p> The following annotations will only document the additions to the v2 version of the function. Refer to the blog posts mentioned in the introduction to see the annotations of the previous versions of the function. </p>



<p><strong data-rich-text-format-boundary="true">Line 191-192</strong>: Addition/change of the script types. Now includes <strong>powershellv6</strong> and <strong>powershellv7</strong>.</p>
<p><strong>Line 201</strong>: A switch that allows the caller to ask for <strong>sudo</strong> support. In practice the function will pipe, via an echo command, the guest credential&#8217;s password to each sudo command in the script.</p>
<p><strong>Line 206-207</strong>: New parameters <strong>InFile</strong> and <strong>OutFile</strong>. They permit files to be copied to/from the script environment.</p>
<p><strong>Line 208</strong>: The NoIPforCert switch</p>
<p><strong>Line 209</strong>: The SkipCertificateCheck switch</p>
<p><strong>Line 214-262</strong>: Internal helper function to send files from the caller&#8217;s environment to the guest OS.</p>
<p><strong>Line 248-255,286-293</strong>: The <strong>SkipCertificateCheck</strong> switch calls Invoke-WebRequest with the option to not check the certificate. In pre-V6 that is done through the CertificatePolicy class, in PS v6 and higher, the SkipCertificateCheck switch on Invoke-WebRequest is used.</p>
<p><strong>Line 264-307</strong>: Internal helper function to receive files from the guest OS into the caller&#8217;s environment.</p>
<p><strong>Line 237-242,276-281</strong>: If the <strong>NoIPforCert</strong> switch is $true, the IP address in the URI returned by the ESXi node (where the VM is running) will be converted to the FQDN of the ESXi node.</p>
<p><strong>Line 248-255,286-293</strong>: If the <strong>SkipCertificateCheck</strong> switch is used, the following Invoke-WebRequest is called with the setting to check checking certificates.</p>
<p><strong>Line 325-326</strong>: New she-bang entries for <strong>PowerShell v6</strong> and <strong>v7</strong>. Note that at the time this post was published, that v7 was still in preview.</p>
<p><strong>Line 331-345</strong>: When the <strong>SkipCertificateCheck</strong> is used and the PS version is pre-V6 and the type hasn&#8217;t been declared yet, the <strong>TrustAllCertsPolicy</strong> class is defined.</p>
<p><strong>Line 365-369</strong>: Additional &#8216;ready&#8217; test. If this property is not $true, the VMware Tools inside the guest OS are not ready to accept any <a href="https://vdc-download.vmware.com/vmwb-repository/dcr-public/790263bc-bd30-48f1-af12-ed36055d718b/e5f17bfc-ecba-40bf-a04f-376bbb11e811/vim.vm.guest.GuestOperationsManager.html" target="_blank" rel="noopener noreferrer">GuestOperations</a> related calls.</p>
<p><strong>Line 400</strong>: For any Windows guest OS, the function currently only accepts BAT, PS, PSv6 and PSv7 scripts.</p>
<p><strong>Line 411</strong>: For any Linux (this includes MacOS) guest OS, the function accepts all scripttypes, except BAT and PowerShell (meaning PS pre-v6).</p>
<p><strong>Line 438-444</strong>: <strong>sudo</strong> support. Each line of the user&#8217;s script containg the sudo command, will be prefixed with an echo command, which will provide the password to the sudo prompt.</p>
<p><strong>Line 465</strong>: In this version of the function, all files will be stored in a temporary directory in the guest OS.</p>
<p><strong>Line 510-517</strong>: The function allows the caller to copy one or more files, from the caller&#8217;s environment to the temporary folder in the guest OS. Since these files will be in the same folder as the actual script, the script can reference these files.</p>
<p><strong>Line 581-595</strong>: The function supports for a Windows guest OS, the use of PSv5.*, PSV6 and PSv7.</p>
<p><strong>Line 651-658</strong>: The function allows the caller to copy one or more files, from the folder, where the script ran in the guest OS, to the caller&#8217;s environment. This allows an alternative method to send data back to caller besides the stdin channel.</p>
<p><strong>Line 663-667</strong>: When the <strong>KeepFiles</strong> switch is not used, the function will remove the temporary directory in the guest OS, where all the script related files are stored.</p>



<h2 class="wp-block-heading">Usage</h2>



<p>The following section will show some examples of how to use the new features introduced in the <strong>v3</strong> of the <strong>Invoke-VMScriptPlus</strong> function.</p>



<h3 class="wp-block-heading">Sudo</h3>



<p>One of security measure on many Linux systems is that you need to use  <a rel="noreferrer noopener" aria-label="sudo (opens in a new tab)" href="https://linuxacademy.com/blog/linux/linux-commands-for-beginners-sudo/" target="_blank">sudo</a> to run commands with elevated privileges. </p>



<p>This is a typical example of such a case.</p>


<pre class="urvanov-syntax-highlighter-plain-tag">$vmName = 'ubuntuVM'
$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))


$sInvoke = @{
&nbsp;&nbsp;&nbsp;&nbsp;VM = $vmName
&nbsp;&nbsp;&nbsp;&nbsp;GuestCredential = $cred
&nbsp;&nbsp;&nbsp;&nbsp;ScriptText = 'apt install gawk'
&nbsp;&nbsp;&nbsp;&nbsp;ScriptType = 'bash'
}
Invoke-VMScriptPlus @sInvoke</pre>


<p>The OS returns the following error.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="840" height="64" src="https://www.lucd.info/wp-content/uploads/2019/11/sudo-1.png" alt="" class="wp-image-6477" srcset="https://www.lucd.info/wp-content/uploads/2019/11/sudo-1.png 840w, https://www.lucd.info/wp-content/uploads/2019/11/sudo-1-300x23.png 300w, https://www.lucd.info/wp-content/uploads/2019/11/sudo-1-768x59.png 768w, https://www.lucd.info/wp-content/uploads/2019/11/sudo-1-720x55.png 720w" sizes="(max-width: 840px) 100vw, 840px" /><figcaption>Elevated privileges required</figcaption></figure>



<p>Ok, let&#8217;s place <strong>sudo</strong> in front of that.</p>


<pre class="urvanov-syntax-highlighter-plain-tag">$vmName = 'ubuntuVM'
$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))


$sInvoke = @{
&nbsp;&nbsp;&nbsp;&nbsp;VM = $vmName
&nbsp;&nbsp;&nbsp;&nbsp;GuestCredential = $cred
&nbsp;&nbsp;&nbsp;&nbsp;ScriptText = 'sudo apt install gawk'
&nbsp;&nbsp;&nbsp;&nbsp;ScriptType = 'bash'
}
Invoke-VMScriptPlus @sInvoke</pre>


<p>But that just makes the next issue obvious. How to answer to a prompt in a script. The method to solve this quite simple. Echo the password and then pipe it to the sudo command.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="519" height="35" src="https://www.lucd.info/wp-content/uploads/2019/11/sudo-2.png" alt="" class="wp-image-6478" srcset="https://www.lucd.info/wp-content/uploads/2019/11/sudo-2.png 519w, https://www.lucd.info/wp-content/uploads/2019/11/sudo-2-300x20.png 300w" sizes="(max-width: 519px) 100vw, 519px" /></figure>



<p>But this not always a practical solution, and probably not very safe either. To avoid having to handle this in the code you sent to the guest OS, the Invoke-VMScriptPlus function has the <strong>Sudo</strong> switch.</p>


<pre class="urvanov-syntax-highlighter-plain-tag">$vmName = 'ubuntuVM'
$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))


$sInvoke = @{
&nbsp;&nbsp;&nbsp;&nbsp;VM = $vmName
&nbsp;&nbsp;&nbsp;&nbsp;GuestCredential = $cred
&nbsp;&nbsp;&nbsp;&nbsp;ScriptText = 'sudo apt install gawk'
&nbsp;&nbsp;&nbsp;&nbsp;ScriptType = 'bash'
    Sudo = $true
}
Invoke-VMScriptPlus @sInvoke</pre>


<p>It will extract the password from the <strong>GuestCredential</strong> parameter value, and insert the <strong>echo with the password</strong> on each line in your code that starts with sudo.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="590" height="65" src="https://www.lucd.info/wp-content/uploads/2019/11/sudo-3.png" alt="" class="wp-image-6484" srcset="https://www.lucd.info/wp-content/uploads/2019/11/sudo-3.png 590w, https://www.lucd.info/wp-content/uploads/2019/11/sudo-3-300x33.png 300w" sizes="auto, (max-width: 590px) 100vw, 590px" /></figure>



<h2 class="wp-block-heading">PowerShell v7</h2>



<p>At the moment, of this writing, PowerShell v7 is still a preview.<br>Since you can install PSv6 and PSv7 side-by-side, you can run your scripts in either version.</p>



<p>This is a handy way to test your scripts for readiness for PSv7.</p>



<p>With the <strong>ScriptType</strong> parameter, you easily define against which PowerShell version your script should run. First we use <strong>powershellv6</strong>.</p>



<pre class="lang:ps decode:true ">$vmName = 'ubuntuVM'
$credVM&nbsp;=&nbsp;Get-VICredentialStoreItem&nbsp;-Host&nbsp;$vmName
$cred&nbsp;=&nbsp;New-Object&nbsp;System.Management.Automation.PSCredential&nbsp;($credVM.User,&nbsp;(ConvertTo-SecureString&nbsp;$credVM.Password&nbsp;-AsPlainText&nbsp;-Force))


$sInvoke&nbsp;=&nbsp;@{
&nbsp;&nbsp;&nbsp;&nbsp;VM&nbsp;=&nbsp;$vmName
&nbsp;&nbsp;&nbsp;&nbsp;GuestCredential&nbsp;=&nbsp;$cred
&nbsp;&nbsp;&nbsp;&nbsp;ScriptText&nbsp;=&nbsp;'$PSVersionTable'
&nbsp;&nbsp;&nbsp;&nbsp;ScriptType&nbsp;=&nbsp;'powershellv6'
}
Invoke-VMScriptPlus&nbsp;@sInvoke</pre>



<p>This results in.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="754" height="232" src="https://www.lucd.info/wp-content/uploads/2019/11/psv6.png" alt="" class="wp-image-6485" srcset="https://www.lucd.info/wp-content/uploads/2019/11/psv6.png 754w, https://www.lucd.info/wp-content/uploads/2019/11/psv6-300x92.png 300w, https://www.lucd.info/wp-content/uploads/2019/11/psv6-750x232.png 750w, https://www.lucd.info/wp-content/uploads/2019/11/psv6-720x222.png 720w" sizes="auto, (max-width: 754px) 100vw, 754px" /><figcaption>PSv6</figcaption></figure>



<p>And then the same, but with <strong>powershellv7</strong>.</p>



<pre class="lang:ps decode:true  ">$vmName = 'ubuntuVM'
$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))


$sInvoke = @{
&nbsp;&nbsp;&nbsp;&nbsp;VM = $vmName
&nbsp;&nbsp;&nbsp;&nbsp;GuestCredential = $cred
&nbsp;&nbsp;&nbsp;&nbsp;ScriptText = '$PSVersionTable'
&nbsp;&nbsp;&nbsp;&nbsp;ScriptType = 'powershellv7'
}
Invoke-VMScriptPlus @sInvoke</pre>



<p>And now we get.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="760" height="232" src="https://www.lucd.info/wp-content/uploads/2019/11/psv7.png" alt="" class="wp-image-6486" srcset="https://www.lucd.info/wp-content/uploads/2019/11/psv7.png 760w, https://www.lucd.info/wp-content/uploads/2019/11/psv7-300x92.png 300w, https://www.lucd.info/wp-content/uploads/2019/11/psv7-720x220.png 720w" sizes="auto, (max-width: 760px) 100vw, 760px" /></figure>



<h3 class="wp-block-heading">Infile/OutFile</h3>



<p>The Invoke-VMScriptPlus function captures the output of your script on the stdin stream. But sometimes you would like to produce multiple outputs, or output in a specific format.</p>



<p>The same goes for your input to your script. You can pass input along to your script, for example with a here-string, but this at least requires extra steps to run your script.</p>



<p>For that reason, this v3 version of Invoke-VMScriptPlus, added two new parameters, <strong>Infile</strong> and <strong>OutFile</strong>.</p>



<p>Each of these parameters allow you to specify <strong>one or more files</strong> in your local environment that will be passed and/or retrieved to the environment where your script runs in the guest OS of the target VM.</p>



<p>A somewhat contrived example on what this allows you to do.</p>



<div>
<pre class="">$vmName = 'ubuntuVM'

$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))

$code = @'
Get-Content -Path .\in.txt |
ForEach-Object -Process {
   $_ | Set-Content -Path ".\$_.txt"
}
'@

# Create input file
1..3 | Set-Content -Path .\in.txt
Get-ChildItem -Path . -Filter *.txt

$sInvoke = @{
   VM = $vmName
   GuestCredential = $cred
   ScriptText = $code
   ScriptType = 'powershellv7'
   InFile = 'in.txt'
   OutFile = '1.txt', '2.txt', '3.txt'
}
Invoke-VMScriptPlus @sInvoke

Get-ChildItem -Path . -Filter *.txt</pre>
</div>



<p>In short, the script creates an input file, then runs a script on the target VM, passing along the input file.<br>The script on the target VM creates a number of files, which are returned to the caller when the script completes.</p>



<p>This is the output from the above code.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="571" height="477" src="https://www.lucd.info/wp-content/uploads/2019/11/in-out-file-1.png" alt="" class="wp-image-6540" srcset="https://www.lucd.info/wp-content/uploads/2019/11/in-out-file-1.png 571w, https://www.lucd.info/wp-content/uploads/2019/11/in-out-file-1-300x251.png 300w" sizes="auto, (max-width: 571px) 100vw, 571px" /></figure>



<p>This is a handy feature when your script requires an existing file as input and produces multiple output files.</p>



<h3 class="wp-block-heading">NoIPinCert</h3>



<p>When the function needs to retrieve files from the guest OS, the ESXi node on which the VM is running, provides a URI. This URI normally contains the IP address of the ESXi node.</p>



<p>This can cause an issue when using certificates, and not bypassing the certificate check. The reason is sometimes that the IP address of the ESXi node is not included as a <strong>Subject Alternate Address</strong> (<a href="https://www.digicert.com/subject-alternative-name.htm" target="_blank" rel="noreferrer noopener" aria-label="SAN (opens in a new tab)">SAN</a>) in the certificate. This is visible through the following error message. Note that the following output also shows some verbose output to demonstrate when this is happening, and also to show that the error occurs when doing a GET with an URI that contains the IP address.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="74" src="https://www.lucd.info/wp-content/uploads/2019/11/san-1024x74.png" alt="" class="wp-image-6558" srcset="https://www.lucd.info/wp-content/uploads/2019/11/san-1024x74.png 1024w, https://www.lucd.info/wp-content/uploads/2019/11/san-300x22.png 300w, https://www.lucd.info/wp-content/uploads/2019/11/san-768x56.png 768w, https://www.lucd.info/wp-content/uploads/2019/11/san-720x52.png 720w, https://www.lucd.info/wp-content/uploads/2019/11/san.png 1196w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption>No IP SAN in certificate</figcaption></figure>



<p>To avoid this error, the Invoke-VMScriptPlus function, by default, translates this IP address into the FQDN of the ESXi node. The following verbose output shows the adapted URI for the GET</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="81" src="https://www.lucd.info/wp-content/uploads/2019/11/san-2-1024x81.png" alt="" class="wp-image-6559" srcset="https://www.lucd.info/wp-content/uploads/2019/11/san-2-1024x81.png 1024w, https://www.lucd.info/wp-content/uploads/2019/11/san-2-300x24.png 300w, https://www.lucd.info/wp-content/uploads/2019/11/san-2-768x61.png 768w, https://www.lucd.info/wp-content/uploads/2019/11/san-2-720x57.png 720w, https://www.lucd.info/wp-content/uploads/2019/11/san-2.png 1085w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In some environments these automatic conversion of the IP address to the FQDN might cause an issue. One reason for this to happen might be that the ESXi node is added with it&#8217;s IP address. Another might be that the DNS query to get the FQDN of the ESXi node fails.<br>Especially for those occasion, the function now has this NoIPforCert switch. This switch, when set, instructs the function to NOT translate the IP address in the URI to the FQDN.</p>



<p>A sample call that uses this switch can look like this.</p>



<pre class="">$sInvoke = @{
    VM = $vmName
    ScriptType = 'bash'
    ScriptText = 'whoami'
    GuestCredential = $cred
    Verbose = $true
    NoIPinCert = $true
}
Invoke-VMScriptPlus @sInvoke</pre>



<p>Enjoy!</p>


]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2019/11/17/invoke-vmscriptplus-v3/feed/</wfw:commentRss>
			<slash:comments>58</slash:comments>
		
		
			</item>
	</channel>
</rss>
