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;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
 
$expectedExpiry = "2/24/2022 5:59:59 PM"
$i=10
while ($i -lt 110) {
                $uri = "https://sp$($i)"
                $webRequest = [Net.WebRequest]::Create($uri)
                try { $webRequest.GetResponse() } catch {}
                $cert = $webRequest.ServicePoint.Certificate
                if ($cert.GetExpirationDateString() -ne $expectedExpiry) {
                                Write-Host -ForegroundColor Red "$uri - expectedExpiry does not match"
                }
                else {
                                Write-Host -ForegroundColor Green "$uri matches expectedExpiry"
                }
                $i++
}

Symantec Messaging Gateway mail server - blank screen on boot - switch to BIOS instead of (U)EFI 
 
$username = "admin"
$password = ""
 
$authorization = [System.Text.Encoding]::UTF8.GetBytes($username + ':' + $password)
$authorizationString = [System.Convert]::ToBase64String($authorization)
$headers = @{"Authorization" = "Basic $($authorizationString)"}
 
$path = 'C:\cert_reqs\covid\uag'
$names = Import-Csv -Path "$($path)\uag_certs_h1.csv"
 
#$url = "https://prefixwisp10:9443/v1/config/adminusers"
#$configResponse = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $headers -Uri $url
 
$i = 97
 
foreach ($i in $list) {
$wispname = "prefixwisp$($i)"
$url = https://$($wispname):9443/rest/v1/config/system
# resend the whole system config for this work
$body = '{ "quiesceMode": true }'
 
$configResponse = Invoke-RestMethod -Method Put -ContentType "application/json" -Headers $headers -Uri $url -Body $body
$configResponse
}
 
# Check thumbprint
 
foreach ($uag in $names) {
                $wispname = $uag.Name
                $url = "https://$($wispname):9443/rest/v1/config/edgeservice/VIEW"
 
                try {
                                $configResponse = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $headers -Uri $url
                }
                catch {
            $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader($responseStream)
            $errorString = $streamReader.ReadToEnd()
                                                Write-Output "ERROR: $errorString `r`n $($url)"
            #throw "Exception $errorString"
    }
                $configResponse.proxyDestinationUrlThumbprints += ",sha1=23 ac a9 0d 58 69 …"
                $body = $configResponse |ConvertTo-Json
               
               
                #Puts have to be lower case
                $url = $url.ToLower()
               
                try {
                                $response = = Invoke-RestMethod -Method Put -ContentType "application/json" -Headers $headers -Uri $url -Body $body
                }
                catch {
            $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader($responseStream)
            $errorString = $streamReader.ReadToEnd()
                                                Write-Output "ERROR: $errorString `r`n $($url)"
                                                pause
            #throw "Exception $errorString"
    }
                $configResponse = $null
}
 
foreach ($uag in $names) {
                $wispname = $uag.Name
                $url = "https://$($wispname):9443/rest/v1/config/edgeservice/VIEW"
 
                try {
                                $configResponse = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $headers -Uri $url
                }
                catch {
            $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader($responseStream)
            $errorString = $streamReader.ReadToEnd()
                                                Write-Output "ERROR: $errorString `r`n $($url)"
            #throw "Exception $errorString"
    }
                # $configResponse.proxyDestinationUrlThumbprints += ",sha1=23 ac a9 0d 58 69 …"
               
                $url = "https://$($wispname):9443/rest/v1/monitor/stats"
               
                try {
                                $response = Invoke-RestMethod -Method Get -ContentType "application/xml" -Headers $headers -Uri $url
                }
                catch {
            $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader($responseStream)
            $errorString = $streamReader.ReadToEnd()
                                                Write-Output "ERROR: $errorString `r`n $($url)"
           #throw "Exception $errorString"
    }
                $reason = $response.accessPointStatusAndStats.viewEdgeServiceStats.backendStatus.reason
                $running = $response.accessPointStatusAndStats.viewEdgeServiceStats.backendStatus.status
                if ($running -ne 'RUNNING') {
                                Write-Host -ForegroundColor Red "$($wispname) - $($running) - $($reason)"
                }
                else {
                                Write-Output "$($wispname) - $($running) - $($reason) - View EdgeService Destination $($configResponse.proxyDestinationUrl)"
                }
                $protocols = $response.accessPointStatusAndStats.viewEdgeServiceStats.protocol
                foreach ($protocol in $protocols) {
                                Write-Output "$($protocol.name):$($protocol.status.status),$($protocol.status.reason):Session=$($protocol.sessions):MaxSessions=$($protocol.maxSessions)"
                }
               
                $radiusStatus = $response.accessPointStatusAndStats.authentication.authBrokerStatus.status
                $successRadiusLogins = $response.accessPointStatusAndStats.authentication.successLogins
                $failedRadiusLogins = $response.accessPointStatusAndStats.authentication.failedLogins
                Write-Output "RADIUS: $($radiusStatus) Successful Logins: $($successRadiusLogins) Failed Logins: $($failedRadiusLogins)"
                Write-Output ""
}
 
$connservers = 'con000', 'con001', 'con004', 'con005'
foreach ($uag in $uagnames) {
                $wispname = $uag.Name
                if (($wispname -eq 'skipThisOne') -or ($wispname -ilike 'andSkipThisOneToo')) {
                                Write-Output "Skipping $($wispname)"
                                continue
                }
                $url = "https://$($wispname):9443/rest/v1/config/edgeservice/VIEW"
 
                try {
                                $response = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $headers -Uri $url
                }
                catch {
            $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader($responseStream)
            $errorString = $streamReader.ReadToEnd()
                                                Write-Output "ERROR: $errorString `r`n $($url)"
            #throw "Exception $errorString"
    }
               
                $response.proxyDestinationUrl = "https://$($connservers[(Get-Random -Minimum 0 -Maximum 6)]).thedomain.gov"
                $response.blastExternalUrl = $response.blastExternalUrl -replace "8443", "443"
                $jsonResponse = $response |ConvertTo-Json
                Write-Output "$($wispname) switching to View Edge Server destination $($response.proxyDestinationUrl) and blastExternalUrl to $($response.blastExternalUrl)"
               
                $url = "https://$($wispname):9443/rest/v1/config/edgeservice/view"
                try {
                                $response2 = Invoke-RestMethod -Method PUT -ContentType "application/json" -Headers $headers -Uri $url -body $jsonResponse
                }
                catch {
                                $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader($responseStream)
            $errorString = $streamReader.ReadToEnd()
                                                Write-Output "ERROR: $errorString `r`n $($url)"
            throw "PUT Exception $errorString"
                }
 
               
}
 
 
$path = 'C:\cert_reqs\covid\uag'
$names = Import-Csv -Path "$($path)\uag_certs_h1.csv"
foreach ($entry in $names) {
                $name = $entry.Name
                #if ($name -ilike "prefixwisp11.*") {
                $externalName = $entry.ExternalName
                $ip = $entry.IP
                $crt = $entry.Cert
                $crtkey = $entry.Key
                $dvswitchpg = $entry.Portgroup
                $wispnetmask = $entry.Netmask
                $wispgateway = $entry.Gateway
                $twconnservtw = $entry.TWConnServTW
                $v6ip = $entry.IPv6
                $v6gateway = $entry.Gatewayv6
                $template = Get-Content -Path "$($path)\template.ini" -Raw
                $template = $template.Replace('WISPNAME',$name)
                $template = $template.Replace('EXTERNALNAME',$externalName)
                $template = $template.Replace('WISPIPADDRESS',$ip)
                $template = $template.Replace('DVSWITCHPG',$dvswitchpg)
                $template = $template.Replace('WISPNETMASK',$wispnetmask)
                $template = $template.Replace('WISPGATEWAY',$wispgateway)
                $template = $template.Replace('COVIDCERTNAME',$crt)
                $template = $template.Replace('COVIDCERTKEY',$crtkey)
                $template = $template.Replace('TWCONNSERVTW',$twconnservtw)
                $template = $template.Replace('V6GATEWAYV6',$v6gateway)
                $template = $template.Replace('V6IPV6',$v6ip)
                $template | Set-Content -Path "$($path)\$($name).ini"
                #}
}
 
Get-VM -Name "specificUAG" | Get-View
$disableSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
$disableSpec.VAppConfigRemoved = $True
$vm.ReconfigVM($disableSpec)
 
 
foreach ($entry in $names) {
                $wispname = $entry.Name
                $url = "https://$($wispname):9443/rest/v1/config/certs/ssl/"
               
                if ($wispname -eq 'skipthisname') {
                                                break
                }
               
               
                $certLocation = "\\a\View 7\CERTS\covid\$($entry.Cert)"
                $keyLocation = "\\a\View 7\CERTS\covid\$($entry.Key)"
                $certContents = (Get-Content -Path $certLocation | Out-String) -replace "'", "\\047" -replace "`r`n", "\n" -replace "`r", ""
                $keyContents = (Get-Content -Path $keyLocation | Out-String) -replace "'", "\\047" -replace "`r`n", "\n" -replace "`r", ""
               
                $certJson = ' { "privateKeyPem" : "'+$keyContents+'", "certChainPem” : "'+$certContents+'"}'
 
                try {
                                $response = Invoke-RestMethod -Method PUT -ContentType "application/json" -Headers $headers -Uri $url -Body $certJson
                                Write-Output "Submitted $($url) : $($entry.Cert)"
                }
                catch {
            $responseStream = $_.Exception.Response.GetResponseStream()
            $streamReader = New-Object System.IO.StreamReader($responseStream)
            $errorString = $streamReader.ReadToEnd()
                                                Write-Output "ERROR: $errorString `r`n $($url)"
            #throw "Exception $errorString"
    }
                }
}
 
 
 
 
 
 
# vra rest
 
[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True,Position=1)]
    [string]$reqId
)
 
#$reqId = "4fa3d1b0-f586-4249-9c82-87cd32958f52" #2a79b51b-3e32-469a-8fe1-7869df2933eb"
$username = "vservice"
$password = ""
$hostname = "vra.thedomain.gov"
$tenant = "vsphere.local"
$identityUrl = "https://$($hostname)/identity/api/tokens"
$url = "https://$($hostname)/catalog-service/api/consumer/resources?%24orderby=dateCreated%20desc"
$authInfo = '{"username":"' + "$username" + '","password":"' + $password + '","tenant":"' + $tenant + '"}'
 
$headers = @{"Accept" = "application/json"}
 
$token = Invoke-RestMethod -Method Post -ContentType "application/json" -Headers $headers -Uri $identityUrl -Body $authInfo
Write-Output "The token expires : $($token.expires)"
 
$authHeaders = $headers
$authHeaders.Add('Authorization', "Bearer $($token.id)")
 
$response = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $authHeaders -Uri $url
$deploymentVMs = $response.content | Where-Object {$_.requestId -eq $reqId}
 
$topologyMapping = @{}
 
foreach ($vm in $deploymentVMs) {
                if ($vm.resourceTypeRef.id.equals("Infrastructure.Virtual") -and $vm.resourceTypeRef.label.equals("Virtual Machine") ) {
                                $url2 = "https://$($hostname)/iaas-proxy-provider/api/machines/$($vm.providerBinding.bindingId)"
                                $iaasProperties = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $authHeaders -Uri $url2
                                $value = $($iaasProperties.properties | Where-Object {$_.name -imatch "thedomain.vra.provisionFor"}).value
                                Write-Output "$($iaasProperties.name)=$($value)"
                }
}
 
09acff64-b320-4bbd-8b4d-12ba4abc1083 / 44c7e02d-c620-4e60-8702-0705cdb799f3
905ce9bf-f648-425d-bc61-8f5d4a1074b5 / 8f970b00-1414-4293-bd48-adda950a523b
 
 
 
 
 
$url2 = "https://$($hostname)/iaas-proxy-provider/api/machines/d719e9ce-51b2-47f5-856e-46532d0e6121"
$response = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $authHeaders -Uri $url2
 
$provisionedFor = $response.properties | Where-Object {$_.name -imatch "thedomain.vra.provisionFor"}
$provisionedFor.value
 
$url3 = "https://$($hostname)/catalog-service/api/consumer/resources/" # $($reqId)"
$response = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $authHeaders -Uri $url3
$response.content | Where-Object {$_.requestId -eq $reqId}
 
$url4 = "https://$($hostname)/catalog-service/api/consumer/resources/905ce9bf-f648-425d-bc61-8f5d4a1074b5"
$url4 = "https://$($hostname)/catalog-service/api/consumer/resources/bd20ced2-78e2-4e7b-b22a-110c51dd04ca"
$response2 = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $authHeaders -Uri $url4
 
PS C:\Users\s> $url3 = "https://$($hostname)/catalog-service/api/consumer/resources/?%24filter=resource/requestId+e
q+'905ce9bf-f648-425d-bc61-8f5d4a1074b5'" # $($reqId)"
 
PS C:\Users\s> $url3 = https://$($hostname)/catalog-service/api/consumer/resources?%24orderby=dateCreated%20desc
 
 
 
$vm = Get-VM -Name "ifj3890fj9w3fj"
 
$spec = New-Object VMware.Vim.VirtualMachineConfigSpec
$spec.latencySensitivity = New-Object VMware.Vim.LatencySensitivity
$spec.LatencySensitivity.Level = [VMware.Vim.LatencySensitivitySensitivityLevel]::high
 
$vm.ExtensionData.ReconfigVM($spec)
 
$vm | Get-VMResourceConfiguration | Set-VMResourceConfiguration -MemReservationMB $vm.MemoryMB
 
$credentials = Get-Credential
Connect-NsxtServer -Server nsx-t-manager.net -Credential $credentials
 
$transportZone = "/infra/sites/default/enforcement-points/default/transport-zones/"
foreach ($vlan in $vlans) {
    # Set variables from csv data
    $segmentId = "n$($vlan.Name)"
    $vlanArray = @($vlan.ExtensionData.Config.DefaultPortConfig.Vlan.VlanId)
    # Pull the current segment information
    $segmentList = Get-NsxtPolicyService -Name com.vmware.nsx_policy.infra.segments
    # Creating a new segment object
    $newSegmentSpec = $segmentList.Help.patch.segment.Create()
    $newSegmentSpec[0].id = $segmentId
    $newSegmentSpec[0].vlan_ids = $vlanArray
    $newSegmentSpec[0].transport_zone_path = $transportZone
    # Create the segment
    $segmentList[0].patch($segmentId, $newSegmentSpec[0])
    Write-Host("Created segment "+$segmentId+ " with vlan ID "+$vlanArray)
  }
 
 
 
 
foreach ($vmhost in $vmhosts) {
    $esxcli = get-esxcli -vmhost $vmhost -v2 #Gain access to ESXCLI on the host.
                $storagedevices = $esxcli.storage.core.device.list.Invoke() |Where {$_.DisplayName -like 'Local NVMe Disk*'}
                foreach ($storagedevice in $storagedevices) {
                                $smartArgs = $esxcli.storage.core.device.smart.get.CreateArgs()
                                $smartArgs.devicename = $storagedevice.Device
                                $devicedetails = $esxcli.storage.core.device.smart.get.Invoke($smartArgs) | Where {$_.Parameter -eq 'Media Wearout Indicator'}
                                Write-Output "$($vmhost.Name): $($storagedevice.Device) = $($devicedetails.Parameter) $($devicedetails.Value)"
                }
}
 
$csvfile = Import-Csv -Path F:\nessus_scammers.csv
[array]::Reverse($csvfile)
foreach ($entry in $csvfile) {
                $vm = Get-VM -Name "$($entry.host)"
                if ($vm -eq $null) {
                                Write-Output "Could not find $($entry.host)"
                }
                else {
                                if (([int]$entry.recom -lt $vm.NumCpu) -or ([int]$entry.recom -eq $vm.NumCpu)) {
                                                Write-Output "$($vm.Name): Recommended $($entry.recom) vCPUs is less than or equal to current CPUs $($vm.NumCpu)"
                                }
                                else {
                                                Write-Output "Shutting down VM  $($vm.Name)"
                                                if ($vm.PowerState -eq "PoweredOff") {
                                                                Write-Output "$($vm.Name) is powered off"
                                                                pause
                                                                pause
                                                }
                                                $vm | Shutdown-VMGuest -confirm:$false
                                                $timeStart = Get-Date
                                                $waiting = $true
                                                while ($waiting) {
                                                                Start-Sleep -s 10
                                                                $vm = Get-VM -Name "$($entry.host)"
                                                                if ($vm.PowerState -eq "PoweredOff") {
                                                                                $waiting = $false
                                                                                Write-Output "$($vm.Name) is powered off"
                                                                                $vm | Set-VM -NumCpu $entry.recom -confirm:$false
                                                                                Start-Sleep -s 5
                                                                                Start-VM -VM "$($vm.Name)" -Confirm:$false -RunAsync
                                                                }
                                                                $timeNow = Get-Date
                                                                $duration = New-Timespan –Start $timeStart –End $timeNow
                                                                if ($duration.TotalSeconds -gt 240) {
                                                                                $waiting = $false
                                                                                Write-Output "$($vm.Name) didn't shut down within $($duration.TotalSeconds) seconds"
                                                                }
                                                }
                                                $waiting = $null
                                                $vm = $null
                                }
                }
}
Write-Host "VMware ESXi Configuration Baseline v4.1"
 
Write-Host "Lockdown Mode Enabled"
$timeChecked = Get-Date -Format s
$expectedValue = $true
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost.ExtensionData.Config.AdminDisabled
                if ($configItem -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "SSH Running"
$timeChecked = Get-Date -Format s
$expectedValue = $false
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost | Get-VMHostService | Where-Object {$_.Key -eq 'TSM-SSH'} | Select Running
                $configItem = $configItem.Running
                if ($configItem -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "NTP Running"
$timeChecked = Get-Date -Format s
$expectedValue = $true
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost | Get-VMHostService | Where-Object {$_.Key -eq 'ntpd'} | Select Running
                $configItem = $configItem.Running
                if ($configItem -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "NTP Start Policy"
$timeChecked = Get-Date -Format s
$expectedValue = "on"
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost | Get-VMHostService | Where-Object {$_.Key -eq 'ntpd'} | Select Policy
                $configItem = $configItem.Policy
                if ($configItem -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "DCUI.Access Value"
$expectedValue = "root"
$timeChecked = Get-Date -Format s
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost | Get-AdvancedSetting -Name "DCUI.Access"
                if ($configItem.Value -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "UserVars.ESXiShellTimeout"
$expectedValue = "900"
$timeChecked = Get-Date -Format `
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost | Get-AdvancedSetting -Name "UserVars.ESXiShellTimeout"
                if ($configItem.Value -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "UserVars.ESXiShellInteractiveTimeout"
$expectedValue = "900"
$timeChecked = Get-Date -Format s
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {       
                $configItem = $vmhost | Get-AdvancedSetting -Name "UserVars.ESXiShellInteractiveTimeout"
                if ($configItem.Value -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "Syslog.global.logHost"
$expectedValue = "udp://syslogServer.the.domain.tld:514"
$timeChecked = Get-Date -Format s
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost | Get-AdvancedSetting -Name "Syslog.global.logHost"
                if ($configItem.Value -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
Write-Host "vSwitch Security Policies"
$expectedValue = $false
$timeChecked = Get-Date -Format s
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $vSwitches = $vmhost | Get-VirtualSwitch -Standard
                foreach ($vswitch in $vSwitches) {
                                $securityPolicy = $vswitch | Get-SecurityPolicy
                                if ($securityPolicy.ForgedTransmits -ne $expectedValue) {
                                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($vswitch.Name) : ForgedTransmits=$($securityPolicy.ForgedTransmits) [Expected Value: $($expectedValue)]"
                                }
                                else {
                                                Write-Host "$($vmhost.Name): $($vswitch.Name) : ForgedTransmits=$($securityPolicy.ForgedTransmits)"
                                }
                               
                                if ($securityPolicy.AllowPromiscuous -ne $expectedValue) {
                                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($vswitch.Name) : AllowPromiscuous=$($securityPolicy.AllowPromiscuous) [Expected Value: $($expectedValue)]"
                                }
                                else {
                                                Write-Host "$($vmhost.Name): $($vswitch.Name) : AllowPromiscuous=$($securityPolicy.AllowPromiscuous)"
                                }
                               
                                if ($securityPolicy.MacChanges -ne $expectedValue) {
                                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($vswitch.Name) : MacChanges=$($securityPolicy.MacChanges) [Expected Value: $($expectedValue)]"
                                }
                                else {
                                                Write-Host "$($vmhost.Name): $($vswitch.Name) : MacChanges=$($securityPolicy.MacChanges)"
                                }
                }
}
 
Write-Host "Authentication Services Domain"
$expectedValue = "the.domain.tld"
$timeChecked = Get-Date -Format s
Write-Host "Time checked: $timeChecked"
foreach ($vmhost in (Get-VMHost | sort)) {
                $configItem = $vmhost | Get-VMHostAuthentication
                $configItem = $configItem.Domain
                if ($configItem -ne $expectedValue) {
                                Write-Host -ForegroundColor Red "$($vmhost.Name): $($configItem) [Expected Value: $($expectedValue)]"
                }
                else {
                                Write-Host "$($vmhost.Name): $($configItem)"
                }
}
 
$clusterName = "DEV Public"
$clusterName = "VDI_VSAN_01"
$clusterName = "VDI_VSAN_01"
$fileDirectory = "E:\vmnic_monitoring\"
$vmhosts = Get-Cluster -Name $clusterName | Get-VMHost | Sort Name
$esxclis = @{}
$vmnics = @{}
 
$from='Cloud Operations '
$to=’sendTo '
$subject="$($clusterName) - port reset"
$server="mailrelay.thedomain.tld"
 
foreach ($vmhost in $vmhosts) {
                $esxcli = Get-EsxCli -VMhost $vmhost -V2
                $esxclis["$($vmhost.Name)"] = $esxcli
                $vswitch = $vmhost | Get-VirtualSwitch -Name "vSwitch0"
                $vmnics["$($vmhost.Name)"] = $vswitch.Nic
}
 
while ($true) {
                foreach ($vmhost in $vmhosts) {
                                if ($vmhost.ConnectionState -ne "Connected") {
                                                Write-Host "$($vmhost.Name) is $($vmhost.ConnectionState)"
                                                continue
                                }
               
                                if ([System.IO.File]::Exists("E:\vmnic_monitoring\$($vmhost.Name)_vmnic.txt") -eq $false) {
                                                Add-Content E:\vmnic_monitoring\$($vmhost.Name)_vmnic.txt "vmnic,stat,count,date,"
                                }
                               
                                $nics = $vmnics.Item($vmhost.Name)
                                $hostnics = $esxclis.Item($vmhost.Name).network.nic.list.Invoke()
                                $nic1 = $hostnics | Where-Object {$_.Name -eq $nics[0]}
                                $nic2 = $hostnics | Where-Object {$_.Name -eq $nics[1]}
                               
                               
                                $nic1results = $null
                                $nic2results = $null
                               
                                $nic1results = $esxclis.Item($vmhost.Name).network.nic.stats.get.Invoke(@{"nicname"="$($nic1.Name)"}) | Select-Object -Property *errors
                                $outStr = ""
                                $date = Date
                                $csvContents = Import-CSV E:\vmnic_monitoring\$($vmhost.Name)_vmnic.txt
                                foreach ($prop in $nic1results.psobject.properties) {
                                                if ($nic1results.$($prop.Name) -ne 0) {
                                                                $lastEntry = $csvContents | Where-Object {$_.stat -eq $prop.Name} | Select-Object -Last 1
                                                                if ($lastEntry.count -ne $($nic1results.$($prop.Name))) {
                                                                                $outStr += "$($nic1.Name),$($prop.Name),$($nic1results.$($prop.Name)),$($date),`r`n"
                                                                }
                                                }
                                }
                                if ($nic2 -ne $null) {
                                                $nic2results = $esxclis.Item($vmhost.Name).network.nic.stats.get.Invoke(@{"nicname"="$($nic2.Name)"}) | Select-Object -Property *errors
                                                $outStr = ""
                                                foreach ($prop in $nic2results.psobject.properties) {
                                                                if ($nic2results.$($prop.Name) -ne 0) {
                                                                                $lastEntry = $csvContents | Where-Object {$_.stat -eq $prop.Name} | Select-Object -Last 1
                                                                                if ($lastEntry.count -ne $($nic2results.$($prop.Name))) {
                                                                                                $outStr += "$($nic1.Name),$($prop.Name),$($nic2results.$($prop.Name)),$($date),`r`n"
                                                                                }
                                                                }
                                                }
                                }
                               
                                $outStr = $outStr.trim()
                                if ($outStr.Length -gt 0) {
                                                Add-Content E:\vmnic_monitoring\$($vmhost.Name)_vmnic.txt $outStr
                                }
 
                                if ($nic1.Link -ne "Up" ) {
                                                $body = "Bringing up $($nic1.Name) on $($vmhost.Name)"
                                                Write-Host $body
                                                Send-MailMessage -To $to -From $from -Subject $subject -Body $body -SmtpServer $server
                                                $esxclis.Item($vmhost.Name).network.nic.up.Invoke(@{"nicname"="$($nic1.Name)"})
                                }
                               
                                if ($nic2 -ne $null -and $nic2.Link -ne "Up" ) {
                                                $body = "Bringing up $($nic2.Name) on $($vmhost.Name)"
                                                Write-Host $body
                                                Send-MailMessage -To $to -From $from -Subject $subject -Body $body -SmtpServer $server
                                                $esxclis.Item($vmhost.Name).network.nic.up.Invoke(@{"nicname"="$($nic2.Name)"})
                                }
                }
               
                $date = Date
                Write-Host "$($date) done with loop"
                Start-Sleep -s 240
                $vmhosts = Get-Cluster -Name $clusterName | Get-VMHost | Sort Name
}
 
$hosts = $cluster | Get-VMHost |sort
$hosts = $hosts | Sort-Object
$result = ""
foreach ($vmhost in $hosts) {
                $vmhost | %{Get-View $_.ID} |
                %{$esxname = $_.Name; Get-View $_.ConfigManager.NetworkSystem} |
                                %{ foreach($physnic in $_.NetworkInfo.Pnic){
                                                $pnicInfo = $_.QueryNetworkHint($physnic.Device)
                                                if ($pnicInfo.Device -eq 'vmnic5' -or $pnicInfo.Device -eq 'vmnic7' ) {
                                                                $myout = "$($esxname) $($physnic.Device) $($pnicInfo.ConnectedSwitchPort.DevId) $($pnicInfo.ConnectedSwitchPort.PortId)"
                                                                $result += $myout
                                                                Write-Output $myout
                                                }
                                               
                                }
                }
}
 
# Sets IP block as private IP in NSX Intelligence
 
$nsxManager = ""
$username = "admin";
$password = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("1234="))
 
 
 
# Required for sending credentials with Basic auth in the header of each request
$authorization = [System.Text.Encoding]::UTF8.GetBytes($username + ':' + $password)
$authorizationString = [System.Convert]::ToBase64String($authorization)
$headers = @{"Authorization" = "Basic $($authorizationString)"}
 
 
$url = "https://$($nsxManager)/api/v1/intelligence/host-config"
 
$response = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $headers -Uri $url
 
$cidrBody = '{
    "private_ip_prefix":  [
                              {
                                  "address_type":  "IPV4",
                                  "address":  "999.0.0.0",
                                  "prefix_length":  8
                              },
                                                                                                                  {
                                  "address_type":  "IPV4",
                                  "address":  "10.0.0.0",
                                  "prefix_length":  8
                              },
                              {
                                  "address_type":  "IPV4",
                                  "address":  "172.16.0.0",
                                  "prefix_length":  12
                              },
                              {
                                  "address_type":  "IPV4",
                                  "address":  "192.168.0.0",
                                  "prefix_length":  16
                              },
                              {
                                  "address_type":  "IPV6",
                                  "address":  "fc00::",
                                  "prefix_length":  7
                              },
                              {
                                  "address_type":  "IPV6",
                                  "address":  "fe80::",
                                 "prefix_length":  10
                              }
                          ]
}'
 
$response = Invoke-RestMethod -Method PATCH -ContentType "application/json" -Headers $headers -Uri $url -Body $cidrBody
 
$response.private_ip_prefix
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
#Create the Security Tags based on vSphere Tags
$vSphereTags = {Get-Tag -Category $categoryName | Select Name}.Invoke()
foreach ($vSphereTag in $vSphereTags) {
                $body = "$($securityTagDefPrefix)$($vSphereTag.Name)$($securityTagDefSuffix)"
                Write-Host "Creating security tag for $($vSphereTag.Name)"
                # After assembling the XML, post to the securityTagUrl
                Invoke-RestMethod -Method Post -ContentType "application/xml" -Headers $headers -Uri $securityTagUrl -Body $body
}
 
# Assign VMs to Security Groups based on vSphere Tag assignments
$securityTagAssignmentPrefix = "https://$($nsxManager)/api/2.0/services/securitytags/tag/"
$tagCategory = Get-TagCategory -Name $categoryName
$tagAssignments = Get-TagAssignment -Category $tagCategory
# Get all Security Tags from NSX Manager
$response = Invoke-RestMethod -Method Get -ContentType "application/json" -Headers $headers -Uri $securityTagUrl
 
foreach ($assignment in $tagAssignments) {
                # extract specific Security Tag based on vSphere Tag name
                $securityTag = $response.securityTags.securityTag |Where-Object {$_.name -eq $assignment.Tag.Name}
                # get the managed object ID of the VM
                $ref = $assignment.entity | Select @{N="MoRef";E={$_.ExtensionData.MoRef}}
                $tagAssignUrl = "$($securityTagAssignmentPrefix)$($securityTag.objectId)/vm/$($ref.MoRef.Value)"
                $body = "$($bodyPrefix)$($assignment.entity.Name)$($bodySuffix)"
                # this PUT assigns a Security Tag to a VM based on IDs instead of name
                Invoke-RestMethod -Method Put -ContentType "application/xml" -Headers $headers -Uri $tagAssignUrl
}
$vmhosts = Get-VMHost
foreach ($vmhost in $vmhosts) {
                Start-VMHostService -HostService ($vmhost  | Get-VMHostService | Where {$_.Key -eq "TSM-SSH"})
                Write-Output "SSH to $($vmhost.Name)"
                echo y | plink root@$($vmhost.Name) -pw $pass "exit"
                plink root@$($vmhost.Name) -pw $pass "echo 'monitor.if_pschange_mc_workaround = \`"TRUE\`"' >> /etc/vmware/config"
                Stop-VMHostService -HostService ($vmhost  | Get-VMHostService | Where {$_.Key -eq "TSM-SSH"}) -Confirm:$false
}
 
foreach ($vmhost in $vmhosts) {
                if (($vmhost.ConnectionState -eq "Connected") -or ($vmhost.ConnectionState -eq "Maintenance")) {
                                $vmhostView = $vmhost | Get-View
                                $firewallView = Get-View -Id $vmhostView.ConfigManager.FirewallSystem
                                $firewallView.DisableRuleset('CIMSLP')
                                Start-VMHostService -HostService ($vmhost  | Get-VMHostService | Where {$_.Key -eq "TSM-SSH"})
                                Write-Output "SSH to $($vmhost.Name)"
                                echo y | plink root@$($vmhost.Name) -pw $pass "exit"
                                plink root@$($vmhost.Name) -pw $pass "/etc/init.d/slpd stop ; chkconfig slpd off"
                                Stop-VMHostService -HostService ($vmhost  | Get-VMHostService | Where {$_.Key -eq "TSM-SSH"}) -Confirm:$false
                }
                else {
                                Write-Output "Skipping $($vmhost.Name) - $($vmhost.ConnectionState)"
                                continue
                }
}
$names = @("fasdfasdf”, “asdfasfasdfas")
$path = 'C:\cert_reqs\ICP'
 
foreach ($name in $names) {
                New-Item -Path $path  -Name $name -ItemType "directory"
                $ipobj = [System.Net.Dns]::GetHostAddresses($name)
                $ip = $ipobj.IPAddressToString
                $template = Get-Content -Path "$($path)\HOSTNAME.cfg" -Raw
                $template = $template.Replace('HOSTNAME',$name)
                $template = $template.Replace('IPADDRESS',$ip)
                $template | Set-Content -Path "$($path)\$($name)\$($name).cfg"
}
 
foreach ($name in $names) {
                cd "$($path)\$($name)"
                openssl genrsa -out "$($name).key" 2048
                openssl req -new -out "$($name).csr" -key "$($name).key" -config "$($name).cfg"
                openssl req -text -noout -in "$($name).csr"
}
 
 
foreach ($datastore in $datastores) {
                New-PSDrive -Location $datastore -Name DS -PSProvider VIMDatstore -Root '\' | Out-Null
                Get-ChildItem -Path DS:\ -Include *.vmdk -Recurse | Select Name,FolderPath | Out-File C:\temp\prod_datastore\$($datastore.Name)
                Remove-PSDrive -Name DS -Confirm:$false
}
 
$switchName = "DEV_dvSwitch01"
$switches = Get-VDSwitch -Name $switchName
 
$vmName = "D255"
$vm = Get-VM -Name $vmName
$networkAdapter = $vm |Get-NetworkAdapter
$vmPortKey = $networkAdapter.ExtensionData.Backing.Port.PortKey
$vmPortGroupKey = $na.ExtensionData.Backing.Port.PortgroupKey
$portGroupName = "$($vm.ExtensionData.Network.Type)-$($vm.ExtensionData.Network.Value)"
$portGroup = Get-VDSwitch | Get-VDPortgroup | Where-Object {$_.id -eq $portGroupName}
 
net-stats -l  |grep d600 |awk '{print $1;}'
pktcap-uw --switchport 50331673 --capture EtherswitchDispath --capture EtherswitchOutput --outfile /tmp/vmxnet3_rcv_srcip.pcap --count 30
 
$vmName = "D251"
switchport=`net-stats -l  |grep d600 |awk ''{print $1;}'' ; pktcap-uw --switchport $switchport --capture EtherswitchDispath --capture EtherswitchOutput --outfile /tmp/vmxnet3_rcv_srcip.pcap --count 30`
plink root@esxi -pw $pas 'switchport=`net-stats -l  |grep prefixmbd600 | cut -f 1 -d " "` ; pktcap-uw --switchport $switchport --capture EtherswitchDispath --capture EtherswitchOutput --outfile /tmp/vmxnet3_rcv_srcip.pcap --count 30'
 
plink root@esxi8  -pw $pass 'echo monitor.if_pschange_mc_workaround = \"TRUE\" >> /tmp/tmp`
$unreachableVMs2 = [System.Collections.ArrayList]@()
$clusterName = "DEV 04"
$cluster = Get-Cluster -Name $clusterName
$vmhosts = $cluster | Get-VMHost |sort
foreach ($vmhost in $vmhosts) {
                $VMs = $vmhost | Get-VM |sort |Where {$_.PowerState -eq 'PoweredOn'}
                $vdpg = Get-VDPortgroup
 
                #[System.Collections.ArrayList] $hostnames = {$VMs.Name}.Invoke()
                $timeout = 100
                $ping = New-Object System.Net.NetworkInformation.Ping
 
                foreach ($vm in $VMs) {
                                $hostname = $vm.Name
                                $response = $ping.Send($hostname,$timeout)
                                if ($response.Status -eq "Success") {
                                                #Write-Output "Was able to ping $($hostname)"
                                }
                                else {
                                                $unreachableVMs2.Add($vm)
                                                $pg = "$($vm.ExtensionData.Network.Type)-$($vm.ExtensionData.Network.Value)"
                                                $pgName = $vdpg | Where-Object {$_.ExtensionData.MoRef -eq $pg}
                                                Write-Output "COULD NOT ping $($hostname) on $($vmhost.Name) - $($pgName)"
                                }
                                $response = $null
                }
}
 
Invoke-WebRequest -Uri "https://vcsa.vmware.com/ph/api/v1/results?deploymentId=addyourown&collectorId=VsanCloudHealth.6_5&objectId=addyourown&type=vsan-updates-json" -OutFile "E:\vsan_dbs\redb.json"
Invoke-WebRequest -Uri "https://partnerweb.vmware.com/service/vsan/all.json" -OutFile "E:\vsan_dbs\hcldb.json"
 
$vmhosts = Get-Cluster -Name "EA_VDI_VSAN_01" | Get-VMHost | Sort Name
 
foreach ($vmhost in $vmhosts) {
                $disks = $vmhost | Get-ScsiLun -LunType Disk | Where-Object {$_.Vendor -like 'EMC'} | Where-Object {$_.MultiPathPolicy -like 'RoundRobin'}
                if ($disks -eq $null) {
                                Write-Host "No EMC disks detected on $($vmhost.Name)"
                }
                else {
                                Write-Host "$($vmhost.Name) Disks"
                                foreach ($disk in $disks) {
                                                Write-Host "IOPS to switch paths changing from $($disk.CommandsToSwitchPath) to 1"
                                                $disk | Set-ScsiLun -CommandsToSwitchPath 1
                                }
                }
}
 
$tempFilePath = 'C:\temp\'
$vcenterServerName = 'theaddress'
 
 
# check to see if last character is a \ and add if missing
if ($tempFilePath[-1] -ne '\') {
                $tempFilePath += "\"
}
 
$vcenterServer = Connect-VIServer $vcenterServerName
if (-not $vcenterServer.isConnected) {
                Write-Host "Unable to connect to vCenter server - check hostname and credentials"
                Write-Host 'Restart script'
                exit
}
 
Set-StrictMode -Version latest
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
 
function Get-SelectedCluster {
                $objForm = New-Object System.Windows.Forms.Form
                $objForm.Text = "Select a Cluster"
                $objForm.Size = New-Object System.Drawing.Size(300,200)
                $objForm.StartPosition = "CenterScreen"
                $objForm.FormBorderStyle = 'Fixed3D'
                $objForm.MaximizeBox = $False
 
                $objForm.KeyPreview = $True
                $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
                                {$x=$objListBox.SelectedItem;$objForm.Close()}})
                $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
                                {$objForm.Close()}})
 
                $OKButton = New-Object System.Windows.Forms.Button
                $OKButton.Location = New-Object System.Drawing.Size(114,120)
                $OKButton.Size = New-Object System.Drawing.Size(75,23)
                $OKButton.Text = "OK"
                $OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()})
                $objForm.Controls.Add($OKButton)
 
                $objLabel = New-Object System.Windows.Forms.Label
                $objLabel.Location = New-Object System.Drawing.Size(10,20)
                $objLabel.Size = New-Object System.Drawing.Size(280,20)
                $objLabel.Text = "Please select a cluster:"
                $objForm.Controls.Add($objLabel)
 
                $objListBox = New-Object System.Windows.Forms.ListBox
                $objListBox.Location = New-Object System.Drawing.Size(10,40)
                $objListBox.Size = New-Object System.Drawing.Size(260,20)
                $objListBox.Height = 80
 
                $allClusters = Get-Cluster | Select Name
                foreach ($item in $allClusters) {
                                [void] $objListBox.Items.Add($item.Name)
                }
 
                $objForm.Controls.Add($objListBox)
 
                $objForm.Topmost = $True
 
                $objForm.Add_Shown({$objForm.Activate()})
                [void] $objForm.ShowDialog()
 
                return $objListBox.SelectedItem
}
 
function Get-SelectedVDS {
                $objForm = New-Object System.Windows.Forms.Form
                $objForm.Text = "Select a vSwitch"
                $objForm.Size = New-Object System.Drawing.Size(300,200)
                $objForm.StartPosition = "CenterScreen"
                $objForm.FormBorderStyle = 'Fixed3D'
                $objForm.MaximizeBox = $False
 
                $objForm.KeyPreview = $True
                $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
                                {$x=$objListBox.SelectedItem;$objForm.Close()}})
                $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
                                {$objForm.Close()}})
 
                $OKButton = New-Object System.Windows.Forms.Button
                $OKButton.Location = New-Object System.Drawing.Size(114,120)
                $OKButton.Size = New-Object System.Drawing.Size(75,23)
                $OKButton.Text = "OK"
                $OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()})
                $objForm.Controls.Add($OKButton)
 
 
                $objLabel = New-Object System.Windows.Forms.Label
                $objLabel.Location = New-Object System.Drawing.Size(10,20)
                $objLabel.Size = New-Object System.Drawing.Size(280,20)
                $objLabel.Text = "Please select a distributed vSwitch:"
                $objForm.Controls.Add($objLabel)
 
                $objListBox = New-Object System.Windows.Forms.ListBox
                $objListBox.Location = New-Object System.Drawing.Size(10,40)
                $objListBox.Size = New-Object System.Drawing.Size(260,20)
                $objListBox.Height = 80
 
                $allVds = Get-VDSwitch |select Name
                foreach ($item in $allVds) {
                                [void] $objListBox.Items.Add($item.Name)
                }
 
                $objForm.Controls.Add($objListBox)
 
                $objForm.Topmost = $True
 
                $objForm.Add_Shown({$objForm.Activate()})
                [void] $objForm.ShowDialog()
 
                return $objListBox.SelectedItem
 
}
 
$clusterName = Get-SelectedCluster
 
try {
                $esxiHost = Get-Cluster $clusterName | Get-VMHost | Select  Name,PowerState |Where-Object {$_.PowerState -eq "PoweredOn"} |Select -first 1 Name
}
catch {
                Write-Host 'Cluster not found, check the name has been entered correctly'
                Write-Host 'Restart script'
                exit
}
 
try {
                $selectedVdsName = Get-SelectedVDS
                $vds = Get-VDSwitch -Name $selectedVdsName
}
catch {
                Write-Host 'Distributed vSwitch not found, check the name has been entered correctly'
                Write-Host 'Restart script'
                exit
}
 
$hostName = $esxiHost.Name
Write-Host 'Exporting port groups from reference host' $hostName 'in cluster' $clusterName
 
if (-Not (Test-Path -Path $tempFilePath) ) {
                Write-Host 'Creating port group export directory' $tempFilePath
                New-Item -ItemType directory -Path $tempFilePath
}
 # Get all port groups from reference host in cluster and export into CSV file
$exportFileName = "$($tempFilePath)$($clusterName)-$($hostName).csv"
Get-VirtualPortGroup -VMHost $hostName |select name,VlanId |export-csv $exportFileName
# Edit file to add underscore (_) to port group name
[io.file]::readalltext($exportFileName).replace("VLAN ","VLAN_") | Out-File $exportFileName -Encoding ascii -Force
<# Remove all other port groups from file by removing every line that doesn't have the word vlan in it, save to new file #>
$newFileContent = Get-Content $exportFileName | Where-Object {$_ -match 'vlan'}
# Getting and Setting in the same line will result in an error because the original file is still open
$newFileContent | Set-Content $exportFileName
 
# By this point, folder and dvSwitch should be MANUALLY created for cluster or cluster group - select already created distributed vSwitch
Import-csv $exportFileName | %{New-VDPortgroup -VDSwitch $vds -Name $_.Name -NumPorts 256 -VlanId $_.VlanId}