Set-Location $PSScriptRoot

$vmExecutingScripts = @{}

$pattern = "-(?:File|Command)\s+(?<scriptName>[^\s]+)\s+-VMName\s+(?<VMName>[^\s]+)"
$psInstancesArguments = Get-CimInstance -ClassName Win32_Process |
                Where-Object { $_.Name -eq "powershell.exe" } | 
                Select-Object CommandLine -ExpandProperty CommandLine
if($psInstancesArguments)
{
    $options = [Text.RegularExpressions.RegexOptions]'IgnoreCase'
    $vmScriptInfoArr = [regex]::Matches($psInstancesArguments, $pattern, $options)
    foreach ($vmScriptInfo in $vmScriptInfoArr) {
        $path = $vmScriptInfo.Groups["scriptName"].Value
        $deepestFolder = Split-Path -Path $path -Parent | Split-Path -Leaf
        $fileName = Split-Path -Path $path -Leaf
        
        $scriptName = Join-Path -Path $deepestFolder -ChildPath $fileName
        $vmName = $vmScriptInfo.Groups["VMName"].Value
    
        $vmExecutingScripts[$vmName] = $scriptName
    }
}

$VMs = Get-VM
$VMStatuses = @()

foreach ($VM in $VMs) {
    $vmName = $VM.Name
    $scriptBeingExecuted = if ($vmExecutingScripts.ContainsKey($vmName)) { $vmExecutingScripts[$vmName] } else { $null }

    $VMStatus = [PSCustomObject]@{
        "VMName" = $vmName
        "Running" = ($VM.State -eq 'Running')
        "CommandBeingExecuted" = $scriptBeingExecuted
    }

    $VMStatuses += $VMStatus
}

if($VMStatuses.Count -eq 0)
{
    Write-Host "[ { } ]"
}
elseif($VMStatuses.Count -eq 1)
{
    Write-Host "[`r`n$($VMStatuses | ConvertTo-Json -Depth 4)`r`n]"
}
else
{
    Write-Host ($VMStatuses | ConvertTo-Json -Depth 4)
}

#Stop-Transcript