Friday, December 14, 2018

Vmware NSX SSL creation 

Using OpenSSL for NSX Manager SSL import:

Creates CSR and 4096 bit KEY

Creating NSX 6.4.2 SSL 

 

openssl req -out nsxcert.csr -newkey rsa:4096 -nodes -keyout nsxcert.key -config dc1vc2nsxmgr01.cnf

 

Log into WIndows PKI

Open CSR in Notepad++ then paste into the Windows PKI Cert web:

https://nsmvpkiweb01/certsrv/

 

Request a Cert

Submit a certificate request by using a base-64-encoded CMC or PKCS #10 file, or submit a renewal request by using a base-64-encoded PKCS #7 file.

Cert Template: VSphere6.5 (Drop down)

 

On Windows PKI server for vCenter SSL cert you will need the **Base 64 encode**:

nsxcert.cer (machine cert)

nsxcert.p7b (CA chain) Carries Sub and Root CA information

 

Open

nsxcert.p7b Extract Sub and Root CA and save as:

 

nsx-sub-root.cer 

nsx-root.cer

 

(Know order sequence)

 

Copy 3 files to the workstation with OPENSSL BIN directory

 

nsxcert.cer

nsx-sub-root.cer 

nsx-root.cer

 

**Have nsxcert.key in same BIN directory**

 

Use notepad++

machine+key+sub+root

 

 

save as .PEM

 

example: nsx-sub-root.pem

 

Convert PEM to PFX using OpenSSL

 

openssl pkcs12 -export -out nsx.pfx -inkey vransxcert.key -in nsx-machine.cer -certfile nsx-sub-root.pem

Monday, September 10, 2018

VCSA SAN Cert creation

  • PSC65-A.lab.local -- 192.168.1.211/24
  • PSC65-B.lab.local -- 192.168.1.212/24
  • VCSA65-A.lab.local -- 192.168.1.201/24
  • VCSA65-B.lab.local -- 192.168.1.202/24
The Virtual Machine names are pretty self-explanatory. I have the IP addresses set up as shown above. This configuration of PSC HA assumes that you have a new vSphere 6.5 environment set up.
I would also like to bring this everybody’s attention that all of the VMs are appliances and not Windows based machines. Most of the steps will be the same for Windows based PSCs as well.
There are a couple of prerequisites that I am going to show in this article as the setup is going to be very basic and there are plenty of articles available online for the same.
Firstly, you will have to install the primary external Platform Services Controller node (PSC65-A.lab.local). Then deploy the secondary SSO node (PSC65-B.lab.local) as a replication partner to the primary Platform Service Controller node.
My Load Balancer FQDN is going to be PSC-LB.lab.local with the IP Address 192.168.1.217/24. Make sure that all of the machines are resolvable using DNS server in the domain.
Now let us move on to the main part of the PSC HA configuration wherein we need to first create a Certificate Signing Request (CSR) from one of the PSC’s.
Log in to one of the PSCs using the root credentials. Create a directory called certs under the root directory. Next step is to create a configuration file which will be used to generate the CSR, the file name will be  psc_ha_csr_cfg.cfg.
Using the vi editor, create this file and edit the subjectAltName and commonName fields.
I have highlighted them in red below. The subjectAltName should contain the FQDNs of both the PSCs and the FQDN of the Load Balancer.
The commonName field will contain the FQDN of the Load Balancer.
distinguished_name = req_distinguished_name
encrypt_key = no
prompt = no
string_mask = nombstr
req_extensions = v3_req
[ v3_req ]
basicConstraints = CA:false
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = DNS:psc65-a.lab.local, DNS:psc65-b.lab.local, DNS:psc-lb.lab.local
[ req_distinguished_name ]
countryName = IN
stateOrProvinceName = State
localityName = City
0.organizationName = Company
organizationalUnitName = Department
commonName = psc-lb.lab.local
Save the file and run the below command to generate the CSR and the key file. The file CSR file will be called psc-ha-vip.csr and the key file will be called psc-ha-vip.key
openssl req -new -nodes -out /certs/psc-ha-vip.csr -newkey rsa:2048 -keyout /certs/psc-ha-vip.key -config /certs/psc_ha_csr_cfg.cfg
Next step is to obtain the certificate using the CSR that was generated in the previous step.
In my environment, I am using a Microsoft Root CA and I am not going to get into the details of how to create the CA and the steps to generate the certificates.
Below is the KB article that covers those topics for those who are not aware of how to do this. Basically, create the certificate using the CSR using a pre-defined template for VMware related certificates.
Obtaining vSphere certificates from a Microsoft Certificate Authority -> https://kb.vmware.com/kb/2112014
After performing the above steps, you will have two certificates that will be created. Once is the Machine_SSL certificate for the PSC and the second is the Root CA certificate.


Rename the certificate files to psc-ha-vip.crt  and CustomRootCA.crt. Upload the certificates to the PSC appliance using a utility like WinSCP.
Before opening a session to the appliance using WinSCP, run this command on the PSC so that it start a session successfully.
chsh -s root /bin/bash
We now have two certificates uploaded to the PSC appliance, run the below commands to create proper chains that we will be using to replace the existing certificate of the PSC appliances.
The below commands will give us the psc-ha-vip-chain.crt certificate.
cat /certs/psc-ha-vip.crt >> /certs/psc-ha-vip-chain.crt
cat /certs/CustomRootCA.crt >> /certs/psc-ha-vip-chain.crt
This command will give us the cachain.crt file.
cat /certs/CustomRootCA.crt >> /certs/cachain.crt
Note: If there are any intermediate certificate authorities, then you will have to run the following commands to create the cachain.crt file. Same applies to the psc-ha-vip-chain.crt as well, add the first two lines before the final line.
cat /certs/CustomInterCA1.crt >> /certs/cachain.crt
cat /certs/CustomInterCA2.crt >> /certs/cachain.crt
cat /certs/CustomRootCA.crt >> /certs/cachain.crt
We have finally reached the stage wherein we have all the files required to replace the PSC certificates. The three files that are required for the process are:
  • psc-ha-vip-chain.crt
  • cachain.crt
  • psc-ha-vip.key
Before continuing to the next step, make sure that you have these three files and are present in the /certs directory on the PSC appliance.
Moving on, let us start the Certificate-Manager utility on the Platform Services Controller using the below command.
 /usr/lib/vmware-vmca/bin/certificate-manager

Select option 1, use the default administrator@vsphere.local account and provide the password for the same.

From here select option 2 since we have already created the certificates required to replace the existing Machine SSL certificate.

As shown above, provide the details about the three files and hit Enter to start the certificate replacement.
If you have followed all the steps correctly, the certificate will be replaced successfully. Use the same three files and replace the certificate on the second PSC as well.
In the next post, we will be looking at how to configure the Load Balancer.
I hope this has been informative and thank you for reading!
 58 enabling FIPS (Federal Information Processing Standards) mode for SSH ensures that only FIPS-validated cryptographic algorithms are used, enhancing the security posture of your system to comply with strict security and compliance requirements. FIPS 140-2 is a U.S. government standard that specifies security requirements for cryptographic modules, and many organizations follow it to secure sensitive data.
 59 When FIPS mode is enabled for SSH on an ESXi 8 host, only FIPS 140-2 approved ciphers and cryptographic algorithms are allowed. The list of FIPS-compliant ciphers for SSH typically follows strict standards to ensure compliance with security requirements and to maintain a strong security posture.
60 configuring SSH gateway ports typically refers to controlling which ports are used for SSH traffic and ensuring secure communication through a gateway (proxy) if applicable. By default, SSH listens on port 22, but you can change this port or configure additional security settings if you use an SSH gateway or proxy.
61 Host-based authentication in SSH allows you to configure access controls that rely on the trust relationship between hosts, rather than individual user credentials. This means that once an ESXi host is configured to trust another host, users can SSH from the trusted host to the ESXi host without needing to provide a password.
62 Can configure the SSH session timeout settings to specify how long an SSH session can remain idle before it is automatically disconnected. You can also control the number of failed login attempts allowed before an SSH session is terminated or blocked. This helps enhance security by reducing the risk of unauthorized access through idle sessions or repeated login attempts.
63 Can configure the SSH idle timeout interval to automatically disconnect SSH sessions that have been idle for a specified period. This helps reduce security risks by ensuring that idle sessions do not remain open indefinitely.
65 configuring SSH with rhosts-based authentication refers to a legacy method that allows a user on one host to SSH into another host without a password, based on the trust relationship defined in files like .rhosts or /etc/hosts.equiv. This type of authentication is considered insecure by modern standards due to its susceptibility to spoofing attacks and lack of robust security measures. As a result, it is generally discouraged and disabled by default in newer versions of SSH and ESXi.
66.  SSH local port forwarding in ESXi 8 can be used to securely tunnel traffic between a local port on your client machine and a remote service on the ESXi host or within its network. This is particularly useful for securely accessing services that are only accessible from the ESXi host network, such as management interfaces or APIs, over an encrypted SSH connection.
67.  enabling SSH TCP forwarding allows you to use SSH to forward network connections, facilitating secure communication for services that might otherwise be inaccessible or unsecured. TCP forwarding is a powerful feature often used for tunneling or creating VPN-like behavior over an SSH connection, supporting use cases like port forwarding and secure access to internal services.
68.   Using SSH tunnels on ESXi can provide a secure means of accessing internal services or remote systems by tunneling traffic through a secure SSH connection. SSH tunnels create encrypted pathways for data, making it a useful technique for securely accessing otherwise restricted or unsecured services.
69.  configuring the SSH user environment involves setting up user-specific settings for SSH sessions, which can influence behaviors like environment variables, command execution, and session customization. This is useful for tailoring the experience for specific users accessing the ESXi shell over SSH. However, it's important to note that VMware ESXi is primarily designed as a hypervisor with a minimal OS, so the level of user environment customization is more limited compared to general-purpose Linux distributions.
74.  VMware supports configuration of Transport Layer Security (TLS) protocols to secure communication with various services on the host, such as vSphere Web Services and APIs. By configuring TLS settings, you can ensure secure communication channels and comply with security policies, such as disabling older, insecure versions of TLS.
76.  Transparent Page Sharing (TPS) in ESXi is a memory management feature that allows ESXi to identify identical memory pages used by different virtual machines (VMs) and store only a single copy of that page in memory. By reducing redundant memory usage, TPS can improve memory efficiency, allowing more VMs to run on a host with the same physical memory.
78.  VIBs (vSphere Installation Bundles) are packages used to install or update software components on an ESXi host, such as drivers, software updates, or third-party modules. Each VIB has an acceptance level, which defines the level of trust VMware assigns to the VIB and determines whether it can be installed on the host.
 

VCSA cli Commands


root@vcsa1 [ ~ ]# service-control –stop –all
Perform stop operation. vmon_profile=ALL, svc_names=None, include_coreossvcs=True, include_leafossvcs=True
2017-05-11T19:17:11.714Z Service vmware-vmon does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:11.714Z Running command: [‘/sbin/service’, u’vmware-vmon’, ‘stop’]
2017-05-11T19:17:32.018Z Done running command
2017-05-11T19:17:32.019Z Successfully stopped service vmware-vmon
Successfully stopped vmon services. Profile ALL.
2017-05-11T19:17:32.025Z Service vmware-psc-client does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:32.025Z Running command: [‘/sbin/service’, u’vmware-psc-client’, ‘status’]
2017-05-11T19:17:32.052Z Done running command
Successfully stopped service vmware-psc-client
2017-05-11T19:17:33.168Z Service vmdnsd does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:33.168Z Running command: [‘/sbin/service’, u’vmdnsd’, ‘status’]
2017-05-11T19:17:33.194Z Done running command
Successfully stopped service vmdnsd
2017-05-11T19:17:33.310Z Service vmware-stsd does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:33.310Z Running command: [‘/sbin/service’, u’vmware-stsd’, ‘status’]
2017-05-11T19:17:33.333Z Done running command
Successfully stopped service vmware-stsd
2017-05-11T19:17:34.445Z Service vmware-sts-idmd does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:34.445Z Running command: [‘/sbin/service’, u’vmware-sts-idmd’, ‘status’]
2017-05-11T19:17:34.470Z Done running command
Successfully stopped service vmware-sts-idmd
2017-05-11T19:17:35.547Z Service vmcad does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:35.547Z Running command: [‘/sbin/service’, u’vmcad’, ‘status’]
2017-05-11T19:17:35.576Z Done running command
Successfully stopped service vmcad
2017-05-11T19:17:35.656Z Service vmdird does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:35.656Z Running command: [‘/sbin/service’, u’vmdird’, ‘status’]
2017-05-11T19:17:35.679Z Done running command
Successfully stopped service vmdird
2017-05-11T19:17:35.768Z Service vmafdd does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:35.768Z Running command: [‘/sbin/service’, u’vmafdd’, ‘status’]
2017-05-11T19:17:35.792Z Done running command
Successfully stopped service vmafdd
2017-05-11T19:17:35.880Z Service lwsmd does not seem to be registered with vMon. If this is unexpected please make sure your service config is a valid json. Also check vmon logs for warnings.
2017-05-11T19:17:35.880Z Running command: [‘/sbin/service’, u’lwsmd’, ‘status’]
2017-05-11T19:17:35.905Z Done running command
Successfully stopped service lwsmd
root@vcsa1 [ ~ ]#

UCS Certificate Install

Install Trusted SSL Certificate in Cisco UCS Manager
derekseaman.com/2012/04/install-trusted-ssl-certificate-in.html
One of the tasks you should complete during the installation of the Cisco UCS Manager is configuring the Fabric Interconnects with a trusted SSL certificate. The procedure is straight forward, and only needs to be completed once, since the two Fabric Interconnects are clustered and the configuration is replicated between the two devices. In my example I’m using a Windows Server 2008 R2 Certificate Authority, but any CA should work, but the steps will vary a bit.

1. Login to your Windows CA web services site (https://yourCA/certsrv) and click on Download a CA certificate, certificate chain, or CRL.

2. On the next screen select the current root certificate, Base 64 encoding, and then click on Download CA certificate chain.

3. Save the P7B certificate file and open it in a text editor such as Notepad. Paste the contents of the file to the clipboard.

4. Login to the Cisco UCSM and click on the Admin tab. Right click on Key Management and select Create Trusted Point. Enter a name for this trust point, such as the name of your CA. Then paste the contents of the clipboard into the certificate chain window. Click OK. 5. Right click on Key Management and select  Create Key Ring. Enter a keyring name, and select the modulus (I’d pick 2048). Left click on the new keyring and then click on Create Certificate Request.​ In the certificate request fill out the information appropriate. Use the FQDN for the “DNS” field and for the “Subject” name use the short hostname. The IP address should be the UCSM VIP (cluster) IP address. Click OK. 6. In the next window copy the request text to the clipboard. Login to your Windows CA then click on Request a certificate, advanced certificate request, then submit a certificate request by using a base-64 encoded CMC of PKCS#10 file. Paste the certificate request into the window provided, and select the appropriate certificate template, such as web server.
1/2
7. Download the certificate as Base 64 encoded, open it innotepad, then copy the contents to 

PowerCLI Reference commands

PowerCLI

This is a list of PowerCLI bits I have picked up along the way.  90% of these were found via Google, I apologize for not having credits for each. Most are simple one-liners that perform particular tasks.  It is typically easy to insert these bits into a larger scripts that loop through hosts, target specific VMs or just link them together to run multiple commands at once.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Add PowerCLI Core snapin
If (!(Get-PSSnapin -name VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
    Add-PSSnapin VMware.VimAutomation.Core}
 
# Add PowerCLI vCD snapin
If (!(Get-PSSnapin -name VMware.VimAutomation.Cloud -ErrorAction SilentlyContinue)) {
    Add-PSSnapin VMware.VimAutomation.Cloud}
 
# Add PowerCLI VDS snapin
If (!(Get-PSSnapin -name VMware.VimAutomation.VDS -ErrorAction SilentlyContinue)) {
    Add-PSSnapin VMware.VimAutomation.VDS}
 
# Connect to vCenter
Connect-VIServer vcenternameorip
# Disconnect from vCenter
Disconnect-VIServer vcenternameorip -Confirm:$False
 
# Connect to vCD
Connect-CIServer my.vcd.url
# Disconnect from vCD
Disconnect-CIServer my.vcd.url -Confirm:$False
 
# Connected VI Servers
$DefaultVIServers
# Number of Connected VI Servers
$DefaultVIServers.Count
 
# PowerCli Version
Get-PowerCLIVersion
 
# PowerCLI Configuration
Get-PowerCLIConfiguration
 
# VMHosts
# Change ESXi root password (or any other local user)
$VMHosts = Get-VMHost
ForEach ($VMHost in $VMHosts)
{
    $HostName = $VMHost.Name
    Connect-VIServer $HostName -User root -password P@ssw0rd
    Set-VMHostAccount -UserAccount root -password N3wPassword
    Disconnect-VIServer -Server $HostName -Confirm:$False
}
 
#Check Lockdown mode status
Get-VMHost | Select Name, @{Name="LockdownModeEnabled";Expression={($_).Extensiondata.Config.adminDisabled}} | ft -auto
 
#Disable Lockdown mode
Get-VMHost | %{($_ | get-view).ExitLockdownMode()}
 
#Enable Lockdown mode
Get-VMHost | %{($_ | get-view).EnterLockdownMode()}
 
# Start ESXi SSH Service
Get-VMHost | Foreach {Start-VMHostService -HostService ($_ | Get-VMHostService | Where { $_.Key -eq "TSM-SSH"} )}
 
# Stop ESXi SSH Service
Get-VMHost | Foreach {Stop-VMHostService -HostService ($_ | Get-VMHostService | Where { $_.Key -eq "TSM-SSH"} ) -Confirm:$false}
 
# View SSH Service state
Get-VMHost | Get-VMHostService | Where { $_.Key -eq "TSM-SSH" } | Select VMHost, Label, Policy, Running | ft -auto
 
#Enable SSH Server firewall exception
Get-VMHost | Get-VMHostFirewallException | Where {$_.Name -eq "SSH Server"} | Set-VMHostFirewallException -Enabled:$true
 
# Sets remote syslog server
Get-VMHost | Set-VMHostSysLogServer -SysLogServer "udp://yoursysogserver:514"
 
# Set Hostd logging level to info (default is verbose)
Get-VMHost | Get-AdvancedSetting -Name Config.HostAgent.log.level | Set-AdvancedSetting -Value "info" -Confirm:$false
 
# Set Vpxa logging level to info (default is verbose)(must be connected to VC)
Get-VMHost | Get-AdvancedSetting -Name Vpx.Vpxa.config.log.level | Set-AdvancedSetting -Value "info" -Confirm:$false
 
# Reset syslog service
$esxcli = Get-EsxCli -VMHost servername
$esxcli.system.syslog.reload()
 
# Sets ESXi syslog server firewall exception
Get-VMHost | Get-VMHostFirewallException |?{$_.Name -eq 'syslog'} | Set-VMHostFirewallException -Enabled:$true
 
# Backup ESXi Host Config
Get-VMHost MyESXiHost | Get-VMHostFirmware -BackupConfiguration -DestinationPath “F:\”
 
# Restore ESXi Host Config
Get-VMHost MyESXiHost | Set-VMHost -State Maintenance | Set-VMHostFirmware -Restore -SourcePath “F:\”
 
# Reset ESXi Host to defaults
Get-VMHost MyESXiHost | Set-VMHostFirmware -ResetToDefaults
 
# Gather Log Bundle from Host
Get-VMHost MyESXiHost | Get-Log -Bundle -DestinationPath “F:\”
 
# Gather Individual Logs
Get-VMHost MyESXiHost | Get-Log hostd | Select -ExpandProperty Entries | Out-File “F:\hostd.log”
Get-VMHost MyESXiHost | Get-Log vpxa | Select -ExpandProperty Entries | Out-File “F:\vpxa.log”
 
# Get the time on all ESXi hosts
Get-VMHost | Select Name,@{Name="Time";Expression={(get-view $_.ExtensionData.configManager.DateTimeSystem).QueryDateTime()}}
 
# Set the time on all ESXi hosts to the PowerCLI host's time
Get-VMHost | %{(Get-View $_.ExtensionData.configManager.DateTimeSystem).UpdateDateTime((Get-Date -format u)) }
 
# Rescan HBA Adapters
Foreach ($esx in Get-VMhost -Location ClusterName | sort Name) { $esx | Get-VMHostStorage -RescanAllHBA -rescanVMFS -refresh }
 
# Retrieve ntp servers
Get-VMHost | Select Name, @{N="NTPServer";E={$_ | Get-VMHostNtpServer}}, @{N="ServiceRunning";E={(Get-VmHostService -VMHost $_ | Where-Object {$_.key -eq "ntpd"}).Running}}
 
# Replace ntp servers on hosts
$oldntpservers = "192.168.0.1","192.168.0.2"
$newntpservers = "192.168.0.20","192.168.0.21"
Foreach($vmhost in Get-VMHost){
    #stop ntpd service
    $vmhost|Get-VMHostService |?{$_.key -eq "ntpd"}|Stop-VMHostService -Confirm:$false
    #remove ntpservers
    $vmhost|Remove-VMHostNtpServer -NtpServer $oldntpservers -Confirm:$false
    #add new ntpservers
    $vmhost|Add-VmHostNtpServer -NtpServer $newntpservers
    #start ntpd service
    $vmhost|Get-VMHostService |?{$_.key -eq "ntpd"}|Start-VMHostService
}
 
# Configure ntp service to start and stop with host
Get-VMHost | Get-VMHostService | ?{$_.key -eq "ntpd"} | Set-VMHostService -Policy "on" -confirm:$false
 
# Change DNS servers, domain name and search suffix
Get-VMHost | Get-VMHostNetwork | Set-VMHostNetwork -DnsAddress [DNS1 IP address],[DNS2 IP address] -Domain [Domain name] -SearchDomain [Search domain name]
 
# Enter Maintenance Mode
Get-VMHost | Set-VMHost -State Maintenance
 
#Add hosts to domain
Get-VMHost | Get-VMHostAuthentication | Set-VMHostAuthentication -Domain domain -User domainuser -Password password -JoinDomain -Confirm:$false
 
#Remove hosts from domain
Get-VMHost | Get-VMHostAuthentication | Set-VMHostAuthentication -LeaveDomain -Confirm:$false
 
#Check host domain status
Get-VMHost | Get-VMHostAuthentication | Select VMHost, DomainMembershipStatus, Domain | ft -auto
 
# Disconnect and Remove from VC
Get-VMHost | Set-VMHost-State Disconnected -Confirm:$false | Remove-VMHost -Confirm:$false
 
# Add into VC
Add-VMHost -Name $VMHost -Location $Location -Credential $cred -Force -Confirm:$false
 
# Join a cluster by moving an ESX host from one location to the cluster.
Move-Inventory -Item (Get-VMHost -Name esxHost) -Destination (Get-Cluster -Name clusterName)
 
 
 
# VM Stuff
# Get VM Information, Cluster, Host, Datastore
Get-VM | Select Name, @{N=”Cluster”;E={Get-Cluster -VM $_}},@{N=”ESX Host”;E={Get-VMHost -VM $_}},@{N=”Datastore”;E={Get-Datastore -VM $_}}
 
# Grab powered on Windows VMs in a particular folder
Get-Folder "projects" | Get-VM | Where-Object {$_.Guest.OSFullName -like "*Windows*" -and $_.PowerState -eq "PoweredOn"} | Sort Name
 
# Get VMs with CPU Reservations:
Get-VM | Get-VMResourceConfiguration | Where {$_.CpuReservationMhz -ne 0} | Select VM,CpuReservationMhz
 
# Get VMs with Memory Reservations:
Get-VM | Get-VMResourceConfiguration | Where {$_.MemReservationMB -ne 0} | Select VM,MemReservationMB
 
# Reset Memory resource limit to Unlimited
Get-VM | Get-VMResourceConfiguration | Where-Object {$_.MemLimitMB -ne "-1"} | Set-VMResourceConfiguration -MemLimitMB $null
 
# Reset CPU resource limit to Unlimited
Get-VM | Get-VMResourceConfiguration | Where-Object {$_.CpuLimitMhz -ne "-1"} | Set-VMResourceConfiguration -CPULimitMhz $null
 
# Reset both Memory and CPU resource limits to Unlimited (slow)
Get-VM | Get-VMResourceConfiguration | Set-VMResourceConfiguration -MemLimitMB $null -CpuLimitMhz $null
 
# Get Running VMs without VMware Tools Installed:
Get-View -ViewType “VirtualMachine” -Property Guest,name  -filter @{“Guest.ToolsStatus”=”toolsNotInstalled”;”Guest.GuestState”=”running”} | Select Name
 
# VMs Created Recently:
Get-VIEvent -maxsamples 10000 | Where {$_.Gettype().Name -eq “VmCreatedEvent”} | Select createdTime, UserName, FullFormattedMessage
 
# VMs Removed Recently:
Get-VIEvent -maxsamples 10000 | Where {$_.Gettype().Name -eq “VmRemovedEvent”} | Select createdTime, UserName, FullFormattedMessage
 
# List the last 10 VMs created, cloned or imported
Get-VIEvent -maxsamples 10000 |where {$_.Gettype().Name-eq "VmCreatedEvent" -or $_.Gettype().Name-eq "VmBeingClonedEvent" -or $_.Gettype().Name-eq "VmBeingDeployedEvent"} |Sort CreatedTime -Descending |Select CreatedTime, UserName,FullformattedMessage -First 10
 
# List last 5 VMs removed
Get-VIEvent -maxsamples 10000 | where {$_.Gettype().Name -eq "VmRemovedEvent"} | Sort CreatedTime -Descending | Select CreatedTime, UserName, FullformattedMessage -First 19
 
# List of the VM’s created over the last 14 days
Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-14) | where {$_.Gettype().Name-eq "VmCreatedEvent" -or $_.Gettype().Name-eq "VmBeingClonedEvent" -or $_.Gettype().Name-eq "VmBeingDeployedEvent"} |Sort CreatedTime -Descending |Select CreatedTime, UserName,FullformattedMessage
 
# List of the VMs removed over the last 14 days
Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-14) |where {$_.Gettype().Name-eq "VmRemovedEvent"} |Sort CreatedTime -Descending |Select CreatedTime, UserName,FullformattedMessage
 
# VMs with more than 2 vCPUs:
Get-VM | Where {$_.NumCPU -gt 2} | Select Name, NumCPU
 
# Check for invalid of inaccessible VMs:
Get-View -ViewType VirtualMachine | Where {-not $_.Config.Template} | Where{$_.Runtime.ConnectionState -eq “invalid” -or $_.Runtime.ConnectionState -eq “inaccessible”} | Select Name
 
# vMotion VM
Move-VM vm_name -Destination (Get-VMHost esxi_hostname)
 
# Storage vMotion VM
Get-VM vm_name | Move-VM -Datastore (Get-Datastore datastore_name)
 
# Create multiple new VMs from a template
$destCluster = Get-Cluster -Name Cluster01
$destDatastore = Get-DatastoreCluster -Name Cluster_Datastore
$destFolder = foldername
$sourceTemplate = Get-Template -Name W2K12_STD
1..6 | Foreach {New-VM -Name test0$_ -ResourcePool $destCluster -Location $destFolder -Template $sourceTemplate -Datastore $destDatastore -RunAsync}
 
 
 
# Storage
# Bulk storage moves
Get-VM -Datastore <SourceDatastore1> | Move-VM -Datastore <TargetDatastore> -runasync
 
# Delete all Snapshots with Certain Name:
Get-VM | Get-Snapshot | Where { $_.Name.Contains(“Consolidate”) } | Remove-Snapshot
 
# List all Snapshots:
Get-VM | Get-Snapshot | Select VM,Name,Description,Created
 
# List all RDM disks
Get-VM | Get-HardDisk -DiskType "RawPhysical","RawVirtual" | Select Parent,Name,DiskType,ScsiCanonicalName,DeviceName
 
# Search datastores for less than x free space
Get-Datastore | Where-Object {$_.freespaceMB -lt 100000}
Get-Datastore | Where-Object {$_.freespaceGB -lt 500 -and $_.Name -notlike "*localstorage*"}
 
# # of VMs per Datastore
Get-Datastore | Select Name, @{N="NumVM";E={@($_ | Get-VM).Count}} | Sort Name
 
# Mount datastore to psdrive
New-PSDrive -name "mounteddatastore" -Root \ -PSProvider VimDatastore -Datastore (Get-Datastore $datastore)
 
# Copy files to mounted datastore
Copy-Datastoreitem $patchLocation + $patch -Destination mounteddatastore:
 
# Delete file on mounted datastore
del mounteddatastore:$patch
 
# Unmount datastore from psdrive
Remove-PSDrive -name "mounteddatastore" -PSProvider VimDatastore
 
# Reload inaccessable VMs after a NFS/iSCSI outage
Get-View -ViewType VirtualMachine | ?{$_.Runtime.ConnectionState -eq "invalid" -or $_.Runtime.ConnectionState -eq "inaccessible"} | %{$_.reload()}
 
# Get Host HBA WWNs
Function Get-VMHostHbaWWN {
    param( $VMHost )
    $EsxHostHba = get-vmhosthba -VMHost $VMHost
    foreach( $hba in $EsxHostHba ){
        $WWN = "{0:x}" -f $hba.PortWorldWideName
        $outObj = New-Object PSObject
        $outObj | Add-Member -MemberType NoteProperty -Name Name -Value $VMHost
        $outObj | Add-Member -MemberType NoteProperty -Name WWNDec -Value $hba.PortWorldWideName
        $outObj | Add-Member -MemberType NoteProperty -Name WWNHex -Value $WWN
        $outObj | Add-Member -MemberType NoteProperty -Name Device -Value $hba.Device
        $outObj | Add-Member -MemberType NoteProperty -Name Type -Value $hba.Type
        $outObj | Add-Member -MemberType NoteProperty -Name Model -Value $hba.Model
        $outObj | Add-Member -MemberType NoteProperty -Name Status -Value $hba.Status
        $outObj
    }
}
 
 
 
# Networking
# Add Port Group “VLAN 500” with VLAN tag 500 to vSwitch1 on all hosts in a Cluster
Foreach ($esx in Get-VMHost -Location ClusterName) { $esx | Get-VirtualSwitch -Name vSwitch1 | New-VirtualPortGroup -Name "VLAN500" -VlanId 500 }
 
# Backup each vNetwork Distributed Switch not including the port groups
export-vdswitch $switch -Withoutportgroups -Description “Backup of $switch without port groups” -Destination “c:\vSphere\$switch.without_portgroups.$date.zip“
 
# Backup each vNetwork Distributed Switch including the port groups
export-vdswitch $switch -Description “Backup of $switch with port groups” -Destination “c:\vSphere\$switch.with_portgroups.$date.zip“
 
# Backup each port group individually
get-vdswitch $switch | Get-VDPortgroup | foreach { export-vdportgroup -vdportgroup $_ -Description “Backup of port group $($_.name)” -destination “c:\vSphere\$($_.name).portgroup.$date.zip“}
 
# Swing VMs from one port group to another
get-vm | get-networkadapter | where-object { $_.networkname -like "OldPortGroup" } | set-networkadapter -networkname "NewPortGroup" -Confirm:$false
 
 
 
# vCenter
# Gather vCenter Logons
Get-VIEvent -MaxSamples 100000 | ?{($_ -is [VMware.Vim.UserLoginSessionEvent]) -or ($_ -is [VMware.Vim.UserLogoutSessionEvent])} | %{
if ($_ -is [VMware.Vim.UserLoginSessionEvent]) {
  $strLoginOrLogout = "logged in"; $strSourceIP = $_.IpAddress
}
  else {
  $strLoginOrLogout = "logged out"; $strSourceIP = $null
  }
New-Object -TypeName PSObject -Property @{
UserName = $_.UserName
SourceIP = $strSourceIP
Time = $_.CreatedTime
Action = $strLoginOrLogout
}
} | Select UserName,SourceIP,Time,Action

Vmware NSX SSL creation 

Using OpenSSL for NSX Manager SSL import: Creates CSR and 4096 bit KEY Creating NSX 6.4.2 SSL    openssl req -out nsxcert.csr -newkey rsa:40...