build 7bbbddf7 | content blog-content@c8490fa · 338 posts | profiles 20 | 0 skipped | | format
apiVersion: soultec.ch/v1kind: Listmetadata: name: nerd/code locale: en labels: lines: 3574 posts: 42 symbols: 101 span: 2014–2026 annotations: route: /en/nerd/code/spec: collection: posts locale: en extract: fenced code blocks sort: date descstatus: count: 130 items: - {ref: lang/bash} - {ref: lang/powershell} - {ref: lang/text} - {ref: lang/yaml} - {ref: lang/properties}
{ "apiVersion": "soultec.ch/v1", "kind": "List", "metadata": { "name": "nerd/code", "locale": "en", "labels": { "lines": "3574", "posts": "42", "symbols": "101", "span": "2014–2026" }, "annotations": { "route": "/en/nerd/code/" } }, "spec": { "collection": "posts", "locale": "en", "extract": "fenced code blocks", "sort": "date desc" }, "status": { "count": 130, "items": [ { "ref": "lang/bash" }, { "ref": "lang/powershell" }, { "ref": "lang/text" }, { "ref": "lang/yaml" }, { "ref": "lang/properties" } ] }}
apiVersion = "soultec.ch/v1"kind = "List"[metadata]name = "nerd/code"locale = "en"[metadata.labels]lines = "3574"posts = "42"symbols = "101"span = "2014–2026"[metadata.annotations]route = "/en/nerd/code/"[spec]collection = "posts"locale = "en"extract = "fenced code blocks"sort = "date desc"[status]count = 130[[status.items]]ref = "lang/bash"[[status.items]]ref = "lang/powershell"[[status.items]]ref = "lang/text"[[status.items]]ref = "lang/yaml"[[status.items]]ref = "lang/properties"
<?xml version="1.0" encoding="UTF-8"?><manifest kind="List"> <apiVersion>soultec.ch/v1</apiVersion> <metadata> <name>nerd/code</name> <locale>en</locale> <labels> <lines>3574</lines> <posts>42</posts> <symbols>101</symbols> <span>2014–2026</span> </labels> <annotations> <route>/en/nerd/code/</route> </annotations> </metadata> <spec> <collection>posts</collection> <locale>en</locale> <extract>fenced code blocks</extract> <sort>date desc</sort> </spec> <status> <count>130</count> <items> <item> <ref>lang/bash</ref> </item> <item> <ref>lang/powershell</ref> </item> <item> <ref>lang/text</ref> </item> <item> <ref>lang/yaml</ref> </item> <item> <ref>lang/properties</ref> </item> </items> </status></manifest>

From the work

Code corpus

Every code block we have published: 130 blocks from 42 posts, 2014–2026. None of it was written for this page. It is what came out of the work and got written down.

  • 130 blocks
  • 3574 lines
  • 42 posts
  • 101 symbols

By language

Language blocks lines
bash 48 741
powershell 39 2389
text 37 388
yaml 4 50
properties 2 6

By symbol

Cmdlets and tools appearing in at least two blocks.

63 further symbols appear once only and are not listed here.

The blocks

# Get the JSON Web Token (JWT)
TOKEN=$(curl -sk -u "USER@DOMAIN" \
-X POST https://SUPERVISOR_FQDN_OR_IP/wcp/login | jq -r '.session_id')

# Query all vSphere Namespaces
curl -k -H "Authorization: Bearer ${TOKEN}" -X GET https://SUPERVISOR_FQDN_OR_IP/api/v1/namespaces | jq -r '.items[].metadata.name'

# Output
default
kube-node-lease
kube-public
kube-state-metrics-139ce
kube-system
svc-argocd
svc-argocd-service-3srmt
svc-auto-attach-1hnu0
svc-cci-ns-xk907
svc-configuration-tbe79
svc-consumption-operator-63v75
svc-contour-m8mn1
svc-harbor-jpft6
svc-metrics-aggregator-rs4er
svc-pais-lyk5h
svc-secret-store-6rqli
svc-supervisor-management-proxy-l4g5n
svc-tkg-gf8p0
svc-tmc-c9
svc-velero-od4zi
svc-vks-cluster-manager-service-3873a
vmware-system-ako
vmware-system-appplatform-operator-system
vmware-system-cert-manager
vmware-system-csi
vmware-system-imageregistry
vmware-system-kubeimage
vmware-system-logging
vmware-system-mgmt-proxy
vmware-system-mobility-operator
vmware-system-monitoring
vmware-system-netop
vmware-system-network-operations
vmware-system-nsop
vmware-system-nsx
vmware-system-pinniped
vmware-system-supervisor-services
vmware-system-supervisor-services-vpc
vmware-system-vks-public
vmware-system-vmop
vmware-system-workload-cli
vmware-system-zoneop
curl

apiVersion: v1
kind: Config
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: https://SUPERVISOR_IP:443
  name: vcf-mgmt-sn91:SUPERVISOR_IP
contexts:
- context:
    cluster: vcf-mgmt-sn91:SUPERVISOR_IP
    user: vcf-mgmt-sn91:USER@[email protected]
  name: vcf-mgmt-sn91
current-context: vcf-mgmt-sn91
users:
- name: vcf-mgmt-sn91:USER@DOMAIN@SUPERVISOR_IP
  user:
    token: REDACTED_JWT
$ErrorActionPreference = "Stop"
$HubUrl = "https://packages.omnissa.com/wsone/AirwatchAgent.msi"
$MsiPath = "C:\Windows\Temp\AirwatchAgent.msi"
$LogPath = "C:\Windows\Temp\WorkspaceONE_Hub_Enrollment.log"
$Server = "ds1234.awmdm.com"
$GroupId = "WINSRV"
$Username = "[email protected]"
Invoke-WebRequest -Uri $HubUrl -OutFile $MsiPath
if (-not (Test-Path -LiteralPath $MsiPath)) {
throw "Intelligent Hub MSI was not downloaded."
}
$SecurePassword = Read-Host "Enter the password for $Username" -AsSecureString
$PasswordPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
try {
$Password = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($PasswordPointer)
$MsiArguments = @(
"/i `"$MsiPath`""
"/qn"
"/norestart"
"/L*v `"$LogPath`""
"ENROLL=Y"
"SERVER=$Server"
"LGNAME=$GroupId"
"USERNAME=$Username"
"PASSWORD=`"$Password`""
"DEVICEOWNERSHIPTYPE=CD"
"ASSIGNTOLOGGEDINUSER=N"
) -join " "

$Process = Start-Process `
-FilePath "msiexec.exe" `
-ArgumentList $MsiArguments `
-Wait `
-PassThru

Write-Host "MSI exit code: $($Process.ExitCode)"
Write-Host "MSI log: $LogPath"
}
finally {
if ($PasswordPointer -ne [IntPtr]::Zero) {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($PasswordPointer)
}
Remove-Variable Password -ErrorAction SilentlyContinue
Remove-Variable SecurePassword -ErrorAction SilentlyContinue
}
Invoke-WebRequestRead-HostRemove-VariableStart-ProcessTest-PathWrite-Host
Get-Service -ErrorAction SilentlyContinue |
Where-Object {
$_.Name -match "Airwatch|Workspace" -or
$_.DisplayName -match "Airwatch|Workspace ONE"
} |
Format-Table Name, DisplayName, Status -AutoSize
Format-TableGet-ServiceWhere-Object
$LogFolder = "C:\ProgramData\AirWatch\UnifiedAgent\Logs"
$EnrollmentLog = Get-ChildItem -Path $LogFolder `
-Filter "DeviceEnrollment-*.log" `
-ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if ($EnrollmentLog) {
Get-Content -Path $EnrollmentLog.FullName -Tail 100
}
else {
Write-Host "No DeviceEnrollment log was found."
}
Get-ChildItemGet-ContentSelect-ObjectSort-ObjectWrite-Host
netsh interface ipv4 set address name="INTERFACE_NAME" static IP_ADDRESS SUBNET_MASK GATEWAY

netsh interface ipv4 set dnsservers name="INTERFACE_NAME" static DNS_SERVER primary

netsh interface ipv4 add dnsservers name="INTERFACE_NAME" address=SECONDARY_DNS_SERVER index=2
netsh interface ipv4 set address name="Ethernet0" static 192.168.1.50 255.255.255.0 192.168.1.1

netsh interface ipv4 set dnsservers name="Ethernet0" static 192.168.1.10 primary

netsh interface ipv4 add dnsservers name="Ethernet0" address=192.168.1.11 index=2
bash ESX 9.0 NVMe Memory Tiering 12 lines
 [root@hades:~] esxcli storage core device partition list
Device Partition Start Sector End Sector Type Size
-------------------------------------------------------------------- --------- ------------ ---------- ---- -------------
t10.NVMe____Samsung_SSD_990_EVO_Plus_2TB____________755B42415C382500 0 0 3907029167 0 2000398934016
mpx.vmhba33:C0:T0:L0 0 0 976773167 0 500107862016
mpx.vmhba33:C0:T0:L0 1 2048 976768064 fb 500104200704
mpx.vmhba32:C0:T0:L0 0 0 30283007 0 15504900096
mpx.vmhba32:C0:T0:L0 1 64 204863 0 104857600
mpx.vmhba32:C0:T0:L0 5 208896 2306047 6 1073741824
mpx.vmhba32:C0:T0:L0 6 2308096 4405247 6 1073741824
mpx.vmhba32:C0:T0:L0 7 4407296 30282974 f8 13248347648
t10.NVMe____Samsung_SSD_990_EVO_Plus_2TB____________7D5B42415C382500 0 0 3907029167 0 2000398934016
esxcli
bash ESX 9.0 NVMe Memory Tiering 2 lines

esxcli system tierdevice create -d /vmfs/devices/disks/t10.NVMe____Samsung_SSD_990_EVO_Plus_2TB____________7D5B42415C382500
esxcli
cp /usr/lib/vmware-vmca/share/config/certool.cfg /tmp/vcma.cfg
cd /usr/lib/vmware-vmca/bin/
./certool --genselfcacert --outprivkey /tmp/key.key --outcert /tmp/vcma.cer --config /tmp/vcma.cfg
./certool --rootca --cert /tmp/vcma.cer --privkey /tmp/key.key
service-control --stop --all
service-control --start vmafdd
service-control --start vmdird
service-control --start vmcad
/usr/lib/vmware-vmafd/bin/dir-cli trustedcert publish --cert /tmp/vcma.cer
service-control --start --all
bash vSphere Supervisor Services 2 lines

kubectl get secret stlab-argocd-cluster -o jsonpath='{.data.admin\.password}' | base64 -d
kubectl

# [STEP-1]
# Login to a NSX manager via root user
# Get the respective T1 gateway ID of the newly created vSphere Namespace
curl -k -u 'admin:PASSWORD' --request GET 'https://localhost/policy/api/v1/infra/tier-1s' | grep VSPHERE_NAMESPACE_T1_NAME-rtr -B 1
"id" : "t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr",
"display_name" : "t1-domain-c5008:23e875a6-44gf-4814-94ff-e840ghm7bc03-VSPHERE_NAMESPACE_T1_NAME-rtr",

# [STEP-2]
# Get the locale-services ID of the respective T1 gateway
# locale-servces ID = t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr-0

curl -k -u 'admin:PASSWORD' --request GET 'https://localhost/policy/api/v1/infra/tier-1s/t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr/locale-servces'
{
"results" : [ {
"edge_cluster_path" : "/infra/sites/default/enforcement-points/default/edge-clusters/294ss994-8128-4217-aa42-a182b954ak8b",
"resource_type" : "LocaleServices",
"id" : "t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr-0",
"display_name" : "t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr-0",
"path" : "/infra/tier-1s/t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr/locale-services/t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr-0",
"relative_path" : "t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr-0",
"parent_path" : "/infra/tier-1s/t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr",
"remote_path" : "",
"unique_id" : "84ca333a-8619-d3f31-a108-13d222c4c349",
"realization_id" : "84ca333a-8619-d3f31-a108-13d222c4c349",
"owner_id" : "48cb77bb-9t43-4285-a245-b2117f8a8b87",
"marked_for_delete" : false,
"overridden" : false,
"_create_time" : 1730469777339,
"_create_user" : "wcp-cluster-user-380fdd7d-6f2c-4cdw-82df-fb7dfddd1b9b-dbd7f126-633c-4a13-badf-f5wwd8cfd11e",
"_last_modified_time" : 1732889723175,
"_last_modified_user" : "admin",
"_system_owned" : false,
"_protection" : "REQUIRE_OVERRIDE",
"_revision" : 1
} ],
"result_count" : 1,
"sort_by" : "display_name",
"sort_ascending" : true

# Verify the associated edge cluster in the 'edge_cluster_path' parameter

curl -k -u 'admin:PASSWORD' --request GET 'https://localhost/policy/api/v1/infra/sites/default/enforcement-points/default/edge-clusters' | grep '\"id\" : \"294ss994-8128-4217-aa42-a182b954ak8b\"' -A 1
"id" : "294ss994-8128-4217-aa42-a182b954ak8b",
"display_name" : "k8s-t0-ec",

# [STEP-3]
# Get the 'path' parameter of the desired T1 edge cluster
# Current edge cluster = 294ss994-8128-4217-aa42-a182b954ak8b
# Desired edge cluster = 486hc7c3-2d29-ad51-b6c3-ff52alo86f4b

curl -k -u 'admin:PASSWORD' --request GET 'https://localhost/policy/api/v1/infra/sites/default/enforcement-points/default/edge-clusters'
{
"results" : [ {
"nsx_id" : "294ss994-8128-4217-aa42-a182b954ak8b",
"inter_site_forwarding_enabled" : false,
"member_node_type" : "EDGE_NODE",
"resource_type" : "PolicyEdgeCluster",
"id" : "294ss994-8128-4217-aa42-a182b954ak8b",
"display_name" : "k8s-t0-ec",
"tags" : [ ],
"path" : "/infra/sites/default/enforcement-points/default/edge-clusters/294ss994-8128-4217-aa42-a182b954ak8b",
"relative_path" : "294ss994-8128-4217-aa42-a182b954ak8b",
"parent_path" : "/infra/sites/default/enforcement-points/default",
"remote_path" : "",
"unique_id" : "294ss994-8128-4217-aa42-a182b954ak8b",
"realization_id" : "294ss994-8128-4217-aa42-a182b954ak8b",
"owner_id" : "48cb77bb-9t43-4285-a245-b2117f8a8b87",
"marked_for_delete" : false,
"overridden" : false,
"_create_time" : 1702468345681,
"_create_user" : "admin",
"_last_modified_time" : 1702471331793,
"_last_modified_user" : "admin",
"_system_owned" : false,
"_protection" : "NOT_PROTECTED",
"_revision" : 1
}, {
"nsx_id" : "486hc7c3-2d29-ad51-b6c3-ff52alo86f4b",
"inter_site_forwarding_enabled" : false,
"member_node_type" : "EDGE_NODE",
"resource_type" : "PolicyEdgeCluster",
"id" : "486hc7c3-2d29-ad51-b6c3-ff52alo86f4b",
"display_name" : "k8s-t1-ec",
"tags" : [ ],
"path" : "/infra/sites/default/enforcement-points/default/edge-clusters/486hc7c3-2d29-ad51-b6c3-ff52alo86f4b",
"relative_path" : "486hc7c3-2d29-ad51-b6c3-ff52alo86f4b",
"parent_path" : "/infra/sites/default/enforcement-points/default",
"remote_path" : "",
"unique_id" : "486hc7c3-2d29-ad51-b6c3-ff52alo86f4b",
"realization_id" : "486hc7c3-2d29-ad51-b6c3-ff52alo86f4b",
"owner_id" : "48cb77bb-9t43-4285-a245-b2117f8a8b87",
"marked_for_delete" : false,
"overridden" : false,
"_create_time" : 1702468349973,
"_create_user" : "admin",
"_last_modified_time" : 1702471337162,
"_last_modified_user" : "admin",
"_system_owned" : false,
"_protection" : "NOT_PROTECTED",
"_revision" : 1
} ],
"result_count" : 2,
"sort_by" : "display_name",
"sort_ascending" : true

# [STEP-4]
# Update the 'edge_cluster_path' parameter in the T1 locale-services from step 2 to the desired T1 edge cluster path from step 3

curl -k -u 'admin:PASSWORD' \
--request PUT 'https://localhost/policy/api/v1/infra/tier-1s/t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr/locale-servces/t1_778759f1-e306-3322-8fe4-6ddkjh658b09_rtr-0' \
--header 'X-Allow-Overwrite: True' \
--header 'Content-Type: application/json' \
--data-raw '{
"edge_cluster_path": "/infra/sites/default/enforcement-points/default/edge-clusters/486hc7c3-2d29-ad51-b6c3-ff52alo86f4b",
"_revision": 0
}'
curl
text IaaS Control Plane – API inaccessible 7 lines
Initialized vSphere resources
Deployed Control Plane VMs
Configured Control Plane VMs
Configured Load Balancer fronting the kubernetes API Server
Configured Core Supervisor Services
Service: velero.vsphere.vmware.com. Status: Configuring
Service: tkg.vsphere.vmware.com. Reason: Reconciling. Message: Reconciling.
bash IaaS Control Plane – API inaccessible 3 lines
cat /var/log/pods/kube-system_etcd-4233ab1d5ddccf36bc5bba316d1972b0_654c066164da8fbdd6d33ad93af301dc/etcd/10364.log

stderr F {"level":"warn","ts":"2024-10-08T18:22:39.077642Z","caller":"wal/repair.go:81","msg":"failed to copy","from":"/var/lib/etcd/member/wal/0000000000000181-000000001c149b6d.wal.broken","to":"/var/lib/etcd/member/wal/0000000000000181-000000001c149b6d.wal","error":"write /var/lib/etcd/member/wal/0000000000000181-000000001c149b6d.wal.broken: no space left on device"}
bash IaaS Control Plane – API inaccessible 12 lines
 
find / -path /proc -prune -o -type f -exec du -Sh {} + | sort -rh | head -n 10
1.1G /var/log/vmware/upgrade-ctl-cli.log.1
884M /var/log/vmware/svchost/stderr.log
730M /var/log/vmware/upgrade-ctl-cli.log
385M /var/log/vmware/audit/kube-apiserver.log
307M /var/log/vmware/fluentbit/consolidated.log
250M /storage/container-registry/docker/registry/v2/blobs/sha256/a0/a0dd531132ecd058d0b0249cf2f32cecccdfbe8d13cfb93b75101aafcd2a50a6/data
248M /var/lib/containerd/io.containerd.content.v1.content/blobs/sha256/4364e490859d064c9434f9e480d74bc62402a0d812480201d644a4ea9d7ff6c3
248M /storage/container-registry/docker/registry/v2/blobs/sha256/43/4364e490859d064c9434f9e480d74bc62402a0d812480201d644a4ea9d7ff6c3/data
234M /var/lib/containerd/io.containerd.content.v1.content/blobs/sha256/fcb275778b51abf28182241bffffc6f9a25861f29ed844d71364f59e4485fb1e
234M /storage/container-registry/docker/registry/v2/blobs/sha256/fc/fcb275778b51abf28182241bffffc6f9a25861f29ed844d71364f59e4485fb1e/data
bash IaaS Control Plane – API inaccessible 6 lines
 
echo > /var/log/vmware/upgrade-ctl-cli.log.1
echo > /var/log/vmware/svchost/stderr.log
echo > /var/log/vmware/upgrade-ctl-cli.log
echo > /var/log/vmware/audit/kube-apiserver.log
echo > /var/log/vmware/fluentbit/consolidated.log
bash IaaS Control Plane – API inaccessible 28 lines
etcdctl member list -w table
+------------------+---------+----------------------------------+----------------------------+----------------------------+------------+
| ID | STATUS | NAME | PEER ADDRS | CLIENT ADDRS | IS LEARNER |
+------------------+---------+----------------------------------+----------------------------+----------------------------+------------+
| 10a00138f3a1ed4f | started | 421dd5792ebae985affbca516bb385c7 | https://172.16.100.11:2380 | https://172.16.100.11:2379 | false |
| 7546e437eef94d66 | started | 421d85be9b7ab8b9dad06f0c6487d976 | https://172.16.100.12:2380 | https://172.16.100.12:2379 | false |
| dec23b7a3b3cc58a | started | 421d411b9b2dca2e5176b3ff2dd4b66f | https://172.16.100.13:2380 | https://172.16.100.13:2379 | false |
+------------------+---------+----------------------------------+----------------------------+----------------------------+------------+

# Check the endpoint status of all members and get the leader.
etcdctl --endpoints=https://172.16.100.11:2379,https://172.16.100.12:2379,https://172.16.100.13:2379 -w table endpoint status
+----------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
| ENDPOINT | ID | VERSION | DB SIZE | IS LEADER | IS LEARNER | RAFT TERM | RAFT INDEX | RAFT APPLIED INDEX | ERRORS |
+----------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
| https://172.16.100.11:2379 | 10a00138f3a1ed4f | 3.5.11 | 164 MB | false | false | 318 | 668808659 | 668808659 | |
| https://172.16.100.12:2379 | 7546e437eef94d66 | 3.5.11 | 164 MB | true | false | 318 | 668808659 | 668808659 | |
| https://172.16.100.13:2379 | dec23b7a3b3cc58a | 3.5.11 | 165 MB | false | false | 318 | 668808659 | 668808659 | |
+----------------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+

# Check the endpoint health of all members.
etcdctl --endpoints=https://172.16.100.11:2379,https://172.16.100.12:2379,https://172.16.100.13:2379 -w table endpoint health
+----------------------------+--------+-------------+-------+
| ENDPOINT | HEALTH | TOOK | ERROR |
+----------------------------+--------+-------------+-------+
| https://172.16.100.11:2379 | true | 15.673792ms | |
| https://172.16.100.11:2379 | true | 17.78887ms | |
| https://172.16.100.11:2379 | true | 15.571392ms | |
+----------------------------+--------+-------------+-------+
# NVIDIA L40S Profiles
# B-Series Virtual GPU Types for NVIDIA L40S
nvidia_l40s-1b=48
nvidia_l40s-2b=24

# Q-Series Virtual GPU Types for NVIDIA L40S
nvidia_l40s-1q=48
nvidia_l40s-2q=24
nvidia_l40s-3q=16
nvidia_l40s-4q=12
nvidia_l40s-6q=8
nvidia_l40s-8q=6
nvidia_l40s-12q=4
nvidia_l40s-16q=3
nvidia_l40s-24q=2
nvidia_l40s-48q=1

# A-Series Virtual GPU Types for NVIDIA L40S
nvidia_l40s-1a=48
nvidia_l40s-2a=24
nvidia_l40s-3a=16
nvidia_l40s-4a=12
nvidia_l40s-6a=8
nvidia_l40s-8a=6
nvidia_l40s-12a=4
nvidia_l40s-16a=3
nvidia_l40s-24a=2
nvidia_l40s-48a=1
text Storage performance testing with vdbench 14 lines
hd=default,shell=vdbench,user=administrator
hd=one
sd=sd_01,lun=\\.\PHYSICALDRIVE1,size=600G,host=one,threads=16
sd=sd_02,lun=\\.\PHYSICALDRIVE2,size=600G,host=one,threads=16
sd=sd_03,lun=\\.\PHYSICALDRIVE3,size=600G,host=one,threads=16
sd=sd_04,lun=\\.\PHYSICALDRIVE4,size=600G,host=one,threads=16
*This is our workload definition. Here we use seekpct=eof to tell vdbench to:
*write random data until it completely writes to the entire lun , rdcpct=0 sets the
*workload to 100% write and xfersize determines the block size. In this case we
*set the block size to 256k
wd=wd1,sd=*,hd=*,seekpct=eof,rdpct=0,xfersize=256k
*This is our run definition. It tells vdbench to run the workload definition
* defined in wd1 above at the maximum iorate it can sustain. The elapsed time *does not matter here. The script will stop when eof is reached as per the *workload definition.
rd=rd1,wd=wd1,elapsed=144000,interval=1,iorate=max,openflags=directio
text Storage performance testing with vdbench 18 lines
*prefill - 256k seq
wd=wd1,host=*,sd=*,rdpct=0,xf=256k,seekpct=eof
*8k 100Read 100Random - Small Random Reads
wd=wd2,host=*,sd=*,rdpct=100,xf=8k,seekpct=100
*8k 100Write 100Random - Small Random Writes
wd=wd3,host=*,sd=*,rdpct=0,xf=8k,seekpct=100
*16k 60Read 40Write 100Random - Small Mix-Read-Write Random
wd=wd4,host=*,sd=*,rdpct=60,xf=16k,seekpct=100
*256k 100Read 100Seq - Large Sequential Read
wd=wd5,host=*,sd=*,rdpct=100,xf=256k,seekpct=0
*256k 100Write 100Seq - Large Sequential Write
wd=wd6,host=*,sd=*,rdpct=0,xf=256k,seekpct=0
*32k 100Read 100Random - Avg Random Reads
wd=wd7,host=*,sd=*,rdpct=100,xf=32k,seekpct=100
*64K 70Read 30Write 100Random - Avg Mixed-Read-Write Random
wd=wd8,host=*,sd=*,rdpct=100,xf=80k,seekpct=100
*4k-50% 32k-50% 60Read 40Write 100Random - Mixed BlockSize Random
wd=wd9,host=*,sd=*,rdpct=60,xf=(4k,50,32k,50),seekpct=100
text Storage performance testing with vdbench 35 lines
concatenate=no
dedupratio=1.5
compratio=3.0
dedupunit=16k
hd=default,vdbench=c:\vdbench,user=Administrator,shell=vdbench,jvms=4 hd=one,system=localhost
sd=default,openflags=directio,size=950g
sd=sd1,host=one,Lun=\\.\PHYSICALDRIVE1
sd=sd2,host=one,Lun=\\.\PHYSICALDRIVE2
sd=sd3,host=one,Lun=\\.\PHYSICALDRIVE3
sd=sd4,host=one,Lun=\\.\PHYSICALDRIVE4
sd=sd5,host=one,Lun=\\.\PHYSICALDRIVE5
sd=sd6,host=one,Lun=\\.\PHYSICALDRIVE6
sd=sd7,host=one,Lun=\\.\PHYSICALDRIVE7
sd=sd8,host=one,Lun=\\.\PHYSICALDRIVE8
*prefill - 256kseq
wd=wd1,host=*,sd=*,rdpct=0,xf=256k,seekpct=eof
*8k 100Read 100Random - Small Random Reads
wd=wd2,host=*,sd=*,rdpct=100,xf=8k,seekpct=100
*8k 100Write 100Random - Small Random Writes
wd=wd3,host=*,sd=*,rdpct=0,xf=8k,seekpct=100
*16k 60Read 40Write 100Random - Small Mix-Read-Write Random
wd=wd4,host=*,sd=*,rdpct=60,xf=16k,seekpct=100
*256k 100Read 100Seq - Large Sequential Read
wd=wd5,host=*,sd=*,rdpct=100,xf=256k,seekpct=0
*256k 100Write 100Seq - Large Sequential Write
wd=wd6,host=*,sd=*,rdpct=0,xf=256k,seekpct=0
*32k 100Read 100Random - Avg Random Reads
wd=wd7,host=*,sd=*,rdpct=100,xf=32k,seekpct=100
*64K 70Read 30Write 100Random - Avg Mixed-Read-Write Random
wd=wd8,host=*,sd=*,rdpct=100,xf=80k,seekpct=100
*8k 100Read 100Random
wd=wd9,host=*,sd=*,rdpct=100,xf=4k,seekpct=100
*8k 100Write 100Random
wd=wd10,host=*,sd=*,rdpct=0,xf=4k,seekpct=100
rd=rd1,wd=wd2,el=900,in=1,warmup=300,forthreads=(32),iorate=max
text Storage performance testing with vdbench 26 lines
concatenate=no
dedupratio=1.5
compratio=3.0
dedupunit=16k
hd=default,vdbench=c:\vdbench50407,user=Administrator,shell=vdbench,jvms=4
hd=one,system=localhost
sd=default,openflags=directio,size=950g
sd=sd1,host= one,Lun=\\.\PHYSICALDRIVE1
sd=sd2,host= one,Lun=\\.\PHYSICALDRIVE2
sd=sd3,host= one,Lun=\\.\PHYSICALDRIVE3
sd=sd4,host= one,Lun=\\.\PHYSICALDRIVE4
sd=sd5,host= one,Lun=\\.\PHYSICALDRIVE5
sd=sd6,host= one,Lun=\\.\PHYSICALDRIVE6
sd=sd7,host= one,Lun=\\.\PHYSICALDRIVE7
sd=sd8,host= one,Lun=\\.\PHYSICALDRIVE8
*prefill - 256kseq
wd=wd1,host=*,sd=*,rdpct=0,xf=256k,seekpct=eof
*8k-50% 32k-50% 60Read 40Write 100Random - Mixed BlockSize Random
wd=wd9,host=*,sd=*,rdpct=60,xf=(8k,50,32k,50),seekpct=100
*8k 60Read 40Write 100Random 128K 50Read 50Write 100Seq **wd10 and wd11 will complete this
wd=wd10,host=*,sd=*,rdpct=60,xf=8k,seekpct=100
wd=wd11,host=*,sd=*,rdpct=50,xf=128k,seekpct=0
*When running wd10 & wd11 loop as *wd=(wd10,wd11) at bottow in rd= section
*4k-20% 8k-20% 16k-20% 64k-20% 128k-10% 256k-10% 65Read 35Write 70Random
wd=wd16,host=*,sd=*,rdpct=65,xf=(4k,20,8k,20,16k,20,64k,20,128k,10,256k,10),seekpct=70
rd=rd1,wd=wd9,el=900,in=1,warmup=300,forthreads=(32),iorate=max
hd=host1,system=localhost
hd=host2,system=192.168.1.2
hd=host3,system=192.168.1.3
hd=host4,system=192.168.1.4
sd=sd1,host=host1,Lun=\\.\PHYSICALDRIVE1
sd=sd2,host=host2,Lun=\\.\PHYSICALDRIVE1
sd=sd3,host=host3,Lun=\\.\PHYSICALDRIVE1
sd=sd4,host=host4,Lun=\\.\PHYSICALDRIVE1
text Storage performance testing with vdbench 29 lines
hd=default,shell=vdbench,user=administrator
hd=host1,system=localhost
hd=host2,system=192.168.1.2
hd=host3,system=192.168.1.3
hd=host4,system=192.168.1.4
sd=sd_11,host=host1,lun=\\.\PHYSICALDRIVE1,size=600G,threads=16
sd=sd_12,host=host1,lun=\\.\PHYSICALDRIVE2,size=600G,threads=16
sd=sd_13,host=host1,lun=\\.\PHYSICALDRIVE3,size=600G,threads=16
sd=sd_14,host=host1,lun=\\.\PHYSICALDRIVE4,size=600G,threads=16
sd=sd_21,host=host2,lun=\\.\PHYSICALDRIVE1,size=600G,threads=16
sd=sd_22,host=host2,lun=\\.\PHYSICALDRIVE2,size=600G,threads=16
sd=sd_23,host=host2,lun=\\.\PHYSICALDRIVE3,size=600G,threads=16
sd=sd_24,host=host2,lun=\\.\PHYSICALDRIVE4,size=600G,threads=16
sd=sd_31,host=host3,lun=\\.\PHYSICALDRIVE1,size=600G,threads=16
sd=sd_32,host=host3,lun=\\.\PHYSICALDRIVE2,size=600G,threads=16
sd=sd_33,host=host3,lun=\\.\PHYSICALDRIVE3,size=600G,threads=16
sd=sd_34,host=host3,lun=\\.\PHYSICALDRIVE4,size=600G,threads=16
sd=sd_41,host=host4,lun=\\.\PHYSICALDRIVE1,size=600G,threads=16
sd=sd_42,host=host4,lun=\\.\PHYSICALDRIVE2,size=600G,threads=16
sd=sd_43,host=host4,lun=\\.\PHYSICALDRIVE3,size=600G,threads=16
sd=sd_44,host=host4,lun=\\.\PHYSICALDRIVE4,size=600G,threads=16
*This is our workload definition. Here we use seekpct=eof to tell vdbench to:
*write random data until it completely writes to the entire lun , rdcpct=0 sets the
*workload to 100% write and xfersize determines the block size. In this case we
*set the block size to 256k
wd=wd1,host=*,sd=sd_*,seekpct=eof,rdpct=0,xfersize=256k
*This is our run definition. It tells vdbench to run the workload definition
* defined in wd1 above at the maximum iorate it can sustain. The elapsed time *does not matter here. The script will stop when eof is reached as per the *workload definition.
rd=rd1,wd=wd*,elapsed=144000,interval=1,iorate=max,openflags=directio
yaml Integrating Antrea into NSX 14 lines
 
# Change into respective vSphere Namespace where TKC is located
kubectl config use-context VSPHERE_NAMESPACE

# Check the assocaited Antrea package of the respective TKC
kubectl get antreaconfigs.cni.tanzu.vmware.com CLUSTER_NAME-antrea-package \
--output yaml | grep antrea.tanzu.vmware.com

# Sample output from an antrea-package
apiVersion: cni.tanzu.vmware.com/v1alpha1
kind: AntreaConfig
  metadata:
    labels:
      tkg.tanzu.vmware.com/package-name: antrea.tanzu.vmware.com.1.11.3---vmware.2-tkg.2-advanced
kubectl
yaml Integrating Antrea into NSX 3 lines
kubectl -n kube-system exec antrea-controller-8589557c86-wprxn --stdin --tty -- antctl version
antctlVersion: v1.11.3-79e45ea
controllerVersion: v1.11.3-79e45ea
kubectl
bash Integrating Antrea into NSX 18 lines
# Extract the antrea-networking ZIP file
unzip antrea-interworking-0.11.0.zip
Archive: antrea-interworking-0.11.0.zip
creating: antrea-interworking-0.11.0/
creating: antrea-interworking-0.11.0/bin/
inflating: antrea-interworking-0.11.0/bin/antreansxctl.tar.gz
inflating: antrea-interworking-0.11.0/bootstrap-config.yaml
inflating: antrea-interworking-0.11.0/deregisterjob.yaml
inflating: antrea-interworking-0.11.0/interworking-debian-0.11.0.tar
inflating: antrea-interworking-0.11.0/interworking.yaml
inflating: antrea-interworking-0.11.0/inventorycleanup.yaml
inflating: antrea-interworking-0.11.0/ns-label-webhook.yaml

# Extract the antreansxctl CLI tool from the GZ file
tar -xzf antrea-interworking-0.11.0/bin/antreansxctl.tar.gz

# Move the antreansxctl binary to the local bin store to make it available for runtime execution
sudo mv antreansxctl /usr/local/bin
text Integrating Antrea into NSX 4 lines
projects.registry.vmware.com/antreainterworking/interworking-debian:VERSION
projects.registry.vmware.com/antreainterworking/interworking-ubuntu:VERSION
projects.registry.vmware.com/antreainterworking/interworking-photon:VERSION
projects.registry.vmware.com/antreainterworking/interworking-ubi:VERSION
bash Integrating Antrea into NSX 3 lines
 
# Replace the field after "image: vmware.io/antrea/interworking:0.11.0" with "image: projects.registry.vmware.com/antreainterworking/interworking-photon:0.11.2_vmware.1" in interworking.yaml and deregisterjob.yaml
sed -i 's|image: vmware.io/antrea/interworking:0.11.0|image: projects.registry.vmware.com/antreainterworking/interworking-photon:0.11.2_vmware.1|' antrea-interworking-0.11.0/interworking.yaml antrea-interworking-0.11.0/deregisterjob.yaml
yaml Integrating Antrea into NSX 15 lines
---
apiVersion: v1
kind: Namespace
metadata:
  name: vmware-system-antrea
  labels:
    app: antrea-interworking
    openshift.io/run-level: '0'
    pod-security.kubernetes.io/enforce: privileged
    pod-security.kubernetes.io/enforce-version: latest
    pod-security.kubernetes.io/audit: privileged
    pod-security.kubernetes.io/audit-version: latest
    pod-security.kubernetes.io/warn: privileged
    pod-security.kubernetes.io/warn-version: latest
---
bash Integrating Antrea into NSX 13 lines
antreansxctl bootstrap --cluster-name shared-tkc01 --nsx-managers 10.24.0.50 --user admin --password 'VMware1!VMware1!'
bootstrap.go:51] "bootStrap" User="admin" ClusterName="shared-tkc01"
cluster.go:260] Configure NSX client for manager IP 10.24.0.50
cluster.go:119] Selected endpoint index: 0, ip: 10.24.0.50
bootstrap.go:97] "Checking PrincipalIdentities in NSX" clusterName="shared-tkc01" Result=false
bootstrap.go:113] "Creating self signed cert" clusterName="shared-tkc01"
bootstrap.go:187] "Creating PrincipalIdentities in NSX" clusterName="shared-tkc01" vpc=""
bootstrap.go:205] "vpc argument is empty, creating enterprise admin PI"
bootstrap.go:225] "Creating principal identity" ClusterName="shared-tkc01"
bootstrap.go:233] "Created principal identity" user="shared-tkc01" vpc="" key="shared-tkc01.key" cert="shared-tkc01.crt" PrincipalIdentity={[...]}
bootstrap.go:235] "role: enterprise_admin on /"
bootstrap.go:275] "Creating bootstrap Configmap and Secret yaml file" clusterName="shared-tkc01" nsxManagers=["10.24.0.50"] vpc=""
bootstrap.go:278] "Created bootstrap Configmap and Secret yaml file" bootstrapYamlFile="shared-tkc01-bootstrap-config.yaml"
bash Integrating Antrea into NSX 27 lines
curl -k -u 'admin:VMware1!VMware1!' \
--request GET 'https://10.24.0.50/api/v1/trust-management/principal-identities/' | grep -i '"name" : "shared-tkc01"' -A 22 -B 1
[…]
"results" : [ {
"name" : "shared-tkc01",
"node_id" : "shared-tkc01",
"role" : "enterprise_admin",
"certificate_id" : "0041f40a-4f52-4718-947d-3c57f7f98806",
"roles_for_paths" : [ {
"path" : "/",
"roles" : [ {
"role" : "enterprise_admin"
} ],
"delete_path" : false
} ],
"is_protected" : true,
"resource_type" : "PrincipalIdentity",
"id" : "03b51c9f-8bda-419d-8a26-9740895e82db",
"display_name" : "shared-tkc01@shared-tkc01",
"_create_time" : 1713260925476,
"_create_user" : "admin",
"_last_modified_time" : 1713260925476,
"_last_modified_user" : "admin",
"_system_owned" : false,
"_protection" : "NOT_PROTECTED",
"_revision" : 0
}, {
curl
bash Integrating Antrea into NSX 21 lines
kubectl apply -f shared-tkc01-bootstrap-config.yaml -f antrea-interworking-0.11.0/interworking.yaml
namespace/vmware-system-antrea created
configmap/bootstrap-config created
secret/nsx-cert created
customresourcedefinition.apiextensions.k8s.io/antreaccpadapterinfos.clusterinformation.antrea-interworking.tanzu.vmware.com created
customresourcedefinition.apiextensions.k8s.io/antreampadapterinfos.clusterinformation.antrea-interworking.tanzu.vmware.com created
namespace/vmware-system-antrea configured
configmap/cluster-id created
configmap/antrea-interworking-config created
serviceaccount/register created
role.rbac.authorization.k8s.io/register created
rolebinding.rbac.authorization.k8s.io/register created
role.rbac.authorization.k8s.io/vmware-system-antrea-register created
rolebinding.rbac.authorization.k8s.io/vmware-system-antrea-register created
serviceaccount/interworking created
clusterrole.rbac.authorization.k8s.io/antrea-interworking created
clusterrolebinding.rbac.authorization.k8s.io/antrea-interworking created
clusterrole.rbac.authorization.k8s.io/antrea-interworking-supportbundle created
clusterrolebinding.rbac.authorization.k8s.io/antrea-interworking-supportbundle created
job.batch/register created
deployment.apps/interworking created
kubectl
bash Integrating Antrea into NSX 13 lines
kubectl -n vmware-system-antrea get all
NAME READY STATUS RESTARTS AGE
pod/interworking-579ff578f7-ng48n 4/4 Running 0 45s
pod/register-v5qrg 0/1 Completed 0 46s

NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/interworking 1/1 1 1 46s

NAME DESIRED CURRENT READY AGE
replicaset.apps/interworking-579ff578f7 1 1 1 45s

NAME COMPLETIONS DURATION AGE
job.batch/register 1/1 7s 46s
kubectl
bash Monitor Cronjobs with Aria Operations 1 lines
45 15 * * * /usr/bin/sudo /bin/bash /opt/vmware/impex/bin/export.sh 2>&1 | logger -t export_sh -n syslog.soultec.ch -P 514 -T
kubectl -n vmware-system-ako get all

NAME                                                          READY STATUS           RESTARTS         AGE
pod/vmware-system-ako-ako-controller-manager-65d78d698d-c944k 1/2   CrashLoopBackOff 1465 (4m17s ago) 49d

NAME                                                     READY UP-TO-DATE AVAILABLE AGE
deployment.apps/vmware-system-ako-ako-controller-manager 0/1   1          0         49d

NAME                                                                DESIRED CURRENT READY AGE
replicaset.apps/vmware-system-ako-ako-controller-manager-65d78d698d 1       1       0     49d
kubectl
kubectl -n vmware-system-ako describe pod vmware-system-ako-ako-controller-manager-65d78d698d-c944k
[...]
Events:
Type    Reason  Age                       From    Message
----    ------  ----                      ----    -------
Warning BackOff 3m14s (x33529 over 5d10h) kubelet Back-off restarting failed container manager in pod vmware-system-ako-ako-controller-manager-65d78d698d-c944k_vmware-system-ako(e629cb54-f4fe-409f-8ac4-f2b0ac58b506)
kubectl
kubectl -n vmware-system-ako logs vmware-system-ako-ako-controller-manager-65d78d698d-c944k infra | more

2024-02-02T09:16:01.591Z INFO infra-main/main.go:49 AKO-Infra is running with version: ob-21883866-460f000-7e6ff10
2024-02-02T09:16:01.591Z INFO infra-main/main.go:55 We are running inside kubernetes cluster. Won't use kubeconfig files.
2024-02-02T09:16:01.594Z INFO infra-main/main.go:76 Successfully created kube client for ako-infra
2024-02-02T09:16:01.594Z INFO utils/utils.go:173 Initializing configmap informer in vmware-system-ako
2024-02-02T09:16:01.675Z INFO lib/dynamic_client.go:134 Skipped initializing dynamic informers for cniPlugin
2024-02-02T09:16:01.682Z INFO ingestion/vcf_k8s_controller.go:346 Got data from ConfigMap {"advancedL4":"true","cloudName":"/infra/sites/default/enforcement-points/default/transport-zones/overlay-tz","clusterID":"domain-c[...]","controllerIP":"[...]","credentialsSecretName":"avi-secret","credentialsSecretNamespace":"vmware-system-ako","logLevel":"WARN","serverURL":"https://[...]"}
2024-02-02T09:16:01.682Z INFO ingestion/vcf_k8s_controller.go:427 TransportZone to use for AKO is set to /infra/sites/default/enforcement-points/default/transport-zones/overlay-tz
E0202 09:16:20.192221 1 avisession.go:668] Client error for URI: login. Error: Post "https://[...]/login": dial tcp [...]:443: connect: no route to host
E0202 09:16:20.193030 1 avisession.go:714] CheckControllerStatus is disabled for this session, not going to retry.
E0202 09:16:20.193046 1 avisession.go:716] Failed to invoke API. Error: Post "https://[...]/login": dial tcp [...]:443: connect: no route to host
E0202 09:16:20.193123 1 avisession.go:383] response error: Rest request error, returning to caller: Post " https://[...]/login": dial tcp [...]:443: connect: no route to host
2024-02-02T09:16:20.193Z ERROR ingestion/vcf_k8s_controller.go:381 Failed to connect to AVI controller using secret provided by NCP, the secret would be deleted, err: Rest request error, returning to caller: Post "https://[...]/login": dial tcp [...]:443: connect: no route to host
2024-02-02T09:16:20.201Z INFO ingestion/vcf_k8s_controller.go:210 ConfigMap Add
2024-02-02T09:16:20.204Z INFO ingestion/vcf_k8s_controller.go:346 Got data from ConfigMap {"advancedL4":"true","cloudName":"/infra/sites/default/enforcement-points/default/transport-zones/overlay-tz","clusterID":"domain-c[...]","controllerIP":"[...]","credentialsSecretName":"avi-secret","credentialsSecretNamespace":"vmware-system-ako","logLevel":"WARN","serverURL":"https://[...]"}
2024-02-02T09:16:20.206Z WARN ingestion/vcf_k8s_controller.go:361 Failed to get Secret, got err: secrets "avi-secret" not found
2024-02-02T09:16:20.206Z INFO ingestion/vcf_k8s_controller.go:210 ConfigMap Add
2024-02-02T09:16:20.208Z INFO ingestion/vcf_k8s_controller.go:346 Got data from ConfigMap
[...]
kubectl
kubectl -n vmware-system-nsx get pods

NAME                       READY   STATUS    RESTARTS   AGE
nsx-ncp-5f4f7d6597-7rstp   2/2     Running   0          49d
nsx-ncp-5f4f7d6597-ppl7w   2/2     Running   0          49d

kubectl -n vmware-system-nsx delete pod nsx-ncp-5f4f7d6597-7rstp
kubectl -n vmware-system-nsx delete pod nsx-ncp-5f4f7d6597-ppl7w
kubectl
[ncp GreenThread-125 W] nsx_ujo.ncp.nsx.policy.ako_bootstrap_service Unexpected exception from NSX manager when acquiring AVI auth token: Unexpected error from backend manager (['nsx-mgr-01:443', 'nsx-mgr-01a:443', 'nsx-mgr-01b:443', 'nsx-mgr-01c:443']) for PUT policy/api/v1/infra/alb-auth-token: Error: I/O error on GET request for https://192.168.100.33/api/user: PKIX path building failed: java.security.cert.CertPathBuilderException: Unable to find certificate chain.; nested exception is javax.net.ssl.SSLHandshakeException: PKIX path building failed: java.security.cert.CertPathBuilderException: Unable to find certificate chain.

[ncp GreenThread-125 W] nsx_ujo.ncp.nsx.policy.ako_bootstrap_service get_avi_auth_token failed, cause: Failed to get Avi auth token: Unexpected error from backend manager (['nsx-mgr-01:443', 'nsx-mgr-01a:443', 'nsx-mgr-01b:443', 'nsx-mgr-01c:443']) for PUT policy/api/v1/infra/alb-auth-token: Error: I/O error on GET request for https://192.168.100.33/api/user: PKIX path building failed: java.security.cert.CertPathBuilderException: Unable to find certificate chain.; nested exception is javax.net.ssl.SSLHandshakeException: PKIX path building failed: java.security.cert.CertPathBuilderException: Unable to find certificate chain., args: (), kwargs: {}

[ncp GreenThread-125 I] nsx_ujo.common.controller AviSecretController worker 1 failed to sync Bootstrap due to retryable exception: Failed to get Avi auth token: Unexpected error from backend manager (['nsx-mgr-01:443', 'nsx-mgr-01a:443', 'nsx-mgr-01b:443', 'nsx-mgr-01c:443']) for PUT policy/api/v1/infra/alb-auth-token: Error: I/O error on GET request for https://192.168.100.33/api/user: PKIX path building failed: java.security.cert.CertPathBuilderException: Unable to find certificate chain.; nested exception is javax.net.ssl.SSLHandshakeException: PKIX path building failed: java.security.cert.CertPathBuilderException: Unable to find certificate chain.
keytool -importcert -alias <private-Root-CA> -keystore /usr/java/jre/lib/security/cacerts -storepass changeit -file <path-to-root-ca-cert>
keytool -importcert -alias <private-Intermediate-CA> -keystore /usr/java/jre/lib/security/cacerts -storepass changeit -file <path-to-intermediate-ca-cert>
sudo cp <path-to-root-ca-cert> /usr/local/share/ca-certificates/
sudo cp <path-to-intermediate-ca-cert> /usr/local/share/ca-certificates/
sudo update-ca-certificates
service proton restart
powershell PowerShell Script to test multiple IP Addresses 15 lines
Param(
[Parameter(Mandatory=$true, position=0)][string]$csvfile
)
$ColumnHeader = "IPaddress"
Write-Host "Reading file" $csvfile
$ipaddresses = import-csv $csvfile | select-object $ColumnHeader
Write-Host "Started Pinging.."
foreach ($ip in $ipaddresses) {
    if (test-connection $ip.("IPAddress") -count 1 -quiet) {
        write-host $ip.("IPAddress") "Ping succeeded." -foreground green
    } else {
        write-host $ip.("IPAddress") "Ping failed." -foreground red
    }
}
Write-Host "Pinging Completed."
Write-Host
text Tanzu default storage class 4 lines
kubectl get sc
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE
sp-tanzu-global csi.vsphere.vmware.com Delete Immediate true 9d
sp-tanzu-global-latebinding csi.vsphere.vmware.com Delete WaitForFirstConsumer true 9d
kubectl
bash Tanzu default storage class 1 lines
kubectl patch storageclass sp-tanzu-global -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
kubectl
text Tanzu default storage class 4 lines
kubectl get sc
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE
sp-tanzu-global (default) csi.vsphere.vmware.com Delete Immediate true 9d
sp-tanzu-global-latebinding csi.vsphere.vmware.com Delete WaitForFirstConsumer true 9d
kubectl
text Secure your DMZ with a proxy 46 lines
### Schema includes ###########################################################
include                 /usr/local/openldap/etc/openldap/schema/core.schema
include                 /usr/local/openldap/etc/openldap/schema/cosine.schema
include                 /usr/local/openldap/etc/openldap/schema/inetorgperson.schema
include                 /usr/local/openldap/etc/openldap/schema/misc.schema
include                 /usr/local/openldap/etc/openldap/schema/nis.schema
include                 /usr/local/openldap/etc/openldap/schema/microsoft.minimal.schema

## Module paths ##############################################################
modulepath              /usr/local/openldap/libexec/openldap
moduleload              back_ldap
moduleload              rwm

# Main settings ###############################################################
pidfile                 /usr/local/openldap/var/run/slapd.pid
argsfile                /usr/local/openldap/var/run/slapd.args

### Database definition (Proxy to AD) #########################################
database                ldap
suffix                  "DC=sample,DC=intra"
rootdn                  "cn=ldap,DC=sample,DC=intra"
rootpw                  "BIND-PW-PROXY"
readonly                yes
protocol-version        3
rebind-as-user          yes
uri                     "ldaps://ADC001,ldaps://ADC002"
idassert-bind bindmethod=simple
    binddn="CN=svc-ldap,OU=Service_Accounts,DC=sample,DC=intra"
    credentials="BIND-PW-AD"
    mode=none
    flags=non-prescriptive
    tls_reqcert=never
    tls_cacert=/usr/local/openldap/etc/openldap/CA.cer  # AD Certificate
overlay                 rwm
rwm-map                 attribute       uid     sAMAccountName

### Logging ###################################################################
loglevel                0

### Limits ####################################################################
sizelimit               unlimited

### LDAPS ####################################################################
TLSCACertificateFile /usr/local/openldap/etc/openldap/CA.cer # PKI CA Certificate
TLSCertificateFile /usr/local/openldap/etc/openldap/proxyldap001.cer # LDAP Proxy Certificate
TLSCertificateKeyFile /usr/local/openldap/etc/openldap/proxyldap001.key # LDAP Proxy Key
text Secure your DMZ with a proxy 1 lines
[root@localhost]# ldapsearch -LLL -x -h localhost -b "DC=sample,DC=intra" -D "cn=ldap,DC=sample,DC=intra" -w "BIND-PW-PROXY" "(objectClass=USER)"
text Secure your DMZ with a proxy 5 lines
w32tm /config /manualpeerlist:"0.ch.pool.ntp.org,0x8 1.ch.pool.ntp.org,0x8 2.ch.pool.ntp.org,0x8 3.ch.pool.ntp.org,0x8" /syncfromflags:manual /reliable:yes /update
w32tm /resync /rediscover
w32tm /config /LocalClockDispersion:0 
w32tm /config /update
net stop w32time && net start w32time
text Secure your DMZ with a proxy 40 lines
# These servers were defined in the installation: (Active Directory)
server 192.168.46.100 trust
server 192.168.46.101 trust
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).

# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift

# Allow the system clock to be stepped in the first three updates
# if its offset is larger than 1 second.
makestep 1.0 3

# Enable kernel synchronization of the real-time clock (RTC).
rtcsync

# Enable hardware timestamping on all interfaces that support it.
#hwtimestamp *

# Increase the minimum number of selectable sources required to adjust
# the system clock.
#minsources 2

# Allow NTP client access from local network. (DMZ)
allow 10.10.10.0/24

# Serve time even if not synchronized to a time source.
local stratum 5

# Specify file containing keys for NTP authentication.
keyfile /etc/chrony.keys

# Get TAI-UTC offset and leap seconds from the system tz database.
leapsectz right/UTC

# Specify directory for log files.
logdir /var/log/chrony

# Select which information is logged.
#log measurements statistics tracking
text Secure your DMZ with a proxy 5 lines
[root@localhost]# chronyc sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^* 192.168.46.100                  2   6     1     9    +76us[  +76us] +/-   32ms
^  192.168.46.101                  4   6     1     9   +206us[ +206us] +/-   29ms
text Secure your DMZ with a proxy 31 lines
options {
        listen-on port 53 { 127.0.0.1; 10.10.10.200; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { localhost; 10.10.10.0/24; };

        forwarders {
            192.168.46.100;
            192.168.46.101;
        };

        recursion yes;

        dnssec-enable no;
        dnssec-validation no;

        auth-nxdomain no;
        managed-keys-directory "/var/named/dynamic";

        pid-file "/run/named/named.pid";
        session-keyfile "/run/named/session.key";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};
text Secure your DMZ with a proxy 7 lines
[root@localhost]# nslookup ADC001
Server:         127.0.0.1
Address:        127.0.0.1#53

Non-authoritative answer:
Name:   ADC001.sample.intra
Address: 192.168.46.100
text Secure your DMZ with a proxy 5 lines
firewall-cmd --add-service=dns --permanent 
firewall-cmd --add-service=ntp --permanent 
firewall-cmd --add-port=123/udp --permanent 
firewall-cmd --add-port=636/tcp --permanent 
firewall-cmd --reload

// Forward Zone
zone "virtual.lab" {
 type master;
 file "/etc/bind/zones/virtual.lab.db";
};
// Reverse Zone
zone "108.16.172.in-addr.arpa" {
 type master;
 file "/etc/bind/zones/rev.108.16.172.in-addr.arpa";
};

$TTL	86400 ; 24 hours / 1d
; $TTL used for all RRs without explicit TTL value
$ORIGIN virtual.lab.
@  1D  IN  SOA dnsserver.virtual.lab. hostmaster.virtual.lab. (
			      2002022401 ; serial
			      3H ; refresh
			      15 ; retry
			      1w ; expire
			      3h ; minimum
			     )
virtual.lab.      IN      NS              dnsserver.virtual.lab.
       

dnsserver    IN  A      172.16.108.53      
vcsa    IN  A      172.16.108.2
esxhost1  IN  A      172.16.108.3  
esxhost2  IN  A      172.16.108.4
       
@ IN SOA virtual.lab. admin.virtual.lab. ( 
                        2006081401; 
                        28800;  
                        604800; 
                        604800; 
                        86400  
) 
 
           IN    NS     dnsserver.virtual.lab. 
53         IN    PTR    virtual.lab 
2	   IN	 PTR	vcsa 
3	   IN	 PTR	esxhost1 
4	   IN	 PTR	esxhost2
powershell Assigning Tags based on VM Notes 29 lines
#just to be thourough here is the code to actually create the Tag-Category
New-TagCategory -Name "Install Date" -Cardinality "Single" -EntityType "VirtualMachine" -Confirm:$false
foreach ($currentVm in get-vm) {
    #here we extract the value from our custom attribute
    $installDate = $currentVm.CustomFields | Where-Object {$_.Key -match "Install"} | Select-Object -ExpandProperty Value
    if ($installDate -eq "")
{
        #if the VM did not have the custom value defined we go ahead and give a value
        $installDate = "01.01.1900"
        #and we add the custome attribute as well
        $currentVm | Set-Annotation -CustomAttribute "Install Date" -Value $installDate -WhatIf
    }
    try
{
        #if the tag is not found we execute the "catch"
        get-tag -Name $installDate -ErrorAction Stop
    }
    catch
{
        #create the tag if it does not exist
        New-Tag -Name $installDate -Category "Install Date" -WhatIf -Confirm:$false
    }
    finally
{
        #at this point we know the tag exists so we assign it to the current VM from the loop
        New-TagAssignment -Tag (Get-Tag -Name $installDate) -Entity $currentVm -WhatIf
    }

}
Get-TagNew-TagNew-TagAssignmentNew-TagCategorySelect-ObjectSet-AnnotationWhere-Object
powershell Automating VPG journal limit changes 115 lines

param(
[Parameter(Mandatory = $true)][string]$zvm = "zvm.virtualfrog.wordpress.com",
[Parameter(Mandatory = $true)][string]$vpgName = "Test",
[Parameter(Mandatory = $true)][Int32]$LimitValueInGB = 300,
[Parameter(Mandatory = $true)][Int32]$ThresholdValueInGB = 250
)

#----------------------------------------------------------[Declarations]----------------------------------------------------------

# Build Base URL -> for all RestMethods
$baseURL = "https://" + $zvm + ":443/v1/"

# New Limit Value in MB
$LimitValueInMB = $LimitValueInGB * 1024

# New Warning Threshold in MB
$ThresholdValueInMB = $ThresholdValueInGB * 1024

# Responsetype
$TypeJSON = "application/json"

#-----------------------------------------------------------[Functions]------------------------------------------------------------

Function Get-ZertoSession ($ZertoUser, $ZertoPassword) {
# Authenticating with Zerto APIs
$xZertoSessionURL = $baseURL + "session/add"
$authInfo = ("{0}:{1}" -f $ZertoUser, $ZertoPassword)
$authInfo = [System.Text.Encoding]::UTF8.GetBytes($authInfo)
$authInfo = [System.Convert]::ToBase64String($authInfo)
$headers = @{Authorization = ("Basic {0}" -f $authInfo)}
$sessionBody = '{"AuthenticationMethod": "1"}'

# Get Zerto Session Response
$xZertoSessionResponse = Invoke-WebRequest -Uri $xZertoSessionURL -Headers $headers -Method POST -Body $sessionBody -ContentType $TypeJSON

# Extracting x-zerto-session from the response
$xZertoSession = $xZertoSessionResponse.headers.get_item("x-zerto-session")

# Return Zerto Session Header
return @{"Accept" = "application/json"; "x-zerto-session" = $xZertoSession}
}

#-----------------------------------------------------------[Execution]------------------------------------------------------------

# Get Zerto Session
$zertoSessionHeader = Get-ZertoSession -ZertoUser "virtualFrog" -ZertoPassword "Password"

# Get VPG
$vpgListUrl = $baseURL + "vpgs"
$vpg = Invoke-RestMethod -Uri $vpgListUrl -Headers $zertoSessionHeader -ContentType $TypeJSON

#Filter the one from the paramater
$vpgToEdit = $vpg |Where-Object {$_.VpgName -eq "$vpgName"}
Write-Host "Changing Journal Limit and Threshold Settings of: "($vpgToEdit.VpgName)

#Get the identifier of this VPG
$VPGidentifier = $vpgToEdit.VpgIdentifier
$VPGidentifierJSON = '{"VpgIdentifier":"' + $VPGidentifier + '"}'
#$VPGidentifier

# Get VPG Settings Identifier
$VPGSettingsIDURL = $baseURL + "vpgSettings"
$VPGSettingsIdentifier = Invoke-RestMethod -Method Post -Uri $VPGSettingsIDURL -Body $VPGidentifierJSON -ContentType $TypeJSON -Headers $zertoSessionHeader

# Set VPG Settings URL
$VPGSettingsURL = $baseURL + "vpgSettings/" + $VPGSettingsIdentifier
$VPGSettingsBasicURL = $VPGSettingsURL + "/basic"
$VPGSettingsJournalURL = $VPGSettingsURL + "/journal"
$VPGSettingsCommitURL = $VPGSettingsURL + "/commit"
$VPGSettingsVMsJournalURL = $VPGSettingsURL + "/vms"

# Get the actual VPG Settings
$VPGSettings = Invoke-RestMethod -Uri $VPGSettingsURL -Headers $zertoSessionHeader -ContentType $TypeJSON

$HardLimitGB = $VPGSettings.Journal.Limitation.HardLimitInMB / 1024
$WarningThresholdGB = $VPGSettings.Journal.Limitation.WarningThresholdInMB / 1024
#Write-Host "Hard Limit of this VPG in GB: " $HardLimitGB
#Write-Host "Warning Threshold of this VPG in GB: " $WarningThresholdGB

#Change Setting of VPG
$VPGSettings.Journal.Limitation.HardLimitInMB = $LimitValueInMB
$VPGSettings.Journal.Limitation.WarningThresholdInMB = $ThresholdValueInMB

$data = @{Limitation = @{
HardLimitInMB = $LimitValueInMB
WarningThresholdInMB = $ThresholdValueInMB
}
}
$json = $data | ConvertTo-Json

$vmdata = @{Journal = @{
Limitation = @{
HardLimitInMB = $LimitValueInMB
WarningThresholdInMB = $ThresholdValueInMB
}
}
}
$vmjson = $vmdata |ConvertTo-Json
#Write Change to Zerto
$ChangedVPG = Invoke-RestMethod -Uri $VPGSettingsJournalURL -Method Put -Body $json -Headers $zertoSessionHeader -ContentType $TypeJSON

foreach ($vm in $VPGSettings.VMs) {
$vmIdentifier = $vm.VmIdentifier
$VPGSettingsVMsJournalURL = $VPGSettingsURL + "/vms/" + $vmIdentifier
$VMHardLimitGB = $vm.Journal.Limitation.HardLimitInMB / 1024
$VMWarningThreshold = $vm.Journal.Limitation.WarningThresholdInMB / 1024

#Write-Host "VM ("$vm.VmIdentifier") has Limit of "$VMHardLimitGB " GB and Warning of " $VMWarningThreshold "GB"
$ChangedVPG = Invoke-RestMethod -Uri $VPGSettingsVMsJournalURL -Method Put -Body $vmjson -Headers $zertoSessionHeader -ContentType $TypeJSON

}

$VPGCommit = Invoke-RestMethod -Method Post -Uri $VPGSettingsCommitURL -ContentType $TypeJSON -Headers $zertoSessionHeader
Write-Host -ForegroundColor Green "Changed the valued successfully!"
ConvertTo-JsonGet-ZertoSessionInvoke-RestMethodInvoke-WebRequestWhere-ObjectWrite-Host
powershell Change Admission Control Percentages 275 lines

#---------------------------------------------------------[Script Parameters]------------------------------------------------------

Param (
    #Script parameters go here
    [Parameter(Mandatory = $true)][string]$vCenter,
    [Parameter(Mandatory = $true)][string]$cluster,
    [Parameter(Mandatory = $true)][string]$failuresToTolerate
)

#---------------------------------------------------------[Initialisations]--------------------------------------------------------

#Set Error Action to Silently Continue
$ErrorActionPreference = 'SilentlyContinue'

#Import Modules & Snap-ins
Import-Module PSLogging

#----------------------------------------------------------[Declarations]----------------------------------------------------------

#Script Version
$sScriptVersion = '1.0'

#Log File Info
$sLogPath = 'C:\Temp'
$sLogName = 'HA_AdmissionControlLog.log'
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName

#-----------------------------------------------------------[Functions]------------------------------------------------------------

Function Connect-VMwareServer {
    Param ([Parameter(Mandatory = $true)][string]$VMServer)

    Begin {
        Write-LogInfo -LogPath $sLogFile -Message "Connecting to vCenter Server [$VMServer]..."
    }

    Process {
        Try {
            $oCred = Get-Credential -Message 'Enter credentials to connect to vCenter Server'
            Connect-VIServer -Server $VMServer -Credential $oCred -ErrorAction Stop
        }

        Catch {
            Write-LogError -LogPath $sLogFile -Message $_.Exception -ExitGracefully
            Break
        }
    }

    End {
        If ($?) {
            Write-LogInfo -LogPath $sLogFile -Message 'Completed Successfully.'
            Write-LogInfo -LogPath $sLogFile -Message ' '
        }
    }
}

Function checkRAMCompliance {
    Param ([Parameter(Mandatory = $true)][string]$clusterName)
    Begin {
        Write-LogInfo -LogPath $sLogFile -Message "Checking if all hosts in cluster [$clusterName] have the same amount of RAM..."
        $myHostsRAM = @()
    }
    Process {
        Try {
            $clusterObject = Get-Cluster -Name $clusterName -ErrorAction Stop
            $hostObjects = $clusterObject | Get-VMHost -ErrorAction Stop

            foreach ($hostObject in $hostObjects) {

                $HostInfoMEM = "" | Select-Object MEM

                $HostInfoMEM.MEM = $hostObject.MemoryTotalGB

                $myHostsRAM += $HostInfoMEM
            }
            #Check if all values are correct: return true, otherwise return false
            if (@($myHostsRAM | Select-Object -Unique).Count -eq 1) {
                #CPU are the same
                Write-LogInfo -LogPath $sLogFile -Message "RAM in the cluster is the same"
                return $true
            }
            else {
                Write-LogInfo -LogPath $sLogFile -Message "RAM in the cluster is NOT the same"
                return $false
            }

        }
        Catch {
            Write-LogError -LogPath $sLogFile -Message $_.Exception -ExitGracefully
            Break
        }
    }
    End {
        If ($?) {
            Write-LogInfo -LogPath $sLogFile -Message 'Completed Successfully.'
            Write-LogInfo -LogPath $sLogFile -Message ' '
        }
    }
}

Function checkCPUCompliance {
    Param ([Parameter(Mandatory = $true)][string]$clusterName)
    Begin {
        Write-LogInfo -LogPath $sLogFile -Message "Checking if all hosts in cluster [$clusterName] have the same CPU..."
        $myHostsCPU = @()
    }
    Process {
        Try {
            $clusterObject = Get-Cluster -Name $clusterName -ErrorAction Stop
            $hostObjects = $clusterObject | Get-VMHost -ErrorAction Stop

            foreach ($hostObject in $hostObjects) {
                $HostInfoCPU = "" | Select-Object CPU

                $HostInfoCPU.CPU = $hostObject.CpuTotalMhz

                $myHostsCPU += $HostInfoCPU
            }
            #Check if all values are correct: return true, otherwise return false

            if (@($myHostsCPU | Select-Object -Unique).Count -eq 1) {
                Write-LogInfo -LogPath $sLogFile -Message "CPU in the cluster is the same"
                return $true
            }
            else {
                Write-LogInfo -LogPath $sLogFile -Message "CPU in the cluster is NOT the same"
                return $false
            }

        }
        Catch {
            Write-LogError -LogPath $sLogFile -Message $_.Exception -ExitGracefully
            Break
        }
    }
    End {
        If ($?) {
            Write-LogInfo -LogPath $sLogFile -Message 'Completed Successfully.'
            Write-LogInfo -LogPath $sLogFile -Message ' '
        }
    }
}

Function getBiggestCPUInCluster {
    Param ([Parameter(Mandatory=$true)][string]$clusterName)
    Begin {
      Write-LogInfo -LogPath $sLogFile -Message "Trying to get the biggest CPU resource in cluster [$clusterName]..."
    }
    Process {
      Try {
        $clusterObject = Get-Cluster $clusterName -ErrorAction Stop
        $hostObjects = $clusterObject | Get-VMHost -ErrorAction Stop
        $cpuResources =  @()
        foreach ($hostObject in $hostObjects) {
            $cpuInfo = "" | Select-Object CPU
            $cpuInfo.CPU = $hostObject.CpuTotalMhz

            $cpuResources += $cpuInfo
        }
        return ($cpuResources | Measure-Object -Maximum)

      }
      Catch {
        Write-LogError -LogPath $sLogFile -Message $_.Exception -ExitGracefully
        Break
      }
    }
    End {
      If ($?) {
        Write-LogInfo -LogPath $sLogFile -Message 'Completed Successfully.'
        Write-LogInfo -LogPath $sLogFile -Message ' '
      }
    }
  }

  Function getBiggestRAMInCluster {
    Param ([Parameter(Mandatory=$true)][string]$clusterName)
    Begin {
      Write-LogInfo -LogPath $sLogFile -Message "Trying to get the biggest RAM resource in cluster [$clusterName]..."
    }
    Process {
      Try {
        $clusterObject = Get-Cluster $clusterName -ErrorAction Stop
        $hostObjects = $clusterObject | Get-VMHost -ErrorAction Stop
        $ramResources =  @()
        foreach ($hostObject in $hostObjects) {
            $ramInfo = "" | Select-Object RAM
            $ramInfo.RAM = $hostObject.MemoryTotalGB

            $ramResources += $ramInfo
        }
        return ($ramResources | Measure-Object -Maximum)

      }
      Catch {
        Write-LogError -LogPath $sLogFile -Message $_.Exception -ExitGracefully
        Break
      }
    }
    End {
      If ($?) {
        Write-LogInfo -LogPath $sLogFile -Message 'Completed Successfully.'
        Write-LogInfo -LogPath $sLogFile -Message ' '
      }
    }
  }

Function SetAdmissionControl {
    Param ([Parameter(Mandatory = $true)][string]$clusterName)
    Begin {
        Write-LogInfo -LogPath $sLogFile -Message "Setting the admission policy on cluster [$clusterName].."
    }
    Process {
        Try {
            $RAMCompliance = checkRAMCompliance $clusterName
            $CPUCompliance = checkCPUCompliance $clusterName
            $totalAmountofHostsInCluster = (Get-Cluster -Name $clusterName -ErrorAction Stop | Get-VMHost -ErrorAction Stop).Count
            if (($RAMCompliance -eq $true) -and ($CPUCompliance -eq $true)) {
                #Same hardware. calculation very simple
                [int]$ramPercentageToReserve = [math]::Round((100 / ($totalAmountofHostsInCluster) * ($failuresToTolerate)), 0)
                [int]$cpuPercentageToReserve = [math]::Round((100 / ($totalAmountofHostsInCluster) * ($failuresToTolerate)), 0)

            }
            if ($CPUCompliance -eq $false) {
                #calculate with different CPU resources but same RAM resources
                #get biggest CPU amount, total amount and number of hosts in cluster
                $biggestCPUValue = getBiggestCPUInCluster $clusterName
                $totalCPUMhz = (Get-Cluster $clusterName).ExtensionData.Summary.TotalCPU

                [int]$cpuPercentageToReserve = [math]::Round(((($biggestCPUValue) * 100) / ($totalCPUMhz)*($failuresToTolerate)),0)
            }
            if ($RAMCompliance -eq $false) {
                #in this case RAM is the decisive factor
                #get biggest RAM amount, total amount and number of hosts in cluster
                $biggestMemoryValue = getBiggestRAMInCluster $clusterName
                $totalMemoryGB = [math]::Round(((Get-Cluster $clusterName).ExtensionData.Summary.TotalMemory /1024 /1024 /1024),0)

                [int]$ramPercentageToReserve = [math]::Round(((($biggestMemoryValue) * 100) / ($totalMemoryGB)*($failuresToTolerate)),0)
            }

            Write-LogInfo -LogPath $sLogFile -Message "CPU Value calculated: [$cpuPercentageToReserve].."
            Write-LogInfo -LogPath $sLogFile -Message "RAM Value calculated: [$ramPercentageToReserve].."

            $spec = New-Object VMware.Vim.ClusterConfigSpecEx
            $spec.dasConfig = New-Object VMware.Vim.ClusterDasConfigInfo
            $spec.dasConfig.AdmissionControlPolicy = New-Object VMware.Vim.ClusterFailoverResourcesAdmissionControlPolicy
            $spec.dasConfig.AdmissionControlEnabled = $true
            $spec.dasConfig.AdmissionControlPolicy.cpuFailoverResourcesPercent = $cpuPercentageToReserve
            $spec.dasConfig.AdmissionControlPolicy.memoryFailoverResourcesPercent = $ramPercentageToReserve

            $clusterObject = Get-Cluster $clusterName
            $clusterView =  Get-View $clusterObject
            $clusterView.ReconfigureComputeResource_Task($spec, $true)

        }
        Catch {
            Write-LogError -LogPath $sLogFile -Message $_.Exception -ExitGracefully
            Break
        }
    }
    End {
        If ($?) {
            Write-LogInfo -LogPath $sLogFile -Message 'Completed Successfully.'
            Write-LogInfo -LogPath $sLogFile -Message ' '
        }
    }
}

#-----------------------------------------------------------[Execution]------------------------------------------------------------

Start-Log -LogPath $sLogPath -LogName $sLogName -ScriptVersion $sScriptVersion
Connect-VMwareServer -VMServer $vCenter
SetAdmissionControl -clusterName $cluster
Stop-Log -LogPath $sLogFile
Connect-VIServerConnect-VMwareServerGet-ClusterGet-CredentialGet-VMHostGet-ViewImport-ModuleJoin-PathMeasure-ObjectNew-ObjectSelect-ObjectStart-LogStop-LogWrite-LogErrorWrite-LogInfo
powershell Getting the Usage of a cluster 26 lines
$clusters = get-cluster
$myClusters = @()
foreach ($cluster in $clusters) {
    $hosts = $cluster |get-vmhost

    [double]$cpuAverage = 0
    [double]$memAverage = 0

    Write-Host $cluster
    foreach ($esx in $hosts) {
        Write-Host $esx
        [double]$esxiCPUavg = [double]($esx | Select-Object @{N = 'cpuAvg'; E = {[double]([math]::Round(($_.CpuUsageMhz) / ($_.CpuTotalMhz) * 100, 2))}} |Select-Object -ExpandProperty cpuAvg)
        $cpuAverage = $cpuAverage + $esxiCPUavg

        [double]$esxiMEMavg = [double]($esx | Select-Object @{N = 'memAvg'; E = {[double]([math]::Round(($_.MemoryUsageMB) / ($_.MemoryTotalMB) * 100, 2))}} |select-object -ExpandProperty memAvg)
        $memAverage = $memAverage + $esxiMEMavg
    }
    $cpuAverage = [math]::Round(($cpuAverage / ($hosts.count) ), 1)
    $memAverage = [math]::Round(($memAverage / ($hosts.count) ), 1)
    $ClusterInfo = "" | Select-Object Name, CPUAvg, MEMAvg
    $ClusterInfo.Name = $cluster.Name
    $ClusterInfo.CPUAvg = $cpuAverage
    $ClusterInfo.MEMAvg = $memAverage
    $myClusters += $ClusterInfo
}
$myClusters
Select-ObjectWrite-Host
powershell Reporting the duration of snapshots 165 lines
# import vmware related modules, get the credentials and connect to the vCenter server
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
#$creds = Get-VICredentialStoreItem -file  "D:\Scripts\CreateSnapshotCreationOverview\login.creds"
#Connect-VIServer -Server $creds.Host -User $creds.User -Password $creds.Password
connect-viserver vCenter.virtualfrog.lab

function Get-TaskPlus {
<#
.EXAMPLE
  PS> Get-TaskPlus -Start (Get-Date).AddDays(-1)
.EXAMPLE
  PS> Get-TaskPlus -Alarm $alarm -Details
#>

  param(
    [CmdletBinding()]
    [VMware.VimAutomation.ViCore.Impl.V1.Alarm.AlarmDefinitionImpl]$Alarm,
    [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl]$Entity,
    [switch]$Recurse = $false,
    [VMware.Vim.TaskInfoState[]]$State,
    [DateTime]$Start,
    [DateTime]$Finish,
    [string]$UserName,
    [int]$MaxSamples = 100,
    [switch]$Reverse = $true,
    [VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$Server = $global:DefaultVIServer,
    [switch]$Realtime,
    [switch]$Details,
    [switch]$Keys,
    [int]$WindowSize = 100
  )

  begin {
    function Get-TaskDetails {
      param(
        [VMware.Vim.TaskInfo[]]$Tasks
      )
      begin{
        $psV3 = $PSversionTable.PSVersion.Major -ge 3
      }

      process{
        $tasks | %{
          if($psV3){
            $object = [ordered]@{}
          }
          else {
            $object = @{}
          }
          $object.Add("Name",$_.Name)
          $object.Add("Description",$_.Description.Message)
          if($Details){$object.Add("DescriptionId",$_.DescriptionId)}
          if($Details){$object.Add("Task Created",$_.QueueTime.tolocaltime())}
          $object.Add("Task Started",$_.StartTime.tolocaltime())
          if($Details){$object.Add("Task Ended",$_.CompleteTime.tolocaltime())}
          $object.Add("State",$_.State)
          $object.Add("Result",$_.Result)
          $object.Add("Entity",$_.EntityName)
          $object.Add("VIServer",$VIObject.Name)
          $object.Add("Error",$_.Error.ocalizedMessage)
          if($Details){
            $object.Add("Cancelled",(&{if($_.Cancelled){"Y"}else{"N"}}))
            $object.Add("Reason",$_.Reason.GetType().Name.Replace("TaskReason", ""))
            $object.Add("AlarmName",$_.Reason.AlarmName)
            $object.Add("AlarmEntity",$_.Reason.EntityName)
            $object.Add("ScheduleName",$_.Reason.Name)
            $object.Add("User",$_.Reason.UserName)
          }
          if($keys){
            $object.Add("Key",$_.Key)
            $object.Add("ParentKey",$_.ParentTaskKey)
            $object.Add("RootKey",$_.RootTaskKey)
          }

          New-Object PSObject -Property $object
        }
      }
    }

    $filter = New-Object VMware.Vim.TaskFilterSpec
    if($Alarm){
      $filter.Alarm = $Alarm.ExtensionData.MoRef
    }
    if($Entity){
      $filter.Entity = New-Object VMware.Vim.TaskFilterSpecByEntity
      $filter.Entity.entity = $Entity.ExtensionData.MoRef
      if($Recurse){
        $filter.Entity.Recursion = [VMware.Vim.TaskFilterSpecRecursionOption]::all
      }
      else{
        $filter.Entity.Recursion = [VMware.Vim.TaskFilterSpecRecursionOption]::self
      }
    }
    if($State){
      $filter.State = $State
    }
    if($Start -or $Finish){
      $filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime
      $filter.Time.beginTime = $Start
      $filter.Time.endTime = $Finish
      $filter.Time.timeType = [vmware.vim.taskfilterspectimeoption]::startedTime
    }
    if($UserName){
      $userNameFilterSpec = New-Object VMware.Vim.TaskFilterSpecByUserName
      $userNameFilterSpec.UserList = $UserName
      $filter.UserName = $userNameFilterSpec
    }
    $nrTasks = 0
  }

  process {
    foreach($viObject in $Server){
      $si = Get-View ServiceInstance -Server $viObject
      $tskMgr = Get-View $si.Content.TaskManager -Server $viObject 

      if($Realtime -and $tskMgr.recentTask){
        $tasks = Get-View $tskMgr.recentTask
        $selectNr = [Math]::Min($tasks.Count,$MaxSamples-$nrTasks)
        Get-TaskDetails -Tasks[0..($selectNr-1)]
        $nrTasks += $selectNr
      }

      try {
      $tCollector = Get-View ($tskMgr.CreateCollectorForTasks($filter))

      if($Reverse){
        $tCollector.ResetCollector()
        $taskReadOp = $tCollector.ReadPreviousTasks
      }
      else{
        $taskReadOp = $tCollector.ReadNextTasks
      }
      do{
        $tasks = $taskReadOp.Invoke($WindowSize)
        if(!$tasks){return}
        $selectNr = [Math]::Min($tasks.Count,$MaxSamples-$nrTasks)
        Get-TaskDetails -Tasks $tasks[0..($selectNr-1)]
        $nrTasks += $selectNr
      }while($nrTasks -lt $MaxSamples)
      }
      catch {
        Write-Host "A error occured in the collector"
      }
    }
    try {
        $tCollector.DestroyCollector()
        }
    catch {
        Write-Host "The error not letting us destroy the collector"
    }
  }
}
$start = (Get-Date).AddDays(-30)
$finish = (Get-Date)
$output = Get-TaskPlus -Details -MaxSamples 20000000 -Start $start -Finish $finish |
? {$_.Name -match "CreateSnapshot_Task" -or $_.Name -match "RemoveSnapshot_Task"} |
select Entity, "Task Created", "Task Started", "Task Ended", User, State, Name,
@{Name="Duration in Seconds"; Expression = {(New-TimeSpan -start $_."Task Started" -End $_."Task Ended").TotalSeconds}}
# create a CSV file with all snapshot related results
$output | Export-Csv -Path "c:\temp\snapshot_create_and_remove_times_last_month.csv" -NoTypeInformation

# cleanup and removal of loaded VMware modules
#Disconnect-VIServer -Server $creds.Host -Confirm:$false
disconnect-viserver vCenter.virtualfrog.lab -confirm:$false
Remove-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
Connect-VIServerDisconnect-VIServerExport-CsvGet-DateGet-TaskDetailsGet-TaskPlusGet-VICredentialStoreItemGet-ViewImport-ModuleNew-ObjectNew-TimeSpanOut-NullRemove-ModuleWrite-Host
<#
.EXAMPLE
    C:\foo> .\Get-AdvancedSettingsNotDefault.ps1 -hostName esx01.virtualfrog.lab -delta:$true

	Description
	-----------
	Gets All settings that are not at default value from given host
.EXAMPLE
    C:\foo> .\Get-AdvancedSettingsNotDefault.ps1 -delta:$true

    Description
    -----------
    Gets All settings from all hosts that are not at default value
.EXAMPLE
    C:\foo> .\Get-AdvancedSettingsNotDefault.ps1 -delta:$false

    Description
    -----------
    Gets All settings from all hosts
#> 

param (
	[Parameter(Mandatory=$False)]
	[string]$hostName="none",
    [Parameter(Mandatory=$False)]
    [boolean]$delta=$false
)

$excludedSettings = "/Migrate/Vmknic|/UserVars/ProductLockerLocation|/UserVars/SuppressShellWarning"
$AdvancedSettings = @()
$AdvancedSettingsFiltered = @()

# Checking if host exists
if ($hostName -ne "none") {
   try {
        $vmhost = Get-VMHost $hostName -ErrorAction Stop
    } catch {
        Write-Host -ForegroundColor Red "There is no host available with name" $hostName
        exit
    } 

    # Retrieving advanced settings
    $esxcli = $vmhost | get-esxcli -V2
    $AdvancedSettings = $esxcli.system.settings.advanced.list.Invoke(@{delta = $delta}) |select @{Name="Hostname"; Expression = {$vmhost}},Path,DefaultIntValue,IntValue,DefaultStringValue,StringValue,Description

    # Displaying results
    #$AdvancedSettings

} else {
    $vmhosts = get-vmhost
    foreach ($vmhost in $vmhosts) {
        $esxcli = $vmhost | get-esxcli -V2
        $AdvancedSettings += $esxcli.system.settings.advanced.list.Invoke(@{delta = $delta}) |select @{Name="Hostname"; Expression = {$vmhost}},Path,DefaultIntValue,IntValue,DefaultStringValue,StringValue,Description
    }
    #$AdvancedSettings
}

# Browsing advanced settings and check for mismatch
ForEach ($advancedSetting in $AdvancedSettings.GetEnumerator()) {
    if ( ($AdvancedSetting.Path -notmatch $excludedSettings) -And (($AdvancedSetting.IntValue -ne $AdvancedSetting.DefaultIntValue) -Or ($AdvancedSetting.StringValue -notmatch $AdvancedSetting.DefaultStringValue) ) ){
        $line = "" | Select Hostname,Path,DefaultIntValue,IntValue,DefaultStringValue,StringValue,Description
        $line.Hostname = $advancedSetting.Hostname
        $line.Path = $advancedSetting.Path
        $line.DefaultIntValue = $advancedSetting.DefaultIntValue
        $line.IntValue = $advancedSetting.IntValue
        $line.DefaultStringValue = $advancedSetting.DefaultStringValue
        $line.StringValue = $advancedSetting.StringValue
        $line.Description = $advancedSetting.Description
        $AdvancedSettingsFiltered += $line
    }
}
$AdvancedSettingsFiltered
Get-AdvancedSettingsNotDefaultGet-VMHostWrite-Hostesxcli
powershell Adding a disk to a VM 178 lines
<#
.EXAMPLE
PS> Add-DiskToVm.ps1 -vMName reg-belairi81 -vCenter virtualfrogvc.virtual.frog -diskGB 10

This will attach a 10 GB disk to the VM on the last of its scsi controllers
.EXAMPLE
PS> Add-DiskToVm.ps1 -vCenter virtualfrogvc.virtual.frog -vMName reg-belairi81 -diskGB 10 -addController:$true -controllerType paravirtual

This will attach a 10 GB disk to the VM and attach it to a new scsi controller of type paravirtual
.EXAMPLE
PS> Add-DiskToVm.ps1 -vCenter virtualfrogvc.virtual.frog -vMName reg-belairi81 -diskGB 10 -controllerNumber 2

This will attach a 10 GB disk to the VM and attach it to the second controller on the VM
#>

##################################################################################
# Script: Add-DiskToVm.ps1
# Datum: 04.10.2017
# Author: Bechtle Steffen Schweiz AG (c) 2017
# Version: 1.0
# History: Check VMs current set of SCSI Controllers when adding Disks
##################################################################################

[CmdletBinding(SupportsShouldProcess=$true)]
Param(
[parameter()]
[string]$vCenter = "virtualfrogvc.virtual.frog",
# Change to default VM for testing
[string]$vMName = "reg-belairi82",
# Change default Disk Size
[decimal]$diskGB = 2.5,
# Hardcode the SCSI Controller # (like 3 for the third controller)
[int]$controllerNumber = 2000,
# Add new SCSI Controller while you're at it
[boolean]$addController = $false,
# Type of SCSI Controller to add (paravirtual|VirtualLsiLogicSAS)
[string]$controllerType = "paravirtual"

)
function get-scsiCount ($vm)
{
try {
return ($vm | get-scsicontroller -ErrorAction Stop).count
}
catch {
Write-Host "Could not count Scsi Controller of $vm"
exit
}
}

function get-scsiID ($vm, $number)
{
try {
return ($vm |get-scsicontroller |select -skip ($number-1) -first 1).ID
}
catch {
Write-Host "Could not get scsi controller number $number from $vm"
exit
}
}

function get-scsiType ($vm, $id)
{
try {
return ($vm |get-scsicontroller -ID $id -ErrorAction Stop).Type
}
catch {
Write-Host "Could not determine type of SCSI Controller on vm ($vm)"
exit
}
}

function add-DiskToVmOnController ($vm, $controller)
{
try {
New-Harddisk -Controller $controller -CapacityGB $diskGB -VM $vm -Whatif -ErrorAction Stop
} catch {
Write-Host "Could not add disk to VM ($vm)"
exit
}
}

function shutDownVm ($vm)
{
try {
Stop-VMGuest -VM $vm -confirm:$false -ErrorAction Stop
Write-Host "Successfully send the shutdown command over VMware Tools"
}
catch {
Write-Host -Foregroundcolor:red "The VM did not respond to a VMware tools shutdown command"
$switch = Read-Host -Prompt "Would you like to Power off the VM $vm ? (yes/no)"
if ($switch -match "yes") {
Stop-VM -VM $vm -confirm:$false
} else {
Write-Host "You chose not to power off the VM. Stopping the script.."
exit
}
}

while ((get-vm $vMName).PowerState -notmatch "PoweredOff")
{
Write-Host "Waiting for $vm to shut down..."
sleep -s 5
}
$vmHasShutDown = $true
}

####### Main Program ######
try {
Import-Module -Name VMware.VimAutomation.Core -ErrorAction Stop | Out-Null
} catch {
Write-Host "Could not add VMware PowerCLI Modules"
exit
}

try {
Connect-VIServer $vCenter -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
}
catch {
Write-Host "Could not connect to vCenter $vCenter"
exit
}

Write-Host "Connected to $vCenter. Starting script"

try {
$vm = Get-VM $vMName -ErrorAction Stop
} catch {
Write-Host "Could not find VM with Name $vMName in vCenter $vCenter"
exit
}
if ($addController) {
if ($vm.PowerState -match "PoweredOn") {
Write-Host -Foregroundcolor:red "The VM is still powered On."
$switch = Read-Host -Prompt "Would you like to shut down the VM ($vm)? (yes/no)"
if ($switch -match "yes") {
shutDownVm $vm

} else {
Write-Host "You chose not to shutdown the VM ($vm). Stopping the script now"
exit
}
}
try {
$vm |New-Harddisk -CapacityGB $diskGB |new-scsicontroller -type $controllerType -ErrorAction Stop
if ($vmHasShutDown) {
$switch = Read-Host -Prompt "The VM was shut down for this operation. Power it back on? (yes/no)"
if ($switch -match "yes") {
Start-VM $vm -confirm:$false
}
}
} catch {
Write-Host "could not add scsi controller with new disk to $vm"
exit
}
} elseif ($controllerNumber -ne 2000) {
$numberOfControllers = get-scsiCount $vm
if ($numberOfControllers -gt $controllerNumber) {
Write-Host "You specified controller number $controllerNumber but the VM ($vm) only has $numberOfControllers controllers"
exit
} else {
$scsiID = get-scsiID $vm $controllerNumber
Write-Host "The VM ($vm) has $numberOfControllers SCSI Controller(s) attached. You chose to attach a new disk to the $controllerNumber. adapter"

Write-Host "The VM ($vm) has a "(get-scsiType $vm $scsiID)" Controller for the number you provided"
add-DiskToVmOnController $vm ($vm | get-scsicontroller -ID $scsiID)
Write-Host "Added a disk of $diskGB GB to $vm on controller "($vm | get-scsicontroller -ID $scsiID).Name
}
}
else {
$numberOfControllers = get-scsiCount $vm
$scsiID = get-scsiID $vm $numberOfControllers
Write-Host "The VM ($vm) has $numberOfControllers SCSI Controller(s) attached"

Write-Host "The VM ($vm) has a "(get-scsiType $vm $scsiID)" Controller as the last one"
add-DiskToVmOnController $vm ($vm | get-scsicontroller -ID $scsiID)
Write-Host "Added a disk of $diskGB GB to $vm on controller "($vm | get-scsicontroller -ID $scsiID).Name
}
Add-DiskToVmConnect-VIServerGet-VMImport-ModuleNew-HarddiskOut-NullRead-HostStart-VMStop-VMStop-VMGuestWrite-Host
powershell Find and disconnect CD Drives on your VMs 2 lines
Get-VMHost <your host> |Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"} | Get-CDDrive | Set-CDDrive -NoMedia -Confirm:$False
Get-VMHost <your host>| Set-VMHost -VMHost Host -State "Maintenance"
Get-CDDriveGet-VMGet-VMHostSet-CDDriveSet-VMHostWhere-Object
powershell Find and disconnect CD Drives on your VMs 1 lines
Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"} | Get-CDDrive | Set-CDDrive -NoMedia -Confirm:$False
Get-CDDriveGet-VMSet-CDDriveWhere-Object
powershell Testing your networks 460 lines

param
(
	[Parameter(Mandatory=$true)]
	[string]$clusterName,
	[Parameter(Mandatory=$true)]
	[string]$dvsName,
	[Parameter(Mandatory=$true)]
	[boolean]$isStandard,
	[Parameter(Mandatory=$true)]
	[pscredential]$creds,
	[Parameter(Mandatory=$true)]
	[string]$vmName,
	[Parameter(Mandatory=$true)]
	[string]$csvFile,
	[int]$timesToPing = 1,
	[int]$pingReplyCountThreshold = 1,
	[Parameter(Mandatory=$true)]
	[string]$resultFile
)

#Setup

# Configure internal variables
$trustVMInvokeable = $false #this is to speed development only.  Set to false.
$testResults = @()
$testPortGroupName = "VirtualFrog"
$data = import-csv $csvFile
$cluster = get-cluster $clusterName
$vm = get-vm $vmName

if ($isStandard -eq $false) {
    $dvs = get-vdswitch $dvsName
    $originalVMPortGroup = ($vm | get-Networkadapter)[0].networkname
	if ($originalVMPortGroup -eq "") {
		$originalVMPortGroup = ($vm | get-virtualswitch -name $dvsName |get-virtualportgroup)[0]
		write-host -Foregroundcolor:red "Adding a fantasy Name to $originalVMPortGroup"
	}
} else {
    $originalVMPortGroup = ($vm | get-Networkadapter)[0].networkname
    $temporaryVar = ($vm |get-networkadapter)[0].NetworkName
	if ($originalVMPortGroup -eq "") {
		$originalVMPortGroup = ($vm |get-vmhost |get-virtualswitch -name $dvsName |get-virtualportgroup -Standard:$true)[0]
		write-host -Foregroundcolor:red "Adding a fantasy Name to $originalVMPortGroup"
	}
}
#We'll use this later to reset the VM back to its original network location if it's empty for some reason wel'll populate it with the first portgroup

#Test if Invoke-VMScript works
if(-not $trustVMInvokeable) {
	if (-not (Invoke-VMScript -ScriptText "echo test" -VM $vm -GuestCredential $creds).ScriptOutput -eq "test") {
		write-output "Unable to run scripts on test VM guest OS!"
		return 1
	}
}

#Define Test Functions
function TestPing($ip, $count, $mtuTest) {
	if($mtuTest) {
		$count = 4 #Less pings for MTU test
		$pingReplyCountThreshold = 3 #Require 3 responses for success on MTU test.  Note this scope is local to function and will not impact variable for future run.
		$script = "ping -f -l 8972 -n $count $ip"
	} else {
		$script =  "ping -n $count $ip"
	}

	write-host "Script to run: $script"
	$result = Invoke-VMScript -ScriptText $script -VM $vm -GuestCredential $creds

	#parse the output for the "received packets" number
	$rxcount = (( $result.ScriptOutput | ? { $_.indexof("Packets") -gt -1 } ).Split(',') | ? { $_.indexof("Received") -gt -1 }).split('=')[1].trim()

	#if we received enough ping replies, consider this a success
	$success = ([int]$rxcount -gt $pingReplyCountThreshold) 

	#however there is one condition where this will be a false positive... gateway reachable but destination not responding
	if ( $result.ScriptOutput | ? { $_.indexof("host unreach") -gt -1 } ) {
		$success = $false
		$rxcount = 0;
	}

	write-host "Full results of ping test..."
	write-host $result.ScriptOutput

	return @($success, $count, $rxcount);
}

function SetGuestIP($ip, $subnet, $gw) {
  $script = @"
	`$iface = (gwmi win32_networkadapter -filter "netconnectionstatus = 2" | select -First 1).interfaceindex
	netsh interface ip set address name=`$iface static $ip $subnet $gw
	netsh interface ipv4 set subinterface `$iface mtu=9000 store=active
"@
  write-host "Script to run: " + $script
  return (Invoke-VMScript -ScriptText $script -VM $vm -GuestCredential $creds)
}

#Tests
# Per Port Group Tests  (Test each port group)

$vmhost = $vm.vmhost
if ($isStandard -eq $false)
{
	foreach($item in $data) {
		if($testPortGroup = $dvs | get-vdportgroup -name $item.PortGroup) {
			($vm | get-Networkadapter)[0] | Set-NetworkAdapter -Portgroup $testPortGroup -confirm:$false
			if( SetGuestIP $item.SourceIP $item.SubnetMask $item.GatewayIP ) {
				echo ("Set Guest IP to " + $item.SourceIP)

				#Run normal ping test
				$pingTestResult = TestPing $item.TestIP $timesToPing $false
				#Add to results
				$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
				$thisTest["Host"] = $vmhost.name
				$thisTest["PortGroupName"] = $testPortGroup.name
				$thisTest["VlanID"] = $testPortGroup.vlanconfiguration.vlanid
				$thisTest["SourceIP"] = $item.SourceIP
				$thisTest["DestinationIP"] = $item.TestIP
				$thisTest["Result"] = $pingTestResult[0].tostring()
				$thisTest["TxCount"] = $pingTestResult[1].tostring()
				$thisTest["RxCount"] = $pingTestResult[2].tostring()
				$thisTest["JumboFramesTest"] = ""
				$thisTest["Uplink"] = $thisUplink

				$testResults += new-object -typename psobject -Property $thisTest

				#DISABLED JUMBO FRAMES TEST!
				if($false) {
					#Run jumbo frames test
					$pingTestResult = TestPing $item.TestIP $timesToPing $true
					#Add to results
					$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
					$thisTest["Host"] = $vmhost.name
					$thisTest["PortGroupName"] = $testPortGroup.name
					$thisTest["VlanID"] = $testPortGroup.vlanconfiguration.vlanid
					$thisTest["SourceIP"] = $item.SourceIP
					$thisTest["DestinationIP"] = $item.TestIP
					$thisTest["Result"] = $pingTestResult[0].tostring()
					$thisTest["TxCount"] = $pingTestResult[1].tostring()
					$thisTest["RxCount"] = $pingTestResult[2].tostring()
					$thisTest["JumboFramesTest"] = ""
					$thisTest["Uplink"] = $thisUplink

					$testResults += new-object -typename psobject -Property $thisTest
				}	

			} else {
				$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
				$thisTest["PortGroupName"] = $testPortGroup.name
				$thisTest["VlanID"] = $testPortGroup.vlanconfiguration.vlanid
				$thisTest["SourceIP"] = $item.SourceIP
				$thisTest["DestinationIP"] = $item.GatewayIP
				$thisTest["Result"] = "false - error setting guest IP"
				$testResults += new-object -typename psobject -Property $thisTest
			}
		} else {
			$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
			$thisTest["PortGroupName"] = $item.PortGroup
			$thisTest["Result"] = "false - could not find port group"
			$testResults += new-object -typename psobject -Property $thisTest
		}
	}
}
else {
    #This is for a Standard Switch
	foreach($item in $data) {
		$dvs = $vm |get-vmhost | get-virtualswitch -name $dvsName
		if($testPortGroup = $dvs | get-virtualportgroup -name $item.PortGroup) {
			($vm | get-Networkadapter)[0] | Set-NetworkAdapter -Portgroup $testPortGroup -confirm:$false
			if( SetGuestIP $item.SourceIP $item.SubnetMask $item.GatewayIP ) {
				echo ("Set Guest IP to " + $item.SourceIP)

				#Run normal ping test
				$pingTestResult = TestPing $item.TestIP $timesToPing $false
				#Add to results
				$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
				$thisTest["Host"] = $vmhost.name
				$thisTest["PortGroupName"] = $testPortGroup.name
				$thisTest["VlanID"] = $testPortGroup.vlanid
				$thisTest["SourceIP"] = $item.SourceIP
				$thisTest["DestinationIP"] = $item.TestIP
				$thisTest["Result"] = $pingTestResult[0].tostring()
				$thisTest["TxCount"] = $pingTestResult[1].tostring()
				$thisTest["RxCount"] = $pingTestResult[2].tostring()
				$thisTest["JumboFramesTest"] = ""
				$thisTest["Uplink"] = $thisUplink

				$testResults += new-object -typename psobject -Property $thisTest

				#DISABLED JUMBO FRAMES TEST!
				if($false) {
					#Run jumbo frames test
					$pingTestResult = TestPing $item.TestIP $timesToPing $true
					#Add to results
					$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
					$thisTest["Host"] = $vmhost.name
					$thisTest["PortGroupName"] = $testPortGroup.name
					$thisTest["VlanID"] = $testPortGroup.vlanid
					$thisTest["SourceIP"] = $item.SourceIP
					$thisTest["DestinationIP"] = $item.TestIP
					$thisTest["Result"] = $pingTestResult[0].tostring()
					$thisTest["TxCount"] = $pingTestResult[1].tostring()
					$thisTest["RxCount"] = $pingTestResult[2].tostring()
					$thisTest["JumboFramesTest"] = ""
					$thisTest["Uplink"] = $thisUplink

					$testResults += new-object -typename psobject -Property $thisTest
				}	

			} else {
				$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
				$thisTest["PortGroupName"] = $testPortGroup.name
				$thisTest["VlanID"] = $testPortGroup.vlanid
				$thisTest["SourceIP"] = $item.SourceIP
				$thisTest["DestinationIP"] = $item.GatewayIP
				$thisTest["Result"] = "false - error setting guest IP"
				$testResults += new-object -typename psobject -Property $thisTest
			}
		} else {
			$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
			$thisTest["PortGroupName"] = $item.PortGroup
			$thisTest["Result"] = "false - could not find port group"
			$testResults += new-object -typename psobject -Property $thisTest
		}
	}
}

# Per Host Tests (Test Each Link for Each VLAN ID on each host)
$testPortGroup = $null

if ($isStandard -eq $false)
{

	($testPortGroup = new-vdportgroup $dvs -Name $testPortGroupName -ErrorAction silentlyContinue) -or ($testPortGroup = $dvs | get-vdportgroup -Name $testPortGroupName)
	($vm | get-Networkadapter)[0] | Set-NetworkAdapter -Portgroup $testPortGroup -confirm:$false

	$cluster | get-vmhost | ? {$_.ConnectionState -match "connected" } | foreach {
		$vmhost = $_
		#Migrate VM to new host
		if(Move-VM -VM $vm -Destination $vmhost) {

			foreach($item in $data) {
				#Configure test port group VLAN ID for this particular VLAN test, or clear VLAN ID if none exists
				$myVlanId = $null
				$myVlanId = (get-vdportgroup -name $item.PortGroup).VlanConfiguration.Vlanid
				if($myVlanId) {
					$testPortGroup = $testPortGroup | Set-VDVlanConfiguration -Vlanid $myVlanId
				} else {
					$testPortGroup = $testPortGroup | Set-VDVlanConfiguration -DisableVlan
				}

				if( SetGuestIP $item.SourceIP $item.SubnetMask $item.GatewayIP ) {
					echo ("Set Guest IP to " + $item.SourceIP)

					#Run test on each uplink individually
					$uplinkset = ( ($testPortGroup | Get-VDUplinkTeamingPolicy).ActiveUplinkPort + ($testPortGroup | Get-VDUplinkTeamingPolicy).StandbyUplinkPort ) | sort
					foreach($thisUplink in $uplinkset) {
						#Disable all uplinks from the test portgroup
						$testPortGroup | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -UnusedUplinkPort $uplinkset
						#Enable  only this uplink for the test portgroup
						$testPortGroup | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -ActiveUplinkPort $thisUplink

						#Run normal ping test
						$pingTestResult = TestPing $item.TestIP $timesToPing $false
						#Add to results
						$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
						$thisTest["Host"] = $vmhost.name
						$thisTest["PortGroupName"] = $testPortGroup.name
						$thisTest["VlanID"] = $testPortGroup.vlanconfiguration.vlanid
						$thisTest["SourceIP"] = $item.SourceIP
						$thisTest["DestinationIP"] = $item.TestIP
						$thisTest["Result"] = $pingTestResult[0].tostring()
						$thisTest["TxCount"] = $pingTestResult[1].tostring()
						$thisTest["RxCount"] = $pingTestResult[2].tostring()
						$thisTest["JumboFramesTest"] = ""
						$thisTest["Uplink"] = $thisUplink

						$testResults += new-object -typename psobject -Property $thisTest

						#DISABLED JUMBO FRAMES TEST!
						if($false) {
							#Run jumbo frames test
							$pingTestResult = TestPing $item.TestIP $timesToPing $true
							#Add to results
							$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
							$thisTest["Host"] = $vmhost.name
							$thisTest["PortGroupName"] = $testPortGroup.name
							$thisTest["VlanID"] = $testPortGroup.vlanconfiguration.vlanid
							$thisTest["SourceIP"] = $item.SourceIP
							$thisTest["DestinationIP"] = $item.TestIP
							$thisTest["Result"] = $pingTestResult[0].tostring()
							$thisTest["TxCount"] = $pingTestResult[1].tostring()
							$thisTest["RxCount"] = $pingTestResult[2].tostring()
							$thisTest["JumboFramesTest"] = ""
							$thisTest["Uplink"] = $thisUplink

							$testResults += new-object -typename psobject -Property $thisTest
						}
					}

					$testPortGroup | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -ActiveUplinkPort ($uplinkset | sort)

				} else {
					$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
					$thisTest["PortGroupName"] = $testPortGroup.name
					$thisTest["VlanID"] = $testPortGroup.vlanconfiguration.vlanid
					$thisTest["SourceIP"] = $item.SourceIP
					$thisTest["DestinationIP"] = $item.GatewayIP
					$thisTest["Result"] = "false - error setting guest IP"
					$testResults += new-object -typename psobject -Property $thisTest
				}
			}
		} else {
			$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
			$thisTest["Result"] = "false - unable to vMotion VM to this host"
			$testResults += new-object -typename psobject -Property $thisTest
		}
	}
}
else {
    #This is for a standard Switch
    $vmhost = $null

    #adding the testPortGroup on all hosts in the cluster
    $cluster | get-vmhost | ? {$_.ConnectionState -match "connected" } | sort | foreach {
		$dvs = get-virtualswitch -Name $dvsName -VMhost $_
    	$dvs | new-virtualportgroup -Name $testPortGroupName -ErrorAction silentlyContinue
    }

    $vmhost = $null
	$cluster | get-vmhost | ? {$_.ConnectionState -match "connected" } | sort | foreach {
		$vmhost = $_
		$dvs = get-virtualswitch -Name $dvsName -VMhost $vmhost
		$testPortGroup = $dvs |get-virtualportgroup -Name $testPortGroupName -VMhost $vmhost -ErrorAction silentlyContinue

		#Migrate VM to new host
		if(Move-VM -VM $vm -Destination $vmhost) {
				write-host -Foregroundcolor:red "Sleeping 5 seconds..."
				start-sleep -seconds 5
				if (($vm | get-Networkadapter)[0] | Set-NetworkAdapter -Portgroup ($dvs |get-virtualportgroup -Name $testPortGroupName -VMhost $vmhost) -confirm:$false -ErrorAction stop)
				{
					write-host -Foregroundcolor:green "Adapter Change successful"
				}else {
				    write-host -Foregroundcolor:red "Cannot change adapter!"
				    #$esxihost = $vm |get-vmhost
				    #$newPortgroup = $esxihost | get-virtualportgroup -Name testPortGroupName -ErrorAction silentlyContinue
				    #if (($vm | get-Networkadapter)[0] | Set-NetworkAdapter -Portgroup ($newPortgroup) -confirm:$false -ErrorAction stop) {
				    #    write-host -Foregroundcolor:green "Adapter Change successful (2nd attempt)"
				    #} else {
				    #    write-host -Foregroundcolor:red "Cannot change Adapter even on 2nd attempt. Exiting script"
				    #    exit 1
				    #}
				}

			foreach($item in $data) {
				#Configure test port group VLAN ID for this particular VLAN test, or clear VLAN ID if none exists
				$myVlanId = $null
				$myVlanId = [int32](get-virtualportgroup -VMhost $vmhost -Standard:$true -name $item.PortGroup).Vlanid
				if($myVlanId) {
					$testPortGroup = $testPortGroup | Set-VirtualPortGroup -Vlanid $myVlanId
				} else {
					$testPortGroup = $testPortGroup | Set-VirtualPortGroup -VlanId 0
				}

				if( SetGuestIP $item.SourceIP $item.SubnetMask $item.GatewayIP ) {
					echo ("Set Guest IP to " + $item.SourceIP)

					#Run test on each uplink individually
					$uplinkset = ( ($testPortGroup | Get-NicTeamingPolicy).ActiveNic + ($testPortGroup |Get-NicTeamingPolicy).StandbyNic ) |sort
					foreach($thisUplink in $uplinkset) {
						#Disable all uplinks from the test portgroup
						$testPortGroup | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicUnused $uplinkset
						#Enable  only this uplink for the test portgroup
						$testPortGroup | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive $thisUplink

						#Run normal ping test
						$pingTestResult = TestPing $item.TestIP $timesToPing $false
						#Add to results
						$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
						$thisTest["Host"] = $vmhost.name
						$thisTest["PortGroupName"] = $testPortGroup.name
						$thisTest["VlanID"] = $testPortGroup.vlanid
						$thisTest["SourceIP"] = $item.SourceIP
						$thisTest["DestinationIP"] = $item.TestIP
						$thisTest["Result"] = $pingTestResult[0].tostring()
						$thisTest["TxCount"] = $pingTestResult[1].tostring()
						$thisTest["RxCount"] = $pingTestResult[2].tostring()
						$thisTest["JumboFramesTest"] = ""
						$thisTest["Uplink"] = $thisUplink

						$testResults += new-object -typename psobject -Property $thisTest

						#DISABLED JUMBO FRAMES TEST!
						if($false) {
							#Run jumbo frames test
							$pingTestResult = TestPing $item.TestIP $timesToPing $true
							#Add to results
							$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
							$thisTest["Host"] = $vmhost.name
							$thisTest["PortGroupName"] = $testPortGroup.name
							$thisTest["VlanID"] = $testPortGroup.vlanid
							$thisTest["SourceIP"] = $item.SourceIP
							$thisTest["DestinationIP"] = $item.TestIP
							$thisTest["Result"] = $pingTestResult[0].tostring()
							$thisTest["TxCount"] = $pingTestResult[1].tostring()
							$thisTest["RxCount"] = $pingTestResult[2].tostring()
							$thisTest["JumboFramesTest"] = ""
							$thisTest["Uplink"] = $thisUplink

							$testResults += new-object -typename psobject -Property $thisTest
						}
					}

					$testPortGroup | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive ($uplinkset | sort)

				} else {
					$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
					$thisTest["PortGroupName"] = $testPortGroup.name
					$thisTest["VlanID"] = $testPortGroup.vlanid
					$thisTest["SourceIP"] = $item.SourceIP
					$thisTest["DestinationIP"] = $item.GatewayIP
					$thisTest["Result"] = "false - error setting guest IP"
					$testResults += new-object -typename psobject -Property $thisTest
				}
			}
		} else {
			$thisTest = [ordered]@{"VM" = $vm.name; "TimeStamp" = (Get-Date -f s); "Host" = $vmhost.name;}
			$thisTest["Result"] = "false - unable to vMotion VM to this host"
			$testResults += new-object -typename psobject -Property $thisTest
		}
	}
}

#Clean up
if ($isStandard -eq $false)
{
	($vm | get-Networkadapter)[0] | Set-NetworkAdapter -Portgroup (get-vdportgroup $originalVMPortGroup) -confirm:$false
	Remove-VDPortGroup -VDPortGroup $testPortGroup -confirm:$false

} else {
	$tempvm = get-vm $vmName
	$temphost = $tempvm |get-VMhost
	$portGroupToRevertTo = $temphost |get-virtualportgroup -name $temporaryVar -Standard:$true
    ($vm | get-Networkadapter)[0] | Set-NetworkAdapter -Portgroup $portGroupToRevertTo -confirm:$false
    write-host -Foregroundcolor:green "Waiting 5 seconds for $vm to revert back to $temporaryVar"
    start-sleep -seconds 5
    $cluster | get-vmhost | ? {$_.ConnectionState -match "connected" } | foreach {
		$vmhost = $_
		$dvs = $vmhost | get-virtualswitch -Name $dvsName
		$testPortGroup = $dvs | get-virtualportgroup -name $testPortGroupName -Standard:$true -VMhost $vmhost
		remove-virtualportgroup -virtualportgroup $testPortGroup -confirm:$false
	}
}

#Future Test Ideas
#Query driver/firmware for each host's network adapters ?

#Show Results
$testResults | ft
$testResults | Export-CSV -notypeinformation $resultFile
Export-CSVGet-DateGet-NicTeamingPolicyGet-VDUplinkTeamingPolicyInvoke-VMScriptMove-VMRemove-VDPortGroupSet-NetworkAdapterSet-NicTeamingPolicySet-VDUplinkTeamingPolicySet-VDVlanConfigurationSet-VirtualPortGroup
powershell Find Zombie Files on Datastores 162 lines
##################################################################################
# Script:           RmOrphanedFiles.ps1
# Datum:            25.07.2017
# Version:          2.1
# History:          Added Comments
#                   Replaced Add-PSSnapin with Module Command
#                   Replaced Get-VmwOrphan Function
##################################################################################

[CmdletBinding(SupportsShouldProcess=$true)]
Param(
  [parameter()]
  [String]$vCenter = "virtualfrogvc.virtual.frog",
  # Change to a SMTP server in your environment
  [string]$SmtpHost = "mail.virtual.frog",
# Change to default email address you want emails to be coming from
    [string]$From = "[email protected]",
# Change to default email address you would like to receive emails
    [Array]$To = @("[email protected]","[email protected]"),
# Change to default Report Filename you like
    [string]$Attachment = "$env:temp\OrphanedFileReport-"+(Get-Date -f "yyyy-MM-dd")+".csv"
)

function Get-VmwOrphan{
<#
.EXAMPLE
  PS> Get-VmwOrphaned -Datastore DS1
.EXAMPLE
  PS> Get-Datastore -Name DS* | Get-VmwOrphaned
#>

  [CmdletBinding()]
  param(
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [PSObject[]]$Datastore
  )

  Begin{
    $flags = New-Object VMware.Vim.FileQueryFlags
    $flags.FileOwner = $true
    $flags.FileSize = $true
    $flags.FileType = $true
    $flags.Modification = $true

    $qFloppy = New-Object VMware.Vim.FloppyImageFileQuery
    $qFolder = New-Object VMware.Vim.FolderFileQuery
    $qISO = New-Object VMware.Vim.IsoImageFileQuery
    $qConfig = New-Object VMware.Vim.VmConfigFileQuery
    $qConfig.Details = New-Object VMware.Vim.VmConfigFileQueryFlags
    $qConfig.Details.ConfigVersion = $true
    $qTemplate = New-Object VMware.Vim.TemplateConfigFileQuery
    $qTemplate.Details = New-Object VMware.Vim.VmConfigFileQueryFlags
    $qTemplate.Details.ConfigVersion = $true
    $qDisk = New-Object VMware.Vim.VmDiskFileQuery
    $qDisk.Details = New-Object VMware.Vim.VmDiskFileQueryFlags
    $qDisk.Details.CapacityKB = $true
    $qDisk.Details.DiskExtents = $true
    $qDisk.Details.DiskType = $true
    $qDisk.Details.HardwareVersion = $true
    $qDisk.Details.Thin = $true
    $qLog = New-Object VMware.Vim.VmLogFileQuery
    $qRAM = New-Object VMware.Vim.VmNvramFileQuery
    $qSnap = New-Object VMware.Vim.VmSnapshotFileQuery

    $searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
    $searchSpec.details = $flags
    $searchSpec.Query = $qFloppy,$qFolder,$qISO,$qConfig,$qTemplate,$qDisk,$qLog,$qRAM,$qSnap
    $searchSpec.sortFoldersFirst = $true
  }

  Process{
    foreach($ds in $Datastore){
      if($ds.GetType().Name -eq "String"){
        $ds = Get-Datastore -Name $ds
        Write-Host "Checking Datastore $ds"
      }

# Only shared VMFS datastore
      if($ds.Type -eq "VMFS" -and $ds.ExtensionData.Summary.MultipleHostAccess){
        Write-Verbose -Message "$(Get-Date)`t$((Get-PSCallStack)[0].Command)`tLooking at $($ds.Name)"

# Define file DB
        $fileTab = @{}

# Get datastore files
        $dsBrowser = Get-View -Id $ds.ExtensionData.browser
        $rootPath = "[" + $ds.Name + "]"
        $searchResult = $dsBrowser.SearchDatastoreSubFolders($rootPath, $searchSpec) | Sort-Object -Property {$_.FolderPath.Length}
        foreach($folder in $searchResult){
          foreach ($file in $folder.File){
            $key = "$($folder.FolderPath)$(if($folder.FolderPath[-1] -eq ']'){' '})$($file.Path)"
            $fileTab.Add($key,$file)

            $folderKey = "$($folder.FolderPath.TrimEnd('/'))"
            if($fileTab.ContainsKey($folderKey)){
              $fileTab.Remove($folderKey)
            }
          }
        }

# Get VM inventory
        Get-VM -Datastore $ds | %{
          $_.ExtensionData.LayoutEx.File | %{
            if($fileTab.ContainsKey($_.Name)){
              $fileTab.Remove($_.Name)
            }
          }
        }

# Get Template inventory
        Get-Template | where {$_.DatastoreIdList -contains $ds.Id} | %{
          $_.ExtensionData.LayoutEx.File | %{
            if($fileTab.ContainsKey($_.Name)){
              $fileTab.Remove($_.Name)
            }
          }
        }

# Remove system files & folders from list
        $systemFiles = $fileTab.Keys | where{$_ -match "] \.|vmkdump"}
        $systemFiles | %{
          $fileTab.Remove($_)
        }

# Organise remaining files
        if($fileTab.Count){
          $fileTab.GetEnumerator() | %{
            $obj = [ordered]@{
              Name = $_.Value.Path
              Folder = $_.Name
              Size = $_.Value.FileSize
              CapacityKB = $_.Value.CapacityKb
              Modification = $_.Value.Modification
              Owner = $_.Value.Owner
              Thin = $_.Value.Thin
              Extents = $_.Value.DiskExtents -join ','
              DiskType = $_.Value.DiskType
              HWVersion = $_.Value.HardwareVersion
            }
            New-Object PSObject -Property $obj
          }
          Write-Verbose -Message "$(Get-Date)`t$((Get-PSCallStack)[0].Command)`tFound orphaned files on $($ds.Name)!"
        }
        else{
          Write-Verbose -Message "$(Get-Date)`t$((Get-PSCallStack)[0].Command)`tNo orphaned files found on $($ds.Name)."
        }
      }
    }
  }
}

Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
Connect-VIServer $vCenter -WarningAction SilentlyContinue | Out-Null
Write-Host "Connected to $vCenter. Starting script"

$bodyh = (Get-Date -f "yyyy-MM-dd HH:mm:ss") + "  -  the following orphaned files were found on Datastores. `n"
$body = Get-Datastore | Get-VmwOrphan
$body | Export-Csv "$Attachment" -NoTypeInformation -UseCulture
$body = $bodyh + ($body | Out-String)
$subject = "Report - orphaned Files on Datastores for $vCenter"
send-mailmessage -from "$from" -to $to -subject "$subject" -body "$body" -Attachment "$Attachment" -smtpServer $SmtpHost
Disconnect-VIServer -Server $vCenter -Force:$true -Confirm:$false
Add-PSSnapinConnect-VIServerDisconnect-VIServerExport-CsvGet-DatastoreGet-DateGet-PSCallStackGet-TemplateGet-VMGet-ViewGet-VmwOrphanGet-VmwOrphanedImport-ModuleNew-ObjectOut-NullOut-StringSort-ObjectWrite-HostWrite-Verbose
powershell Automating VMware Tools and Hardware Upgrades 489 lines
#####################################################################################################################
# Author:           Bechtle Schweiz AG, Dario Doerflinger (c) 2015-2017
# Skript:           Update_VMs_1.0.4.ps1
# Datum:            24.07.2017
# Version:          1.0.4
# Original Author:  AFokkema: http://ict-freak.nl/2009/07/15/powercli-upgrading-vhardware-to-vsphere-part-2-vms/
# Changelog:
#                   - Improved Readability and added a general variables section
#                   - Addedd functionality to upgrade VM Version 7 VMs
#                   - Added Snapshot Mechanism to enable Linux Tools Upgrade
#                   - Added functionality to upgrade VM Versions to 11
#                   - Added functionality to upgrade VM Versions to 13 (12 is only for Desktop products)
#                   - Changed Add-Snapin to Import Module (not relevant for PowerCLI 6.5.1)
#
# Summary:          This script will upgrade the VMWare Tools level and the hardware level from VMs
#####################################################################################################################
clear
Write-Host " "
Write-Host " "
Write-Host "######################## Update_VMs_1.0.4.ps1 ##########################"
Write-Host " "
Write-Host "            this script updates  VMware Tools und hardware."
Write-Host " "
Write-Host "######################################################################"
Write-Host " "

Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
# This script adds some helper functions and sets the appearance.
#"C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCliEnvironment.ps1"

# Variables
$vCenter = Read-Host "Enter your vCenter servername"
#$Folder = Read-Host "Enter the name of the folder where the VMs are stored"
$timestamp = Get-Date -format "yyyyMMdd-HH.mm"
# Note: enter the csv file without extension:
$csvfile = "c:\tmp\$timestamp-vminfo.csv"
$logFile = "c:\tmp\vm-update.log"

#Rotate the Logfile
if (Test-Path $logFile)
{
    if (Test-Path c:\tmp\old_vm-update.log)
    {
        Remove-Item -Path c:\tmp\old_vm-update.log -Force -Confirm:$false
    }
    Rename-Item -Path $logfile -NewName old_vm-update.log -Force -Confirm:$false
}

#LogFunction: Standard at Coop!
function LogWrite
{
    #Aufruf: LogWrite "Tobi ist doof" "INFO" "1"
    Param([string]$logString, [string]$logLevel, [string]$priority)
    $nowDate = Get-Date -Format dd.MM.yyyy
    $nowTime = Get-Date -Format HH:mm:ss

    if ($logLevel -eq "EMPTY")
    {
        Add-Content $logFile -value "$logstring"
        Write-Host $logString
    } else {
        Add-Content $logFile -value "[$logLevel][Prio: $priority][$nowDate][$nowTime] - $logString"
        Write-Host "[$logLevel][Prio: $priority][$nowDate][$nowTime] - $logString"

    }

}

################################################################
#       Einlesen der Cred fuer vCenter und ESXi Server          #
################################################################
#$vcCred = C:\vm-scripts\Get-myCredential.ps1 butob C:\vm-scripts\credentials
#$esxCred = C:\vm-scripts\Get-myCredential.ps1 root C:\vm-scripts\host-credential

###############################################################
#                  Prompt for Credentials                      #
################################################################
$vcCred = $host.ui.PromptForCredential("VCENTER LOGIN", "Provide VCENTER credentials (administrator privileges)", "", "")
#$esxCred = $host.ui.PromptForCredential("ESX HOST LOGIN", "Provide ESX host credentials (probably root)", "root", "")

Function Make-Snapshot($vm)
{
  $snapshot = New-Snapshot -VM $vm -Name "BeforeUpgradeVMware" -Description "Snapshot taken before Tools and Hardware was updated" -Confirm:$false

}

Function Delete-Snap()
{
  get-vm | get-snapshot -Name "BeforeUpgradeVMware" | Remove-Snapshot -Confirm:$false
  # $snapshot = Get-Snapshot -Name "BeforeUpgradeVMware" -VM $vm
  # Remove-Snapshot -Snapshot $snapshot -Confirm:$false
}

Function VM-Selection
{
   $sourcetype = Read-Host "Do you want to upgrade AllVMs, a VM, Folder, ResourcePool or from a VMfile?"
   if($sourcetype -eq "AllVMs")
   {
      $abort = Read-Host "You've chosen $sourcetype, this is your last chance to abort by pressing +C. Press  to continue selecting old hardware VMs"
      #$vms = Get-VM | Get-View | Where-Object {-not $_.config.template -and $_.Config.Version -eq "vmx-08" } | Select Name
      $vms = Get-VM | Get-View | Where-Object {-not $_.config.template} | Select Name
   }
   else
   {
      $sourcename = Read-Host "Give the name of the object or inputfile (full path) you want to upgrade"
      if($sourcetype -eq "VM")
      {
        $abort = Read-Host "You've chosen $sourcetype, this is your last chance to abort by pressing +C. Press  to continue selecting old hardware VMs"
        #$vms = Get-VM $sourcename | Get-View | Where-Object {-not $_.config.template -and $_.Config.Version -eq "vmx-08" } | Select Name
        $vms = Get-VM $sourcename | Get-View | Where-Object {-not $_.config.template} | Select Name
      }
      elseif($sourcetype -eq "Folder")
      {
        $abort = Read-Host "You've chosen $sourcetype, this is your last chance to abort by pressing +C. Press  to continue selecting old hardware VMs"
        #$vms = Get-Folder $sourcename | Get-VM  | Get-View | Where-Object {-not $_.config.template -and $_.Config.Version -eq "vmx-08" } | Select Name
        $vms = Get-Folder $sourcename | Get-VM  | Get-View | Where-Object {-not $_.config.template} | Select Name
      }
      elseif($sourcetype -eq "ResourcePool")
      {
        $abort = Read-Host "You've chosen $sourcetype, this is your last chance to abort by pressing +C. Press  to continue selecting old hardware VMs"
        #$vms = Get-ResourcePool $sourcename | Get-VM  | Get-View | Where-Object {-not $_.config.template -and $_.Config.Version -eq "vmx-08" } | Select Name
        $vms = Get-ResourcePool $sourcename | Get-VM  | Get-View | Where-Object {-not $_.config.template} | Select Name
      }
      elseif(($sourcetype -eq "VMfile") -and ((Test-Path -path $sourcename) -eq $True))
      {
        $abort = Read-Host "You've chosen $sourcetype with this file: $sourcename, this is your last chance to abort by pressing +C. Press  to continue selecting old hardware VMs"
        #$list = Get-Content $sourcename | Foreach-Object {Get-VM $_ | Get-View | Where-Object {-not $_.config.template -and $_.Config.Version -eq "vmx-08" } | Select Name }
        $list = Get-Content $sourcename | Foreach-Object {Get-VM $_ | Get-View | Where-Object {-not $_.config.template} | Select Name }
        $vms = $list
      }
      else
      {
         Write-Host "$sourcetype is not an exact match of AllVMs, VM, Folder, ResourcePool or VMfile, or the VMfile does not exist. Exit the script by pressing +C and try again."
      }
   }
   return $vms
}

Function PowerOn-VM($vm)
{
   Start-VM -VM $vm -Confirm:$false -RunAsync | Out-Null
   Write-Host "$vm is starting!" -ForegroundColor Yellow
   sleep 10

   do
   {
    $vmview = get-VM $vm | Get-View
    $getvm = Get-VM $vm
    $powerstate = $getvm.PowerState
    $toolsstatus = $vmview.Guest.ToolsStatus

    Write-Host "$vm is starting, powerstate is $powerstate and toolsstatus is $toolsstatus!" -ForegroundColor Yellow
    sleep 5
    #NOTE that if the tools in the VM get the state toolsNotRunning this loop will never end. There needs to be a timekeeper variable to make sure the loop ends

    }until(($powerstate -match "PoweredOn") -and (($toolsstatus -match "toolsOld") -or ($toolsstatus -match "toolsOk") -or ($toolsstatus -match "toolsNotInstalled")))

    if (($toolsstatus -match "toolsOk") -or ($toolsstatus -match "toolsOld"))
    {
      $Startup = "OK"
      Write-Host "$vm is started and has ToolsStatus $toolsstatus"
    }
    else
    {
      $Startup = "ERROR"
      [console]::ForegroundColor = "Red"
      Read-Host "The ToolsStatus of $vm is $toolsstatus. This is unusual. Press +C to quit the script or press  to continue"
      LogWrite "PowerOn Error detected on $vm" "ERROR" "1"
      [console]::ResetColor()
    }
    return $Startup
}

Function PowerOff-VM($vm)
{
   Shutdown-VMGuest -VM $vm -Confirm:$false | Out-Null
   Write-Host "$vm is stopping!" -ForegroundColor Yellow
   sleep 10

   do
   {
      $vmview = Get-VM $vm | Get-View
      $getvm = Get-VM $vm
      $powerstate = $getvm.PowerState
      $toolsstatus = $vmview.Guest.ToolsStatus

      Write-Host "$vm is stopping with powerstate $powerstate and toolsStatus $toolsstatus!" -ForegroundColor Yellow
      sleep 5

   }until($powerstate -match "PoweredOff")

   if (($powerstate -match "PoweredOff") -and (($toolsstatus -match "toolsNotRunning") -or ($toolsstatus -match "toolsNotInstalled")))
   {
      $Shutdown = "OK"
      Write-Host "$vm is powered-off"
   }
   else
   {
      $Shutdown = "ERROR"
      [console]::ForegroundColor = "Red"
      Read-Host "The ToolsStatus of $vm is $toolsstatus. This is unusual. Press +C to quit the script or press  to continue"
      LogWrite "PowerOff Error detected on $vm" "ERROR" "1"
      [console]::ResetColor()
   }
   return $Shutdown
}

Function Check-ToolsStatus($vm)
{
    $vmview = get-VM $vm | Get-View
    $status = $vmview.Guest.ToolsStatus

    if ($status -match "toolsOld")
    {
      $vmTools = "Old"
    }
    elseif($status -match "toolsNotRunning")
    {
      $vmTools = "NotRunning"
    }
    elseif($status -match "toolsNotInstalled")
    {
      $vmTools = "NotInstalled"
    }
    elseif($status -match "toolsOK")
    {
      $vmTools = "OK"
    }
    else
    {
      $vmTools = "ERROR"
      Read-Host "The ToolsStatus of $vm is $vmTools. Press +C to quit the script or press  to continue"
      LogWrite "VMware Tools Error detected on $vm" "ERROR" "1"
    }
   return $vmTools
}

Function Check-VMHardwareVersion($vm)
{
    $vmView = get-VM $vm | Get-View
    $vmVersion = $vmView.Config.Version
    $v7 = "vmx-07"
    $v8 = "vmx-08"
    $v9 = "vmx-09"
    $v10 = "vmx-10"
    $v11 = "vmx-11"
    $v13 = "vmx-13"
    if ($vmVersion -eq $v8)
    {
      $vmHardware = "Old"
    }
    elseif($vmVersion -eq $v7)
    {
      $vmHardware = "Old"
    }
    elseif($vmVersion -eq $v9)
    {
      $vmHardware = "Old"
    }
    elseif($vmVersion -eq $v10)
    {
      $vmHardware = "Old"
    }
    elseif($vmVersion -eq $v11)
    {
      $vmHardware = "Old"
    }
    elseif($vmVersion -eq $v13)
    {
      $vmHardware = "Ok"
    }
    else
    {
      $vmHardware = "ERROR"
      LogWrite "Hardware Version Error detected on $vm" "ERROR" "1"
      [console]::ForegroundColor = "Red"
      Read-Host "The Hardware version of $vm is not set to $v7 or $v8 or $v9 or $v10 or $v11 or $v13. This is unusual. Press +C to quit the script or press  to continue"
      [console]::ResetColor()
    }
    return $vmHardware
}

Function Upgrade-VMHardware($vm)
{
  $vmview = Get-VM $vm | Get-View
  $vmVersion = $vmView.Config.Version
  $v7 = "vmx-07"
  $v8 = "vmx-08"
  $v9 = "vmx-09"
  $v10 = "vmx-10"
  $v11 = "vmx-11"
  $v13 = "vmx-13"

  if ($vmVersion -eq $v7)
  {
    Write-Host "Version 7 detected" -ForegroundColor Red

    # Update Hardware
    Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow
    Get-View ($vmView.UpgradeVM_Task($v13)) | Out-Null
  }

  if ($vmVersion -eq $v8)
  {
    Write-Host "Version 8 detected" -ForegroundColor Red

    # Update Hardware
    Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow
    Get-View ($vmView.UpgradeVM_Task($v13)) | Out-Null
  }

  if ($vmVersion -eq $v9)
  {
    Write-Host "Version 9 detected" -ForegroundColor Red

    # Update Hardware
    Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow
    Get-View ($vmView.UpgradeVM_Task($v13)) | Out-Null
  }

  if ($vmVersion -eq $v10)
  {
    Write-Host "Version 10 detected" -ForegroundColor Red

    # Update Hardware
    Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow
    Get-View ($vmView.UpgradeVM_Task($v13)) | Out-Null
  }

  if ($vmVersion -eq $v11)
  {
    Write-Host "Version 10 detected" -ForegroundColor Red

    # Update Hardware
    Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow
    Get-View ($vmView.UpgradeVM_Task($v13)) | Out-Null
  }
}

Function CreateHWList($vms, $csvfile)
{
  # The setup for this hwlist comes from http://www.warmetal.nl/powerclicsvvminfo
  Write-Host "Creating a CSV File with VM info" -ForegroundColor Yellow

  $MyCol = @()
  ForEach ($item in $vms)
  {
    $vm = $item.Name
    # Variable getvm is required, for some reason the $vm cannot be used to query the host and the IP-address
    $getvm = Get-VM $VM
    $vmview = Get-VM $VM | Get-View

    # VM has to be turned on to make sure all information can be recorded
    $powerstate = $getvm.PowerState
    if ($powerstate -ne "PoweredOn")
    {
      PowerOn-VM $vm
    }

    $vmnic = Get-NetworkAdapter -VM $VM
    $nicmac = Get-NetworkAdapter -VM $VM | ForEach-Object {$_.MacAddress}
    $nictype = Get-NetworkAdapter -VM $VM | ForEach-Object {$_.Type}
    $nicname = Get-NetworkAdapter -VM $VM | ForEach-Object {$_.NetworkName}
    $VMInfo = "" | Select VMName,NICCount,IPAddress,MacAddress,NICType,NetworkName,GuestRunningOS,PowerState,ToolsVersion,ToolsStatus,ToolsRunningStatus,HWLevel,VMHost
    $VMInfo.VMName = $vmview.Name
    $VMInfo.NICCount = $vmview.Guest.Net.Count
    $VMInfo.IPAddress = [String]$getvm.Guest.IPAddress
    $VMInfo.MacAddress = [String]$nicmac
    $VMInfo.NICType = [String]$nictype
    $VMInfo.NetworkName = [String]$nicname
    $VMInfo.GuestRunningOS = $vmview.Guest.GuestFullname
    $VMInfo.PowerState = $getvm.PowerState
    $VMInfo.ToolsVersion = $vmview.Guest.ToolsVersion
    $VMInfo.ToolsStatus = $vmview.Guest.ToolsStatus
    $VMInfo.ToolsRunningStatus = $vmview.Guest.ToolsRunningStatus
    $VMInfo.HWLevel = $vmview.Config.Version
    $VMInfo.VMHost = $getvm.VMHost
    $myCol += $VMInfo
  }

  if ((Test-Path -path $csvfile) -ne $True)
  {
    $myCol |Export-csv -NoTypeInformation $csvfile
  }
  else
  {
    $myCol |Export-csv -NoTypeInformation $csvfile-after.csv
  }
}

Function CheckAndUpgradeTools($vm)
{
  $vmview = Get-VM $VM | Get-View
  $family = $vmview.Guest.GuestFamily
  $vmToolsStatus = Check-ToolsStatus $vm

  if($vmToolsStatus -eq "OK")
  {
    Write-Host "The VM tools are $vmToolsStatus on $vm"
  }
  elseif(($family -eq "windowsGuest") -and ($vmToolsStatus -ne "NotInstalled"))
  {
    Write-Host "The VM tools are $vmToolsStatus on $vm. Starting update/install now! This will take at few minutes." -ForegroundColor Red
    Get-Date
    Get-VMGuest $vm | Update-Tools -NoReboot
    do
    {
      sleep 10
      Write-Host "Checking ToolsStatus $vm now"
      $vmToolsStatus = Check-ToolsStatus $vm
    }until($vmToolsStatus -eq "OK")
    PowerOff-VM $vm
    PowerOn-VM $vm
  }
  else
  {
    LogWrite "Linux / Windows (no tools installed) detected: $vm" "WARNING" "1"
    # ToDo: If the guest is running windows but tools notrunning/notinstalled it might be an option to invoke the installation through powershell.
    # Options are then Invoke-VMScript cmdlet or through windows installer: msiexec-i "D: \ VMware Tools64.msi" ADDLOCAL = ALL REMOVE = Audio, Hgfs, VMXNet, WYSE, GuestSDK, VICFSDK, VAssertSDK / qn
    # We're skipping all non-windows guest since automated installs are not supported
    # Write-Host "$vm is a $family with tools status $vmToolsStatus. Therefore we're skipping this VM" -ForegroundColor Red

    Write-Host "$vm is a $family with tools status $vmToolsStatus. We are going to do the upgrade, but we'll take a snapshot beforehand"
    if ($vmToolsStatus -ne "NotInstalled")
    {
      Make-Snapshot $vm
      Get-Date
      Get-VMGuest $vm | Update-Tools -NoReboot
      do
      {
        sleep 10
        Write-Host "Checking ToolsStatus $vm now"
        $vmToolsStatus = Check-ToolsStatus $vm
      }until($vmToolsStatus -eq "OK")
      PowerOff-VM $vm
      PowerOn-VM $vm

    }

  }
}

Function CheckAndUpgrade($vm)
{
  $vmHardware = Check-VMHardwareVersion $vm
  $vmToolsStatus = Check-ToolsStatus $vm

  if($vmHardware -eq "OK")
  {
      Write-Host "The hardware level is $vmHardware on $vm"
  }
  elseif($vmToolsStatus -eq "OK")
  {
      Write-Host "The hardware level is $vmHardware on $vm." -ForegroundColor Red
      $PowerOffVM = PowerOff-VM $vm
      if($PowerOffVM -eq "OK")
      {
          Write-Host "Starting upgrade hardware level on $vm."
          Upgrade-VMHardware $vm
          sleep 5
          PowerOn-VM $vm
          Write-Host $vm "is up to date" -ForegroundColor Green
      }
      else
      {
          Write-Host "There is something wrong with the hardware level or the tools of $vm. Skipping $vm."
      }
  }
}

Connect-VIServer -Server $vcenter -Credential $vcCred -WarningAction SilentlyContinue | out-null
Write-Host "connecting to $vcenter"

$vms = VM-Selection
CreateHWList $vms $csvfile
foreach($item in $vms)
{
    $vm = $item.Name
    Write-Host "Test $vm"
    CheckAndUpgradeTools $vm
    CheckAndUpgrade $vm
}
CreateHWList $vms $csvfile
# $toggle = Read-Host "Would you like me to remove the snapshots taken on Linux VMs? (yes/no)"
# if ($toggle -eq "yes")
# {
#   Get-VM | Delete-Snap
# }
Disconnect-VIServer -Confirm:$false
Add-ContentAdd-SnapinConnect-VIServerDisconnect-VIServerForEach-ObjectGet-ContentGet-DateGet-FolderGet-NetworkAdapterGet-ResourcePoolGet-SnapshotGet-VMGet-VMGuestGet-ViewImport-ModuleInitialize-PowerCliEnvironmentInvoke-VMScriptNew-SnapshotOut-NullRead-HostRemove-ItemRemove-SnapshotRename-ItemStart-VMTest-PathUpdate-ToolsWhere-ObjectWrite-Host
powershell Report Empty LUNs 41 lines

##################################################################################
# Script:           Get-Empty-LUNs.ps1
# Datum:            24.07.2017
# Version:          1.1
# History:          Initial Script
#                   Changed values to share it online
##################################################################################

# vCenter Credentials koennen mit folgendem Command vorgaengig einmalig konfiguriert und hinterlegt werden
# New-VICredentialStoreItem $vCenter
# Default Parameter in erster "Param" Sektion anpassen, ansonnsten werden die hinterlegten Default Werte verwendet

[CmdletBinding(SupportsShouldProcess=$true)]
Param(
  [parameter()]
  [Array]$vCenter = @("vCenter 1","vCenter 2"),
  # Change to a SMTP server in your environment
  [string]$SmtpHost = "mailserver",
# Change to default email address you want emails to be coming from
    [string]$From = "here_is_your_from_email_address",
# Change to default email address you would like to receive emails
    [Array]$To = @("first","second"),
# Change to default Report Filename you like
    [string]$Attachment = "$env:temp\Empty-LUN-Report-"+(Get-Date -f "yyyy-MM-dd")+".csv"
)

Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
#There are multiple ways to achieve this. see other blog posts for more
$cred = D:\sw\Script\PowerShell\VMWare\Get-myCredentials.ps1 domain\user D:\sw\Script\PowerShell\VMWare\cred_doeda_dmz

Connect-VIServer $vCenter -Credential $cred -WarningAction SilentlyContinue | Out-Null
Write-Host "Connected to $vCenter. Starting script"

$bodyh = (Get-Date -f "yyyy-MM-dd HH:mm:ss") + "  -  the following Datastores were found to be empty. `n"
$body = foreach ( $cluster in Get-Cluster) {Get-Datastore -RelatedObject $cluster |? {($_ |Get-VM).Count -eq 0 -and $_ -notlike "*rest*" -and $_ -notlike "*_local" -and $_ -notlike "*snapshot*" -and $_ -notlike "*placeholder*"}|select Name, FreeSpaceGB, CapacityGB, @{N="NumVM";E={@($_ |Get-VM).Count}}, @{N="LUN";E={($_.ExtensionData.Info.Vmfs.Extent[0]).DiskName}}, @{N="Cluster";E={@($cluster.Name)}} |Sort Name }
$body | Export-Csv "$Attachment" -NoTypeInformation -UseCulture
$body = $bodyh + ($body | Out-String)
$subject = "Report - Emtpy Datastores"
send-mailmessage -from "$from" -to $to -subject "$subject" -body "$body" -Attachment "$Attachment" -smtpServer $SmtpHost
Disconnect-VIServer -Server $vCenter -Force:$true -Confirm:$false
Connect-VIServerDisconnect-VIServerExport-CsvGet-ClusterGet-DatastoreGet-DateGet-EmptyGet-VMImport-ModuleNew-VICredentialStoreItemOut-NullOut-StringWrite-Host
powershell Automating VM Shutdown triggered by USV 94 lines

############################################################################################
# Script name:     EvacuateVMsFromUSV.ps1
# Description:     Evacuate all VMs from one site in a active-active cluster and shut down the Hosts
# Version:         1.0
# Date:            20.07.2017
# Author:          Dario Doerflinger (virtualfrog.wordpress.com)
# History:         20.07.2017 - First tested release
############################################################################################

# Example: # e.g.: .\EvacuateVMsFromUSV.ps1 -SiteToShutdown Allschwil

param (
    [string]$SiteToShutdown # Identifier of site
)
$vCenter_server = "bezhvcs03.bechtlezh.ch"
# clear global ERROR variable
$Error.Clear()

# import vmware related modules, get the credentials and connect to the vCenter server
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
Import-Module -Name VMware.VimAutomation.Vds -ErrorAction SilentlyContinue |Out-Null
$creds = Get-VICredentialStoreItem -file  "C:\Users\Administrator\Desktop\login.creds"
Connect-VIServer -Server $vCenter_server -User $creds.User -Password $creds.Password |Out-Null

# define global variables

$current_date = $(Get-Date -format "dd.MM.yyyy HH:mm:ss")
$log_file = "C:\Users\Administrator\Desktop\\log_$(Get-Date -format "yyyyMMdd").txt"

Function SetDRStoAutomatic ($cluster)
{
    try {
        $cluster | Set-Cluster -DrsEnabled:$true -DrsAutomationLevel FullyAutomated -Confirm:$false |Out-Null
    } catch {
        Write-Host -Foregroundcolor:red "Could not set DRS Mode to automatic"
    }
}

Function RemoveRemovableMediaFromVMs($esxhost)
{
    try {
        $esxhost | Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"} | Get-CDDrive | Set-CDDrive -NoMedia -Confirm:$False |Out-Null

    } catch {
        Write-Host -Foregroundcolor:red "Could not get the vm objects from host."
    }
}

Function EvacuateVMsFromHost($esxhost)
{
    try {
        $esxhost | Set-VMHost -State Maintenance -Evacuate:$true -Confirm:$false |Out-Null
    } catch {
        Write-Host -Foregroundcolor:red "Could not put host into maintenance mode"
    }
}

Function ShutDownHost($esxhost)
{
    try {
       $esxhost | Stop-VMhost -Confirm:$false -Whatif
    } catch {
        Write-Host -Foregroundcolor:red "Could not shut down host"
    }
}

###### Main Program ######
if ($SiteToShutdown -eq "Allschwil") {
    $hosts = @("bezhesx40.bechtlezh.ch")

} elseif ($SiteToShutdown -eq "Pratteln")
{
    $hosts = @("bezhesx41.bechtlezh.ch")
}

foreach ($esxhost in $hosts)
{
    $cluster = (get-vmhost $esxhost).Parent
    SetDRStoAutomatic($cluster)

    $esxihost = Get-VMhost $esxhost
    RemoveRemovableMediaFromVMs($esxihost)
    EvacuateVMsFromHost($esxihost)
    ShutDownHost($esxihost)
}

# cleanup and removal of loaded VMware modules
Disconnect-VIServer -Server $vCenter_server -Confirm:$false |Out-Null
Remove-Module -Name VMware.VimAutomation.Vds -ErrorAction SilentlyContinue | Out-Null
Remove-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null

# write all error messages to the log file
Add-Content -Path $log_file -Value $Error
Add-ContentConnect-VIServerDisconnect-VIServerGet-CDDriveGet-DateGet-VICredentialStoreItemGet-VMGet-VMhostImport-ModuleOut-NullRemove-ModuleSet-CDDriveSet-ClusterSet-VMHostStop-VMhostWhere-ObjectWrite-Host
bash Automating VCSA Backup & Restore 290 lines
#!/bin/bash

#***************************************************************
# Get Options from the command line
#***************************************************************
while getopts "b:r:h" options
do
case $options in
                b ) opt_b=$OPTARG;;
                r ) opt_r=$OPTARG;;
                h ) opt_h=1;;
                \? ) opt_h=1;;
esac
done

###############################################
# bkp_rst.sh
#=============================================
# Name: bkp_rst.sh
# Datum: 24.07.2017
# Ziel: Mache ein Backup der vCenter Appliance Datenbank, Restore die Datenbank
#
# Autor: Dario aka virtualFrog
version="1.5"
#
# Changelog:
# 0.1                   dario           Initial-Setup
# 1.0                   dario           Testing, Testing, Testing
# 1.1                   dario           Added dynamic filename & cleanUp Function
# 1.2                   dario           Added local cleanup
# 1.3                   dario           Changed local cleanup to delete all but most recent 3 files
# 1.4                   dario           Added checkForErrors function and writeMail function
# 1.5                   dario           Added CheckForErrors before every exit statement

# Variablen
# ---------

#log-Variablen
log=/var/log/vmware_backup_restore.log

#Mail variabeln
recipients="[email protected],[email protected]"

#NFS-Parameter
nfsmount="vcsa"
nfsserver=""
nfsoptions="nfs4"

# Funktionen
# ----------

function print_banner
{
        echo "

___  __ ____   ___________
\  \/ // ___\ /  ___/\__  \

 \   /\  \___ \___ \  / __ \_
  \_/  \___  >____  >(____  /
           \/     \/      \/
                            "
echo "v$version"
}

function get_parameter
{
        echo "GET_PARAMETER"

        if [ $opt_h ]; then print_help
        fi

        #--------------------------------------
        # Check to see if -b was passed in
        #--------------------------------------
        if [ $opt_b ]; then
                backup_string=$opt_b
                echo -e "\tBackup: $backup_string"
                echo "Backup: $backup_string" >> $log
                echo ""
                validate_backup_path
                filename=`hostname`-`date +%Y-%d-%m:%H:%M:%S`.bak
                todo="backup"
                echo ""
        elif [ $opt_r ]; then
                restore_string=$opt_r
                echo -e "\tRestore: $restore_string"
                echo "Restore: $restore_string" >> $log
                echo ""
                validate_restore_path
                todo="restore"
                echo ""
        else
                echo "warning: no parameters supplied." >> $log
                echo -e "\tKeine Parameter gefunden."
                print_help
        fi

}

function print_help
{
        echo "Gueltige Parameter: -b  -r "
        echo ""
        echo "To restore you should mount the volume ($nfsmount) on ($nfsserver) which this script copies the backups to"
        exit 0
}

function init_log
{

                echo `date` > $log
                echo "fzag_bkp_rst.sh in der Version $version auf `hostname -f`" >> $log
                echo "____________________________________________" >> $log

                #echo "Nun startet das Script in der Version $version"
                echo ""
}
function validate_backup_path
{
        echo "VALIDATE BACKUP PATH"
        echo -e "\tChecking Backup Path: $backup_string"
        if [ ! -d "$backup_string" ]; then
                echo -e "\tDirectory did not exist. Creating.."
                mkdir -p $backup_string
                echo -e "\tDirectory created."
        else
                echo -e "\tDirectory does exist."
        fi
        echo ""
}

function validate_restore_path
{
        echo "VALIDATE RESTORE PATH"
        echo -e "\tChecking Backup Path: $restore_string"
        if [ -f $restore_string ];
        then
                echo -e "\tFile $restore_string exists."
                echo "File $restore_string exists." >> $log
        else
                echo -e "\tFile $restore_string does not exist. Exiting"
                echo "error: $restore_string does not exist." >> $log
                checkForErrors
                exit 1
        fi
        echo ""
}
function check_python_scripts
{
        echo "CHECK PYTHON SCRIPTS"
        echo -e "\tChecking if Python Scripts are available"
        DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
        if [ -f "$DIR/backup_lin.py" ]; then
                echo -e "\tBackup Script found, continue.."
                echo "script for backup found" >> $log
                if [ -f "$DIR/restore_lin.py" ]; then
                        echo -e "\tRestore Script found, continue.."
                        echo "script for restore found" >> $log
                else
                        echo -e "\tNo restore script found, exit"
                        echo "error: no python restore script found" >> $log
                        checkForErrors
                        exit 1
                fi
        else
                echo -e "\tNo backup script found, exit"
                echo "error: no python backup scripts found" >> $log
                checkForErrors
                exit 1
        fi
        echo ""
}

function create_backup
{
        echo "CREATE BACKUP"
        echo -e "\tCreating the Backup in the file $backup_string/bk.bak:"
        DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

        echo `python $DIR/backup_lin.py -f $backup_string/$filename` >> $log
        if [ $? -ne 0 ]; then
                echo -e "\tError: Return code from backup job was not 0"
                echo "error: return code from backup job was not 0" >> $log
                checkForErrors
                exit 1
        else
                if [ -f "$backup_string/$filename" ]; then
                        echo -e "\tSuccess! Backup created."
                        echo "success: backup created" >> $log
                fi
        fi
        echo ""
}

function restore_db
{
        echo "RESTORE DB"
        echo -e "\tRestoring Database with supplied Backup-File: $restore_string"
        DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
        echo `python $DIR/restore_lin.py -f $restore_string` >> $log
        if [ $? -ne 0 ]; then
                echo -e "\tError: Return code from restore job was not 0"
                echo "error: return code from restore job was not 0" >> $log
        fi
        echo ""

}

function mountNFS
{
        echo "MOUNT NFS"
        echo -e "\tMounting the given NFS Volume ($nfsmount) on server ($nfsserver)"
        if [[ ! -d /mnt/bkp ]]; then
                mkdir -p /mnt/bkp
        fi

        mount -t $nfsoptions $nfsserver:$nfsmount /mnt/bkp
        if [[ $? -ne 0 ]]; then
                echo -e "\tMount was not successful. Abort the operation"
                echo "mount was not successful" >> $log
                checkForErrors
                exit 1
        fi
        echo ""
        return 0
}

function copyBackup
{
        echo "COPY BACKUP"
        echo -e "\tCopying Backup to NFS Mount"
        cp $backup_string/$filename /mnt/bkp/
        if [[ $? -ne 0 ]]; then
                echo -e "\tCopy Operation was not successful. Abort the operation"
                echo "copy was not successful" >> $log
                checkForErrors
                exit 1
        fi
        echo ""
}

function unMountNFS
{
        echo "UMOUNT NFS"
        echo -e "\tUnmounting the NFS Mount"
        umount /mnt/bkp
        if [[ $? -ne 0 ]]; then
                echo -e "\tumount Operation was not successful."
                echo "umount was not successful" >> $log
        fi
        echo ""
}

function cleanUp
{
        echo "CLEAN UP"
        echo -e "\tCleaning up Backups older than 4 days and all local files but the 3 most recent"

        find /mnt/bkp -mtime +4 -exec rm -rf {} \;
        if [[ $? -ne 0 ]]; then
                echo -e "\tNFS cleanUp Operation was not successful."
                echo "NFS cleanUp was not successful" >> $log
        fi

        cd $backup_string
        ls -t1 $backup_string |tail -n +3 | xargs rm
        if [[ $? -ne 0 ]]; then
                echo -e "\tLocal cleanUp Operation was not successful."
                echo "local cleanUp was not successful" >> $log
        fi
        echo ""
}

function writeEmail
{
        echo "WRITE EMAIL"
        echo -e "\tSending the logfile as a mail to $recipients"
        subject="VCSA Backup has run into a error"
        from="root@`hostname -f`"
        body=`cat $log`

        /usr/sbin/sendmail "$recipients" <> $log
        service vmware-vdcs stop >> $log
        restore_db
        service-control --start vmware-vpxd >> $log
        service-control --start vmware-vdcs >> $log
        unMountNFS
        checkForErrors
fi
powershell Automating VM Skeleton Deployment 18 lines
# import VMware related modules
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null

# get server and credential input
$server = Read-Host "Please provide the servername (fqdn)"
$user_name = Read-Host "please provide the username (domain\user)"
$user_password_encrypted = Read-Host "please input the password" -AsSecureString
$file_location = Read-Host "where should the login.creds file be stored? (e.g.:c:\script)"

# convert password back to plain text for further use with New-VICredentialStoreItem
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($user_password_encrypted)
$user_password_decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 

# create credential file
New-VICredentialStoreItem -Host $server -User $user_name -Password $user_password_decrypted -File "$file_location\login.creds"

# remove VMware related modules
Remove-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
Import-ModuleNew-VICredentialStoreItemOut-NullRead-HostRemove-Module
powershell Automating VM Skeleton Deployment 112 lines
############################################################################################
# Script name:     VmAutomatedDeployment.ps1
# Description:     For simple virtual machine container provisioning use only.
# Version:         1.2
# Date:            02.02.2017
# Author:          Bechtle Steffen Schweiz AG
# History:         02.02.2017 - First tested release
#                  19.07.2017 - Replaced Portgroup for Networkname, diskformat and resource pool based on hostname
#                  19.07.2017 - Added return value: MAC Address of created VM as requested by customer
############################################################################################

# Example: # e.g.: .\VmAutomatedDeployment.ps1 -vm_name Test_A053763 -vm_guestid windows9_64Guest -vm_memory 2048 -vm_cpu 2 -vm_network "Server_2037_L2"

param (

    [string]$vm_guestid, # GuestOS identifier from VMware e.g. windows_64Guest for Windows 10 x64
    [string]$vm_name, # Name of the virtual machine
    #[int64]$vm_disk, # System disk size in GB
    [int32]$vm_memory, # Memory size in MB
    [int32]$vm_cpu, # Amount of vCPUs
    [string]$vm_network # Portgroup name to connect
    #[string]$vm_folder # VM Folder location

    # to get the GuestOS identifier run: [VMware.Vim.VirtualMachineGuestOsIdentifier].GetEnumValues()
    # Common Windows versions:
    #-------------------------
    # windows7_64Guest          // Windows 7 (x64)
    # windows7Server64Guest     // Windows Server 2008 R2
    # windows8_64Guest          // Windows 8 (x64)
    # windows8Server64Guest     // Windows Server 2012 R2
    # windows9_64Guest          // Windows 10 (x64)
    # windows9Server64Guest     // Windows Server 2016
)

# clear global ERROR variable
$Error.Clear()

# import vmware related modules, get the credentials and connect to the vCenter server
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
Import-Module -Name VMware.VimAutomation.Vds -ErrorAction SilentlyContinue |Out-Null
$creds = Get-VICredentialStoreItem -file  "C:\scripts\VmAutomatedDeployment\login.creds"
Connect-VIServer -Server $creds.Host -User $creds.User -Password $creds.Password |Out-Null

# define global variables
$init_cluster = 'virtualFrogLab'
$init_datastore = 'VF_ds_01'
$vm_folder = 'VM-Staging'
$current_date = $(Get-Date -format "dd.MM.yyyy HH:mm:ss")
$log_file = "C:\Scripts\VmAutomatedDeployment\log_$(Get-Date -format "yyyyMMdd").txt"
[int64]$vm_disk = 72
$dvPortGroup = Get-VDPortgroup -Name $vm_network

# check if var $VM_NAME already exists in the vCenter inventory

$CheckInventoryByVmName = Get-VM -Name $vm_name -ErrorAction Ignore

if ($CheckInventoryByVmName) {

    Write-Host "This virtual machine already exists!"

} else {

    # check the inputs for provisioning sizing of the virtual machine
    # allowed maximums: 2 vCPU / 8192MB vRAM / 100GB vDISK

    if ($vm_cpu -gt 2) {Write-Host "You input is invalid! (max. 2 vCPUs allowed)"}
    elseif ($vm_memory -gt 8192) {Write-Host "You input is invalid! (max. 8GB vRAM allowed)"}
    elseif ($vm_disk -gt 100) {Write-Host "You input is invalid! (max. 100GB vDisk size allowed)"}
    else {

        # create new virtual machine container
        # e.g.: .\VmAutomatedDeployment.ps1 -vm_name Test_A054108 -vm_guestid windows9_64Guest -vm_disk 72 -vm_memory 2048 -vm_cpu 2 -vm_network "Test 10.10.0.0"
        if ($vm_name -like "vm-t*")
        {
            $diskformat = "Thin"
            $init_cluster ="Test"
        }else {
            $diskformat = "Thick"
            $init_cluster = "Production"
        }
        $create_vm = New-VM -Name $vm_name -GuestId $vm_guestid -Location $vm_folder -ResourcePool $init_cluster -Datastore $init_datastore -DiskGB $vm_disk -DiskStorageFormat $diskformat -MemoryMB $vm_memory -NumCpu $vm_cpu -Portgroup $dvPortGroup -CD -Confirm:$false -ErrorAction SilentlyContinue

        # check if virtual machine exists
        if ($create_vm) {
            # change all network adapters to VMXNET3
            $change_vm_network = Get-VM -Name $create_vm | Get-NetworkAdapter | Set-NetworkAdapter -Type Vmxnet3 -Confirm:$false -ErrorAction SilentlyContinue

            # check if network adapter exists
            if ($change_vm_network) {
                Add-Content -Path $log_file -Value "$current_date     SCRIPT          $message"
                $macaddress = (get-vm -Name $create_vm |get-networkadapter).MacAddress
            } else {
                Write-Host "There was an unexpected error during the provisioning. For more information see log file: $log_file"
            }
        } else {
            Write-Host "There was an unexpected error during the provisioning. For more information see log file: $log_file"

        }

    }

}

# cleanup and removal of loaded VMware modules
Disconnect-VIServer -Server $creds.Host -Confirm:$false
Remove-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null

# write all error messages to the log file
Add-Content -Path $log_file -Value $Error

#return the MAC address
return $macaddress
Add-ContentConnect-VIServerDisconnect-VIServerGet-DateGet-NetworkAdapterGet-VDPortgroupGet-VICredentialStoreItemGet-VMImport-ModuleNew-VMOut-NullRemove-ModuleSet-NetworkAdapterWrite-Host
$OutArray = @()

$vms = Get-VM
foreach ($vm in $vms)
{
$myobj = "" | Select "VM", "DNSname", "Status"
$guest = Get-VMGuest -VM $vm
$pat = "."
$vmname = $guest.VmName
$hostname = $guest.HostName
$myobj.VM = $vmname
$myobj.DNSname = $hostname
if ( $hostname -ne $null)
{
$pos = $hostname.IndexOf(".")
if ( $pos -ne "-1")
{
$hostname = $hostname.Substring(0, $pos)
}
if ( $hostname -ne $vmname )
{
Write-Host -ForegroundColor Red "---> The VM: $vm has different DNS and Display-Name!"
Write-Host -ForegroundColor Red "---->Hostname: " $hostname
Write-Host -ForegroundColor Red "---->VmName: "$vmname
$myobj.Status = "Not OK!"
}
Else
{
Write-Host -ForegroundColor Green "---> The VM: $vm has identical Names."
$myobj.Status = "OK!"
}
}
Else
{
Write-Host -ForegroundColor Yellow "---> The VM: $vm is not powered-on. Hostname cannot be found in this state!"
$myobj.Status = "N/A"
}
Clear-variable -Name hostname
Clear-variable -Name vmname
$OutArray += $myobj
}
$OutArray | Export-Csv "c:\tmp\name_vs_dns_$vcenter.csv"
Export-CsvGet-VMGet-VMGuestWrite-Host