Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Active Directory Powershell: Aduser A value for the attribute was not in the acceptable range of values

August 21, 2017 08:02PM

While writing and testing script Active Directory Powershell: Create bulk users from CSV file, Simulating single user creation I came across an error. This error says.

New-ADUser : A value for the attribute was not in the acceptable range of values
At line:1 char:1
+ New-ADUser -Name TestUser -PasswordNotRequired $true -path 'ou=new,dc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=TestUser,ou=new,dc=vcloud-lab,dc=com:String) [New-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8322,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Error is coming up due to incorrect value provided in parameter country as shown in the screenshot. If you even use Set-Aduser same error can be produced.

Active directory domain controller powershell, active directory user properties create new-aduser country a value for the attribute was not in the acceptable range of values

If you see on the Active directory users and computers, dsa.mmc console >> user properties >> Address tab  >> drop down the list of Country/region, It shows full name of the all countries, if I use them in parameter value for example India, it will throw an error. To see correct value I ran cmdlet Get-ADUser username -Properties Country and it showed me country alpha-2 code instead. 

Active Directory Powershell Get-Aduser country properties error -ADUser  A value for the attribute was not in the acceptable range of values

Below are the list of all country with their respective valid Alpha 2 codes. Parameter value need to be supplied as a below code list instead full name. 

Country Name Country code
Afghanistan AF
Åland Islands AX
Albania AL
Algeria DZ
American Samoa AS
Andorra AD
Angola AO
Anguilla AI
Antarctica AQ
Antigua and Barbuda AG
Argentina AR
Armenia AM
Aruba AW
Australia AU
Austria AT
Azerbaijan AZ
Bahamas BS
Bahrain BH
Bangladesh BD
Barbados BB
Belarus BY
Belgium BE
Belize BZ
Benin BJ
Bermuda BM
Bhutan BT
Bolivia (Plurinational State of) BO
Bonaire, Sint Eustatius and Saba BQ
Bosnia and Herzegovina BA
Botswana BW
Bouvet Island BV
Brazil BR
British Indian Ocean Territory IO
Brunei Darussalam BN
Bulgaria BG
Burkina Faso BF
Burundi BI
Cabo Verde CV
Cambodia KH
Cameroon CM
Canada CA
Cayman Islands KY
Central African Republic CF
Chad TD
Chile CL
China CN
Christmas Island CX
Cocos (Keeling) Islands CC
Colombia CO
Comoros KM
Congo CG
Congo (Democratic Republic of the) CD
Cook Islands CK
Costa Rica CR
Côte d'Ivoire CI
Croatia HR
Cuba CU
Curaçao CW
Cyprus CY
Czechia CZ
Denmark DK
Djibouti DJ
Dominica DM
Dominican Republic DO
Ecuador EC
Egypt EG
El Salvador SV
Equatorial Guinea GQ
Eritrea ER
Estonia EE
Ethiopia ET
Falkland Islands (Malvinas) FK
Faroe Islands FO
Fiji FJ
Finland FI
France FR
French Guiana GF
French Polynesia PF
French Southern Territories TF
Gabon GA
Gambia GM
Georgia GE
Germany DE
Ghana GH
Gibraltar GI
Greece GR
Greenland GL
Grenada GD
Guadeloupe GP
Guam GU
Guatemala GT
Guernsey GG
Guinea GN
Guinea-Bissau GW
Guyana GY
Haiti HT
Heard Island and McDonald Islands HM
Holy See VA
Honduras HN
Hong Kong HK
Hungary HU
Iceland IS
India IN
Indonesia ID
Iran (Islamic Republic of) IR
Iraq IQ
Ireland IE
Isle of Man IM
Israel IL
Italy IT
Jamaica JM
Japan JP
Jersey JE
Jordan JO
Kazakhstan KZ
Kenya KE
Kiribati KI
Korea (Democratic People's Republic of) KP
Korea (Republic of) KR
Kuwait KW
Kyrgyzstan KG
Lao People's Democratic Republic LA
Latvia LV
Lebanon LB
Lesotho LS
Liberia LR
Libya LY
Liechtenstein LI
Lithuania LT
Luxembourg LU
Macao MO
Macedonia (the former Yugoslav Republic of) MK
Madagascar MG
Malawi MW
Malaysia MY
Maldives MV
Mali ML
Malta MT
Marshall Islands MH
Martinique MQ
Mauritania MR
Mauritius MU
Mayotte YT
Mexico MX
Micronesia (Federated States of) FM
Moldova (Republic of) MD
Monaco MC
Mongolia MN
Montenegro ME
Montserrat MS
Morocco MA
Mozambique MZ
Myanmar MM
Namibia NA
Nauru NR
Nepal NP
Netherlands NL
New Caledonia NC
New Zealand NZ
Nicaragua NI
Niger NE
Nigeria NG
Niue NU
Norfolk Island NF
Northern Mariana Islands MP
Norway NO
Oman OM
Pakistan PK
Palau PW
Palestine, State of PS
Panama PA
Papua New Guinea PG
Paraguay PY
Peru PE
Philippines PH
Pitcairn PN
Poland PL
Portugal PT
Puerto Rico PR
Qatar QA
Réunion RE
Romania RO
Russian Federation RU
Rwanda RW
Saint Barthélemy BL
Saint Helena, Ascension and Tristan da Cunha SH
Saint Kitts and Nevis KN
Saint Lucia LC
Saint Martin (French part) MF
Saint Pierre and Miquelon PM
Saint Vincent and the Grenadines VC
Samoa WS
San Marino SM
Sao Tome and Principe ST
Saudi Arabia SA
Senegal SN
Serbia RS
Seychelles SC
Sierra Leone SL
Singapore SG
Sint Maarten (Dutch part) SX
Slovakia SK
Slovenia SI
Solomon Islands SB
Somalia SO
South Africa ZA
South Georgia and the South Sandwich Islands GS
South Sudan SS
Spain ES
Sri Lanka LK
Sudan SD
Suriname SR
Svalbard and Jan Mayen SJ
Swaziland SZ
Sweden SE
Switzerland CH
Syrian Arab Republic SY
Taiwan, Province of China[a] TW
Tajikistan TJ
Tanzania, United Republic of TZ
Thailand TH
Timor-Leste TL
Togo TG
Tokelau TK
Tonga TO
Trinidad and Tobago TT
Tunisia TN
Turkey TR
Turkmenistan TM
Turks and Caicos Islands TC
Tuvalu TV
Uganda UG
Ukraine UA
United Arab Emirates AE
United Kingdom of Great Britain and Northern Ireland GB
United States of America US
United States Minor Outlying Islands UM
Uruguay UY
Uzbekistan UZ
Vanuatu VU
Venezuela (Bolivarian Republic of) VE
Viet Nam VN
Virgin Islands (British) VG
Virgin Islands (U.S.) VI
Wallis and Futuna WF
Western Sahara EH
Yemen YE
Zambia ZM
Zimbabwe ZW

Useful articles
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE (CHANGE) MANAGER NAME IN ORGANIZATION TAB OF USER
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE PROXYADDRESSES IN USER PROPERTIES ATTRIBUTE EDITOR
Powershell one liner: Create multiple user accounts

Active Directory Powershell: Create bulk users from CSV file

August 19, 2017 11:00PM

Creating bulk multiple user accounts on Active Directory Users and Computers mmc console is very boring and tough task also it is most of the time consuming and error prone tend to be lots of mistakes. If same task is done using automation it will be interesting and happen in less time. Active directory Powershell is best way to automate the task of importing users from excel file. 

Download script and csv file sample
download new-aduseraccount fake account inventory list in excel csv

My CSV file contains below AD user properties, I tried to cover and take all properties as much as possible. If you would like to add more properties follow Microsoft official link. You will have add the same in script and header column in CSV. Below is example of one user.

Name Patrick Heninghem  active directory powershell user properties all attributes and classes filled up new-aduser 
DisplayName Patrick Heninghem
GivenName Patrick
Surname Heninghem
SamAccountName PH6558
UserPrincipalName PH6558@vcloud-lab.com
EmployeeID 6558
AccountPassword PaTo@6558
Description Employee
EmailAddress Patrick.Heninghem@vcloud-lab.com
Enabled $True
MobilePhone 184.192.5.227
Company vcloud-lab.com
Office Development Center
Department Testing
Division Software
Organization Cider
OfficePhone 339692762
StreetAddress 2392 Cameron Road
City HIGH BRIDGE
State Wisconsin
Country US
PostalCode 54846
Path ou=New,dc=vcloud-lab,dc=com
ProfilePath \\vcloud-lab.com\Profiles\%username%

To execute ps1 scripts follow this blog Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled. Next I have kept my both the script in C:\temp folder location, change the location to folder using cd c:\temp command. I am running script and only providing csv file path.

.\New-AdUserAccount.ps1 -Path C:\temp\employees.csv

Active Directory Powershell  New-Aduser, domain controller new-aduseraccount, Ad user, users from csv file, enable-adaccount -identity, set-aduser, dsa.msc, ad users and computers, organization unit.

In next example if you are connecting to remote domain, I am giving explicit domain name and credential.

.\New-AdUserAccount.ps1 -Path C:\temp\employees.csv -Domain vCloud-lab.com -Credential 

Active Directory Powershell  New-Aduser, domain controller new-aduseraccount, Ad user, users from csv file, enable-adaccount -identity, set-aduser, best powershell function advanced usage teach powershell free

This code and CSV is available on Github.

#requires -version 3
<#
.SYNOPSIS
    Create new user account in Active Directory.
.DESCRIPTION
    The New-AdUserAccount cmdlet creates new user accounts on active directory domain controller from CSV file. It asks for parameter valid CSV file path, Optional Active directory domain name and Credential. This cmdlet uses
.PARAMETER Path
    Prompts you for CSV file path. There are 2 alias CSV and File, This is mandetory parameter and require valid path.
.PARAMETER Domain
    This is active directory domain name where you want to connect. 
.PARAMETER Credential
    Popups for active directory username password, supply domain admin user account for authentication.
.INPUTS
    [String]
    [Switch]
.OUTPUTS
    Output is on console directly.
.NOTES
    Version:        1.0
    Author:         Kunal Udapi
    Creation Date:  12 June 2017
    Purpose/Change: Bulk user account creation in Microsoft Active Directory domain from Excel/csv.
    Useful URLs: http://vcloud-lab.com/entries/active-directory/powershell-installing-and-configuring-active-directory-and-dns-server
.EXAMPLE
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv

    This command create bulk users account in logged in domain from CSV file, It uses default logged in Credentials.
.Example
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv -Domain vCloud-lab.com -Credential

    Here I have used all the parameters Path with user information, Domain name and Credentials.
.EXAMPLE
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv -Domain vCloud-lab.com
#>

[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com',
    DefaultParameterSetName='File')]
Param
(
    [parameter(ParameterSetName = 'File', Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [parameter(ParameterSetName = 'Credential', Position=0, Mandatory=$true)]
    [alias('CSV', 'File')]
    [ValidateScript({
        If(Test-Path $_){$true}else{throw "Invalid path given: $_"}
        })]
    [String]$Path,
    [Parameter(ParameterSetName='Credential', Position=1, Mandatory=$True)]
    [alias('ADServer', 'DomainName')]
    [String]$Domain,
    [Parameter(ParameterSetName='Credential')]
    [Switch]$Credential
)
#$Path = 'C:\temp\employees.csv'
if ($Credential.IsPresent -eq $True) {
    $Cred = Get-Credential -Message 'Type domain credentials to connect remote AD' -UserName (WhoAmI)
}
Import-Csv -Path $Path | foreach -Begin {
    try {
        Import-Module ActiveDirectory -ErrorAction Stop
    }
    catch {
        Write-host "Missing....Install ActiveDirectory Powershell feature -- RSAT (Remote Server Administration). Cannot Create Accounts" -BackgroundColor DarkRed
        Break
    }

} -Process {
    $UserProp = @{ 
            Name = $_.Name
            SamAccountName = $_.SamAccountName 
            UserPrincipalName = $_.UserPrincipalName 
            GivenName = $_.GivenName 
            DisplayName = $_.DisplayName 
            Surname = $_.Surname 
            AccountPassword = (ConvertTo-SecureString -AsPlainText $_.AccountPassword -Force) 
            Description = $_.Description
            EmployeeID = $_.EmployeeID 
            EmailAddress = $_.EmailAddress
            Path = $_.Path 
            MobilePhone = $_.MobilePhone
            Company = $_.Company
            Office = $_.Office 
            Department =  $_.Department 
            Division = $_.Division 
            Organization = $_.Organization 
            OfficePhone = $_.OfficePhone 
            StreetAddress = $_.StreetAddress
            City = $_.City
            State = $_.State
            Country = $_.Country
            PostalCode = $_.PostalCode
            ProfilePath = $_.ProfilePath
            ErrorAction = 'Stop'
    }
    try {
        $Name = $_.Name
        Write-Host "Processing account $Name" -NoNewline -BackgroundColor Gray
        switch ($PsCmdlet.ParameterSetName) {
            'Credential' {
                if ($Credential.IsPresent -eq $false) {
                    New-ADUser @UserProp -Server $Domain
                }
                else {
                    New-ADUser @UserProp -Server $Domain -Credential $Cred
                }
                Break
            }
            'File' {
                New-ADUser @UserProp; break
            }
        }
            Enable-ADAccount -Identity $_.SamAccountName -ErrorAction Stop
            Set-ADUser -Identity $_.SamAccountName -ChangePasswordAtLogon $True
            Write-Host "....Account $Name successfully created" -BackgroundColor DarkGreen
    }
    catch {
        Write-Host "....Processing $Name failed" -BackgroundColor DarkRed
    }
} -End {}

Useful articles
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE (CHANGE) MANAGER NAME IN ORGANIZATION TAB OF USER
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE PROXYADDRESSES IN USER PROPERTIES ATTRIBUTE EDITOR
Powershell one liner: Create multiple user accounts

Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled

August 19, 2017 03:12PM

By default PowerShell scripts ps1 extension files are restricted to execute on windows system (For windows 2016 it is by default remotesigned), Generally whenever you run ps1 file you will see below error on Powershell console. This is not the authentication issue instead no one can execute ps1 files even administrator. To run script first need to make changes on OS, even if there is single line in the ps1 script file. For this article I will be using basic program line "Hello world!"

PS C:\> .\Script.ps1
.\Script.ps1 : File C:\Script.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\Script.ps1
+ ~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

Microsoft Powershell Script execution get-Executionpolicy unrestricted script cannot be loaded because running scripts is disabled on this system, For more information, see about_Execution_Policies

Powershell script file extention is ps1. to execute it change the prompt with CD command to the folder where script is stored and . dot source it while running or give complete path as shown below. It will fail by default. 

Microsoft Powershell Script execution get-Executionpolicy set-executionpolicy dot source unrestricted script cannot be loaded because running scripts is disabled on this system, Information about_Execution_policies

The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at http://go.microsoft.com/fwlink/?LinkID=135170. Below policies list exists.

Policy Description
AllSigned All ps1 files must be digitally signed. If remote, signed, and executed, Windows PowerShell prompts the user to determine if files from the signing publisher should be run.
Bypass No files must be signed, and internet origin is not verified.
Default The most restrictive policy available. Restricted
RemoteSigned All ps1 Files originating from the internet must be digitally signed. If remote, signed, and executed, Windows PowerShell prompts the user to determine if files from the signing publisher should be run. Allow local scripts and remote signed scripts.
Restricted All PS1 files are blocked. Windows PowerShell prompts the user if the user hasn't decided whether to trust the publisher yet.

To view current execution policy check with command Get-ExecutionPolicy. By default result will be Restricted if no previous changes. After changing policy with command Set-ExecutionPolicy Unrestricted, press enter twice to accept yes. Choose appropriate one of the policy as per your environment hardening policy. Unrestricted is not recommended. As per below screenshot, script is executed successfully.

Microsoft Powershell Get-executionpolicy, Set-Executionpolicy Unrestricted script.ps1, execution policy change

Set-ExecutionPolicy : Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option. To change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser".
At line:1 char:1
+ Set-ExecutionPolicy Unrestricted
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

To run Set-Executionpolicy unrestricted cmdlet administrator rights are required. If admin rights (Run as Administrator) not preset it shows access denied error. But still non administrators can bypass below error using command Set-ExecutionPolicy -Scope CurrentUser Unrestricted. It work without admin rights and changes are applicable to the current logged in user only. 

Windows Powershell, Set-Executionpolicy Scope CurrentUser, get-Executionpolicy, unrestricted, registry key powershell, executionpolicy, shellids software

In the Background it is modifying registry key value data of HKEY_CURRENT_USER\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\ExecutionPolicy. This requires non administrator rights. But editing localmachine scope or HKEY_Local_Machine requires Administrator rights.

Powershell hkey_current_user, hkey_current_machine software microsoft powershell shellids microsoft.powershell, executionpolicy edit string registry key string value data


This is another way I use a lot to run ps1 scripts in complete restricted environments. I can perform same from cmd (command prompt) as well.

1) Once PowerShell is lanuched, by default execution policy is restricted and script cann't be run,
2 & 3) Using Powershell -executionpolicy unrestricted, I have lifted restrictions. and I am into nested powershell mode (Powershell inside powershell).
4) I verified running script that I can run script.
5) Nested Powershell is exited using command Exit.
6 & 7) If you don't want nested console and run file directly, you can run one liner command Powershell -executionpolicy unrestricted -file 'c:\script.ps1', It will provide the result and close the unrestricted powershell session.
8) Powershell is still in restricted execution node.

Windows Powershell, microsoft get-execution policy, Powershell -executionpolicy unrestricted -file, disabled ps run console, nested powershell examples


This is another best way and doesn't require any special requirement. Copy content from ps1 file and paste on PowerShell directly. Or copy paste code in function script { code here }. Using function you will get more control, and run it whenever you want without need to copy paste, just need to run function command name as shown below. it can also be stored in powershell profiles if you run same script file frequently.

vcloud-lab.com script notepad microsoft windows Powershell write-output hello world, script example, advance Function execute blocked script


I found below is best way to bypass powershell execution policy but using infrequently and no need to open file in notepad by running cat c:\script.ps1 | Invoke-expression. The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.

Last way in this article, Copy paste ps1 file content commands inside curly braces {} and use & and operator (also alias to invoke-expression/iex) to run it.

Execute Powershell get-content, cat, hello world write-output,  Invoke-expression, iex, running script execution policy unrestricted, script in curly braces

VMWare Powercli: Time Configuration (NTP - Network Time Protocol) on multiple Esxi server

August 16, 2017 05:01PM

This blog is related to my earlier blog vSphere ESXi security best practices: Time configuration - (NTP) Network Time Protocol, This is Powercli part of same article. Login into vCenter server, For more details check VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP.

To add ntpserver on esxi server run below command, For adding multiple NTP addresses, run same command with different server IP twice or use array as given format @('192.168.34.11','pool.ntp.org').
Add-VMHostNtpServer -VMHost esxi001.vcloud-lab.com -NtpServer 192.168.34.11

Once NTP IP addresses are added, Start ntpd service (daemon).
Get-VmHostService -VMHost esxi001.vcloud-lab.com | ? {$_.key -eq "ntpd"} | Start-VMHostService

Next setup ntpd service policy on (Start or Stop with esxi host)
Get-VmHostService -VMHost esxi001.vcloud-lab.com | ? {$_.key -eq "ntpd"} | Set-VMHostService -policy "on"

Powercli vmware esxi time configuration NTP (Network time Protocol) Add-VMHostNtpServer vmhost ntpserver Get-vmhostservice key start-vmhostservice, Set-VMhostservice ntpd ntp daemon policy on, Service status running true false

Next step check NTP client status in the esxi firewall. This step might not be required. 
Get-VMHostFirewallException -VMHost esxi001.vcloud-lab.com | ? {$_.Name -eq "NTP client"}

If in case firewall port 123 is not enabled execute below command.
Get-VMHostFirewallException -VMHost esxi001.vcloud-lab.com | ? {$_.Name -eq "NTP client"} | Set-VMHostFirewallException -Enabled:$true

Powercli esxi time configuration NTP (Network time Protocol) vmhost Get-VMHostFirewallException NTP client Set-VMHostFirewallException enabled UDP port 123, incoming and outgoing port

I have combined all above commands and created one single Powercli function, To execute it either copy paste script code on console directly as shown or store it in powershell profile (reopen Powershell). (Get-VMHost).Name contains the all esxi server names in vCenter server. Once script is executed successfully, it shows the progress.

Set-VMHostNTPServer -VMHost (Get-VMHost).Name -NtpServer @('192.168.34.11','192.168.34.12')

vmware Powercli, set-vmhostntpserver, start-vmhostservice, set-vmhostservice, get-vmhostfirewallexception, set-vmhostfirewallexception, add-vmhostntpserver

 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
function Set-VMHostNTPServer {  
   [CmdletBinding()]  
  #####################################   
  ## http://vcloud-lab.com
  ## Version: 1   
  ## Tested this script on successfully  
  ## 1) Powershell v6   
  ## 2) Windows 10
  ## 3) vSphere 6.5 (vcenter, esxi, powercli)
  #####################################   
  Param (  
     [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
     [ValidateNotNullOrEmpty()]
     [Alias("Name")]
     [string[]]$VMHost,
     [string[]]$NtpServer
   )  
   begin {}  
   Process {
        foreach ($esxi in $VMHost) {
            Write-Host "Working on $esxi"
            foreach ($Ntp in $NtpServer) {
                Add-VMHostNtpServer -VMHost $esxi -NtpServer $Ntp | Out-Null
            }
            $NTPService | Set-VMHostService -Policy 'on' | Out-Null
            Get-VMHostFirewallException -VMHost $esxi | ? {$_.Name -eq "NTP client"} | Set-VMHostFirewallException -Enabled:$true | Out-Null
            $AllServices = Get-VMHostService -VMHost $esxi  
            $NTPService = $AllServices | Where-Object {$_.Key -eq 'ntpd'}    
            if ($NTPService.running -eq $false) {  
                $NTPService | Start-VMHostService -confirm:$false | Out-Null
            }  
            else {  
                Write-Host -BackgroundColor DarkGreen -Object "ntpd service on $esxi is already running"  
            }
        }
   }  
   end {}  
}

 

vSphere ESXi security best practices: Time configuration - (NTP) Network Time Protocol

August 15, 2017 02:09PM

By default NTP - Network time protocol service is disabled on esxi server. ESXi servers always should be configured with NTP for below reasons.

Logs: Very first good reason is logs (events, /var/log). If your Esxi is not synchronized with Time server correctly, Details in logs will show incorrect dates and there will be hard time in finding or troubleshooting issues.
Snapshot creation: If your environment (mostly in test and development) is highly dependent on snapshots, Snapshot creation and resuming might have wrong time.
Virtual Machine startup and restart, Incorrect time will show in absence of NTP.
vMotion: In some environments virtual machine might take or sync timing from Esxi server directly using VMWare tools. While VM migration from esxi server to another esxi, if NTP is not configured, VM OS will pickup wrong time or may be out of sync.

VMWare Powercli: Time Configuration (NTP - Network Time Protocol) on multiple Esxi server

Timekeeping is a best practice in every environment. To enable and configure NTP services, on the esxi server, click Configure tab, from the left hand pane expand system select Time Configuration click Edit.

On the popup box select Use Network Time Protocol (Enable NTP client), Start service under NTP service status, and add NTP Servers. as inset screenshot you will see Time configuration is changed.vmware vsphere esxi, configure, time configuration, NTP Service settings start restart, startup policy, NTP servers, network time protocol

In case of NTP client is disabled, It can be enabled under security profile, firewall edit, check the NTP client status, This setting is not required as it is by default enabled in firewall.

vmware vsphere esxi, configure, time configuration, NTP Service settings start restart, startup policy, NTP servers, network time  protocol, Security Profile, NTP client, esxi Firewall

Powershell one liner: Create multiple user accounts

August 9, 2017 10:44PM

I had an opportunity to teach PowerShell Active Directory basics to some of my junior subordinate, Where I wanted them to show few test cases on creating multiple active directory user accounts, After building active directory from scratch, As this was the demo example lab, accounts created  running below one liner, I can create n number of user accounts in one shot, without wasting any time. Once command is executed it creates 20 accounts, name starting with user in the given ldap ou path. Password is blank and it will be asking for password upon login.

POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 

1..20 | foreach {New-ADUser -Name user$_ -PasswordNotRequired $true -Enabled $true -Path 'ou=Temp-Users, dc=vcloud-lab, dc=com'}

Active directory users and computers, New-AdUser Passwordnotrequired path ou organization unit, enabled user account

Useful articles
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE (CHANGE) MANAGER NAME IN ORGANIZATION TAB OF USER
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE PROXYADDRESSES IN USER PROPERTIES ATTRIBUTE EDITOR
Powershell one liner: Create multiple user accounts
Active Directory Powershell: Create bulk users from CSV file

Powershell: Change DNS IP addresses remotely on multiple computers using CIM & WMI

August 2, 2017 08:05PM

Although I had written this script around 4 years back I have again revised it to work it in more better way with status report on console. I used this script again after long time to change/update DNS ip addresses on remote Windows servers, after introducing my new upgraded DNS servers. Same task I performed but this time  to replace DNS ips on an average 6000 remote windows servers. As it can be seen in below screenshot, There are 2 Nics In my environment, on all the server and I wanted to change DNS IPs on physical adapter with name Ethernet only. 

If you check on windows 2012 and above server OS, physical network adapter is named as Ethernet by default, unless it is modified.

Windows Powershell Network Connections physical adapter Ethernet properties Internet Protocol version 4 tcpipv4 dns server addreses preferred dns

Copy script in the Set-DnsIP.ps1 file, I have kept file on root c:\ drive. Run Set-ExecutionPolicy Unrestricted, so ps1 scripts are allowed to execute. Next by running below command I will replace existing DNS IPs and it also verify it and shows result on console. For simplicity I am running this command directly from domain joined server logged in with domain admin username and password, So there is no requirement to mention credentials.
.\Set-DnsIP.ps1 -Name DSC01 -NetworkName Ethernet -DnsIPs @('192.168.33.5','192.168.33.6')

PARAMETERS
-Name = Put computername here
-NetworkName = Type network physical adapter name here which is found under network connections, in most of the cases it will named as Ethernet.
-DnsIP = here you can put multiple ip in array with @()
-Protocol = This is optional and Dcom (Remote procedure call - RPC) or WSman (Windows Powershell remoting need to be enabled) can be used here. By default it connects using Dcom and does not require any special configuration.
-Credential = This is another optional parameter and here you can add credentials to connect remotely or locally.

Another way of performing same task on multiple system, Here in below example I am fetching computer names from active directory domain controller and updating IP on those servers with foreach loop.

Get-ADComputer -Filter * | foreach {.\Set-DNSIP -Name $_.Name -NetworkName Ethernet -DnsIPs 192.168.33.11}

Powershell set dns IP remotely or locally Set-DnsIP Ethernet Physical adapter DnsIp, Get-ADComputer successful completion

In the last if you have list of servers in plain text file replace Get-Adcomputer -filter * with cat filename.txt. This script is based and built using CIM cmdlets.

to use different username and password credentials than the logged in user, use parameter -credential, it will popup for username and password.
.\Set-DnsIP.ps1 -Name DSC01 -NetworkName Ethernet -DnsIPs @('192.168.33.5','192.168.33.6') -Credential

  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
#requires -version 3
<#
.SYNOPSIS
    Set or change DNS IP address in network adapter.
.DESCRIPTION
    The Set-DnsIP cmdlet changes DNS IP addresses of a local or remote etherenet card on windows. It requires parameternames computername, Ethernet Name, DNS IP addresses. This cmdlet uses CIM and WMI (DCom and winrm) protocol to connect remote computer. 
.PARAMETER Name
    Prompts you for local or remote computer hostname, Computername parameter is an alias, This value can be taken from pipline by property name.
.PARAMETER NetworkName
    This is physical network adapter name on the windows server or desktop, By default 2012 and above windows OS network name is Ethernet.
.PARAMETER DnsIPs
    This sets DNS Ip addresses, multiple DNS servers can be provided with this parameters.
.PARAMETER Protocol
    There are two protocols can be used while connecting to remote computer, first is DCOM which is default and need not to mention, Default will work in all scenario. Another protocol is WSman require PS remoting need to be enabled. 
.INPUTS
    No Input
.OUTPUTS
    Output is on console directly.
.NOTES
  Version:        2.0
  Author:         Kunal Udapi
  Creation Date:  12 February 2017
  Purpose/Change: Update to my existing script buit on 1 June 2013 (http://kunaludapi.blogspot.in/2013/06/change-dns-ip-address-remotely-on.html)
  Useful URLs: http://vcloud-lab.com/entries/powershell/powershell-ps-remoting-between-standalone-workgroup-computers
.EXAMPLE 1
    PS C:\>Set-DNSIP -Name MyServer01 -NetworkName Ethernet -DnsIPs @('192.168.33.5', '192.168.33.6')

    This command sets DNS ips on computername 'MyServer01'. Physical Adapter name is 'Ethernet'. IP addresses can be mentioned in arrays.
.Example 2
    Get-ADComputer -Filter * | ForEach-Object {Set-DNSIP -Name $_.Name -NetworkName Ethernet -DnsIPs 192.168.33.11}

    Here computer names are pulled from active directory computers. Process further with Foreach-Object loop.
.EXAMPLE 3
    PS C:\>Set-DNSIP -Name MyServer01 -NetworkName Ethernet -DnsIPs 192.168.33.11 -Protocol Wsman

    With optional parameter name 'Protocol', DCom and WSMan protocol can be used, Dcom is default protocol and works in every scenario, for WSman Ps remoting need to be enabled and check notes help section for more information.
#>

[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com')]
Param
(
    [parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [alias('ComputerName')]
    [String]$Name = 'Localhost',
    [parameter(Position=1, Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    [alias('LAN', 'EthernetName')]
    [String]$NetworkName = 'EtherNet',
    [parameter(Position=2, Mandatory=$true, 
        ValueFromPipeline=$true)]
    [array]$DnsIPs = @('192.168.33.5','192.168.33.6'),
    [parameter(Position=3, Mandatory=$false)]
    [ValidateSet('Dcom','Default','Wsman')]
    [String]$Protocol = 'Dcom',
    [Switch]$Credential
)
Begin {
    $CimSessionOptions = New-CimSessionOption -Protocol $Protocol
    $Query = "Select * from  Win32_NetworkAdapter" #Where NetConnectionID='$NetworkName'"

    if (-not(Test-Connection -ComputerName $Name -Count 2 -Quiet)) {
        Write-Host -BackgroundColor DarkYellow ([char]8734) -NoNewline
        Write-Host " $Name is not reachable but still trying to connect...."
        #Break
    }
    else {
        Write-Host -BackgroundColor DarkGreen ([char]8730) -NoNewline
        Write-Host " $Name is reachable connecting...."
    }
}
Process {
    try {
        if ($Credential.IsPresent -eq $false) {
            $Cimsession = New-CimSession -Name $Name -ComputerName $Name -SessionOption $CimSessionOptions -ErrorAction Stop
        }
        else {
            $Cred = Get-Credential -Message 'Type Your credentials to connect remotely' -UserName (WhoAmI)
            $Cimsession = New-CimSession -Name $Name -ComputerName $Name -SessionOption $CimSessionOptions -Credential $Cred -ErrorAction Stop
        }
        $AllNICs = Get-CimInstance -Namespace 'root/CIMv2' -Query $Query -CimSession $Cimsession
        if ($AllNICs.NetConnectionID -contains $NetworkName) {
            $Nic = $AllNICs | Where-Object {$_.NetConnectionID -eq $NetworkName}
            $NICConf = Get-CimAssociatedInstance -InputObject $NIC -ResultClass Win32_NetworkAdapterConfiguration -CimSession $Cimsession
            $NICConfituraion = $NICConf | Invoke-CimMethod -MethodName SetDNSServerSearchOrder -Arguments @{DNSServerSearchOrder = $DnsIPs}
            $NICConf = Get-CimAssociatedInstance -InputObject $NIC -ResultClass Win32_NetworkAdapterConfiguration -CimSession $Cimsession
            $errorcode = $NICConfituraion.ReturnValue
        }
        else {
            Write-Host -BackgroundColor DarkRed ([char]215) -NoNewline
            Write-Host " Connected to $Name successfully but no NIC found with name $NetworkName"
        }
    }
    catch {
        Write-Host -BackgroundColor DarkRed ([char]215) -NoNewline
        Write-Host " DNS IP on $Name did not changed, check manually." 
        $errorcode = -1
    }
}
end{
    switch ($errorcode) { 
        -1 {Write-host -NoNewline ''}
        0 {Write-Host -BackgroundColor DarkGreen ([char]8730) -NoNewline; " Successful completion, no reboot required, New DNS IPs are $($NICConf.DNSServerSearchOrder -join ', ')"; break}
        1 {'Successful completion, reboot required'; break}
        64 {'Method not supported on this platform'; break}
        65 {'Unknown failure'; break}
        66 {'Invalid subnet mask'; break}
        67 {'An error occurred while processing an Instance that was returned'; break}
        68 {'Invalid input parameter'; break}
        69 {'More than 5 gateways specified'; break}
        70 {'Invalid IP address'; break}
        71 {'Invalid gateway IP address'; break}
        72 {'An error occurred while accessing the Registry for the requested information'; break}
        73 {'Invalid domain name'; break}
        74 {'Invalid host name'; break}
        75 {'No primary/secondary WINS server defined'; break}
        76 {'Invalid file'; break}
        77 {'Invalid system path'; break}
        78 {'File copy failed'; break}
        79 {'Invalid security parameter'; break}
        80 {'Unable to configure TCP/IP service'; break}
        81 {'Unable to configure DHCP service'; break}
        82 {'Unable to renew DHCP lease'; break}
        83 {'Unable to release DHCP lease'; break}
        84 {'IP not enabled on adapter'; break}
        85 {'IPX not enabled on adapter'; break}
        86 {'Frame/network number bounds error'; break}
        87 {'Invalid frame type'; break}
        88 {'Invalid network number'; break}
        89 {'Duplicate network number'; break}
        90 {'Parameter out of bounds'; break}
        91 {'Access denied'; break}
        92 {'Out of memory'; break}
        93 {'Already exists'; break}
        94 {'Path, file or object not found'; break}
        95 {'Unable to notify service'; break}
        96 {'Unable to notify DNS service'; break}
        97 {'Interface not configurable'; break}
        98 {'Not all DHCP leases could be released/renewed'; break}
        100 {'DHCP not enabled on adapter'; break}
        default {'Other - Error code 101–4294967295'; break}
    }
}

POWERCLI AND VSPHERE WEB CLIENT: JOIN ESXI INTO ACTIVE DIRECTORY DOMAIN CONTROLLER

July 26, 2017 09:22AM

This is another best security guideline to always join Esxi server into domin, most preferable is Active Directory domain controller, One of the advantage is I can use domain-wide authentication with Domain joined ESXi, Means I don't have to use or share root or any local username to login, Creating local username and maintaining it will be tedious job on Esxi, Users can login with there own elevated domain account and auditors can review the logs for activities performed directly on esxi. Before starting make sure you have configured AD-DNS server IP correctly, check my previous article on how to configure DNS on esxi server for the same. To check whether my DNS is functioning properly or for further troubleshooting on esxi server do ssh putty, ping or netcat domain ports and name, in my case when I ping domain name it is resolving IP address.

VMWARE SECURITY BEST PRACTICES: POWERCLI ENABLE OR DISABLE ESXI SSH

vmware vsphere esxi vcenter putty ping, telnet and nc, netcat

Further you check telnet below AD ports whether they are reachable from ESXi.
Port 88 - Kerberos authentication
Port 123 – NTP
Port 135 - RPC
Port 137 - NetBIOS Name Service
Port 139 - NetBIOS Session Service (SMB)
Port 389 - LDAP
Port 445 - Microsoft-DS Active Directory, Windows shares (SMB over TCP)
Port 464 - Kerberos - change/password changes
Port 3268- Global Catalog search

Next in the vSphere web client, on Esxi server, click Configure tab on the right, Next from left pane, under services, select Authentication Services. On this summary page, my Directory services Type is Local Authentication. to change it click Join domain button. In the popup box type domain and use credentials who has rights to pull computers in the domain.

VMware esxi vsphere vcenter configure Authentication services, directory services configuration, Join domain, leave domain, active directory, Trusted domain controllers

Once successful it changes directory services type to AD and Domain name.

Check the Advanced System Settings and search for esx admins or Config.HostAgent.plugins.hostsvc.esxAdminsGroup, here you see value ESX Admins, This Active directory group name that is automatically granted administrator privileges on the ESX. here I can change this group name if I want.

VMware vsphere esxi, Configure, Advanced system settings, config.hostagent.plugins.hostsvc.esxAdminsGroup, ESX Admins, active directory ad group

I will go ahead quickly on the Active directory users and computers mmc (dsa.msc) and create group name ESX Admins. Add few user members to it. Also notice there is Computer account got created with esxi name under Computers container (This location might be different in your environment)

vmware esxi computer account in active directory users and Computers, domain controllers, dsa.msc, Esx admins group properties members.png

Use embedded web esxi client using https://esxifqdn_or_Ip/ui and use your AD user account to login. No need to share root password with users now. Activities and Events are logged with user name.

esxi web client ui, login using ad domain account

Next for demostration. I have logged on to esxi with putty using domain account, It shows domain and username in the prompt, I fired up few commands, and they are logged - captured in /var/log/shell.log file, I will use tail or cat command to view content of file, and you can see the activities captured for root and user account.

vmware esxi active directory login ssh putty, ad user, /var/log var log, esxi log location, shell.log capture keyboard, linux tail command logs.png


VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP
In this powercli session I am performing same steps used above. (before proceeding I have reverted settings and removed esxi from domain)

First I will see the ad group name in esxi advanced settings which need to created on domain. Value is ESX Admins, I can create it in AD domain and Add users as member to it (Same can be done using New-AdGroup command).
Get-AdvancedSetting -Entity Esxi001.vcloud-lab.com -Name Config.HostAgent.Plugins.hostsvc.esxAdminsGroup

Using below I get the authentication status, Domain and DomainMembershipStatus is blank, means this server is still not a part of domain.
Get-VMHostAuthentication -VMHost esxi001.vcloud-lab.com

vmware esxi powercli esx admins ad domain group, Get-AdvancedSetting -Entity Config.HostAgent.Plugins.hostsvc.esxAdminsGroup, Get-VMhostAuthentication vmhost domainmembershipstatus, TrustedDomains

Running below command will join esxi into domain, it prompts for username and password and shows the domain name and current membership status to Ok.
Get-VMHostAuthentication -VMHost esxi001.vcloud-lab.com | Set-VMHostAuthentication -Domain vcloud-lab.com -Credential (Get-Credential) -JoinDomain -Confirm:$false

vmware vsphere esxi join domain Get-vmhostauthentication, set-vmhostauthentication, domain, credential, get-credential, joindomain confirm.png

VMWARE SECURITY BEST PRACTICES: POWERCLI ENABLE OR DISABLE ESXI SSH

July 25, 2017 09:14AM

Logging into SSH required in some of the common troubleshooting scenario or fetching information: ie  checking logs, telnet, ping, esxtop etc, Although subject title of this blog is mentioned Powercli, but I am showing all ways to enable SSH service on esxi including GUI as well, By default SSH server service is disabled on ESXi, VMware recommends the same for security best practices reason. For more on Esxi hardening follow this official guides. Whenever you need to login into Esxi directly through SSH (putty), this service (daemon) can be enabled using one of the method VMWare web client. 

Select Esxi server, go to Configure tab on the right side, collapse System and click Security Profile, here all required services are listed, SSH is is stopped. Press Edit button, 

vmware vsphere esxi, configure, Security profile, services, Edit services, SSH server and client , how to enable ssh on esxi server

In Edit Security Profile, select SSH daemon, service name from the list, down below expand Service Details, under status click Start button, and status will change to running. below screenshot is after starting service. Same procedure is used to stop it. Three types of startup policy exist.

Start and stop with host: If service is running it will start automatically once host is restarted. Same with if service is stopped, service status will persist with ESXi reboot.
Start and stop manually: This is self explanatory. service need to manually start or stop depending on status, Once Esxi is rebooted, service will be stopped. 
Start and stop with port usage: Start automatically if any ports are open, and stop when all ports are closed

vmware vsphere esxi, edit security profile, SSH daemon stopped running, start and stop manually, startup policy

Port status can be checked using withing Esxi firewall itself, make sure SSH port number 22 is open (by default it is open), If you are not able to putty also check physical firewall. Under Secure shell there are 2 option SSH server and SSH client. Server is esxi and used to connect. Client is once logged onto esxi you can use it as client to connect remote servers.

vmware vcenter esxi configure security profile firewall edit ssh server 22, allow connection from any ip web client

Next open putty and login to server and test server.

vmware vsphere esxi, putty how to ssh to esxi step by step guide, putty session, certificate rsa2 key accept, login as root.png


In this next tutorial I am using VMWare Powercli for starting and stopping SSH server, for Configuring and installing Powercli check my previous article VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP

Once logged onto vcenter or esxi successfully. I will check the the status of TSM-SSH service on Esxi Server, In my case it is not running and says false.
Get-VMHostService -VMHost esxi001.vcloud-lab.com | Where-Object {$_.Key -eq 'TSM-SSH'}

To start it use this one-liner powercli command.
Get-VMHostService -VMHost esxi001.vcloud-lab.com | Where-Object {$_.Key -eq 'TSM-SSH'} | Start-VMHostService -Confirm:$false

vmware vsphere esxi vcenter, vmware powercli, get-vmhostservice, where-object tsm-ssh, Policy, Stop-VMHostService

Powershell and $profile, microsoft.powershell_profile.ps1 module path environment $env psmodulepath -split, modules powershell, windows powershell.pngIt is my daily task to login to esxi for troubleshooting or getting information, and each time I don't want to run above long one liner commands, Instead for my preference I have created below functions and copied it in powershell profiles. Profiles are startup script, whenever you open new powershell console by default it will execute those profile script and save in console memory. Run command $PROFILE to know the the profile file path. For ISE this path is different. 

 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
function Start-SSHService {  
   [CmdletBinding()]  
  #####################################   
  ## http://vcloud-lab.com
  ## Version: 1   
  ## Tested this script on successfully  
  ## 1) Powershell v3   
  ## 2) Windows 7
  ## 3) vSphere 5.5 (vcenter, esxi, powercli)
  #####################################   
  Param (  
     [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)]  
     [ValidateNotNullOrEmpty()]  
     [Alias("Name")]  
     [string]$VMHost  
   )  
   begin {}  
   Process {  
     $AllServices = Get-VMHostService -VMHost $VMHost   
     $SShService = $AllServices | Where-Object {$_.Key -eq 'TSM-SSH'}   
     if ($SShService.running -eq $false) {  
       $SShService | Start-VMHostService -confirm:$false  
     }  
     else {  
       Write-Host -BackgroundColor DarkGreen -Object "SSH service on $VMHost is already running"  
     }  
   }  
   end {}  
 }  

function Stop-SSHService {  
  #####################################    
  ## http://vcloud-lab.com   
  ## Version: 1    
  ## Tested this script on successfully   
  ## 1) Powershell v3    
  ## 2) Windows 7  
  ## 3) vSphere 5.5 (vcenter, esxi, powercli)  
  #####################################   
   [CmdletBinding()]  
   Param (  
     [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)]  
     [ValidateNotNullOrEmpty()]  
     [Alias("Name")]  
     [string]$VMHost  
   )  
   begin {}  
   Process {  
     $AllServices = Get-VMHostService -vmhost $VMHost   
     $SShService = $AllServices | Where-Object {$_.Key -eq 'TSM-SSH'}   
     if ($SShService.running -eq $true) {  
       $SShService | Stop-VMHostService -confirm:$false  
     }  
     else {  
       Write-Host -BackgroundColor darkGreen -Object "SSH service on $VMHost is already stopped"  
     }  
   }  
   end {}  
 }  

Once Profiles are loaded or opened powershell, I can simply run below oneliner smaller commands to do their jobs.
Start-SSHService -VMHost Esxi001.vcloud-lab.com               #To start service
Stop-SSHService  -VMHost Esxi001.vcloud-lab.com               #To stop service


This is third technique you can use to enable or disable SSH service as well as esxi shell. Login to DCUI (Direct console user interface), This is accessible when in front of the server physically or through medium of remote console ie Dell Rac., log in into pressing F2 button.

VMware esxi command line, dcui direct console user interface, login name f2, authentication password.png

Scroll to Troubleshooting Options, go to enable SSH hit enter to change it, It will either enable or disable according to current state.

vmware esxi, dcui, direct console user interface, Troubleshooting options, disable, Enable Esxi Shell.png

POWERCLI: VIRTUAL MACHINE STORAGE MIGRATE/SVMOTION AND DATASTORE PORT BINDING MULTIPATHING

July 20, 2017 08:45AM

Series Parts
MICROSOFT WINDOWS 2012 R2 ISCSI TARGET STORAGE SERVER FOR ESXI AND HYPERV 
POWERSHELL INSTALLING AND CONFIGURING MICROSOFT ISCSI TARGET SERVER
VMWARE ESXI CONFIGURE (VSWITCH) VMKERNEL NETWORK PORT FOR ISCSI STORAGE
POWERCLI: VMWARE ESXI CONFIGURE (VSWITCH) VMKERNEL NETWORK PORT FOR ISCSI STORAGE
VMWARE ESXI INSTALL AND CONFIGURE SOFTWARE ISCSI STORAGE ADAPTER FOR VMFS VERSION 6 DATASTORE
POWERCLI VMWARE: CONFIGURE SOFTWARE ISCSI STORAGE ADAPTER AND ADD VMFS DATASTORE
VMWARE VCENTER STORAGE MIGRATE/SVMOTION VM AND PORT BINDING MULTIPATHING TESTING
POWERCLI: VIRTUAL MACHINE STORAGE MIGRATE/SVMOTION AND DATASTORE PORT BINDING MULTIPATHING

In earlier chapter I shown how to migrate VM and test storage multipath using vSphere web client, here I will perform same task using commands using VMware Powercli. For this I have reverted all the setting. To setup powercli check my earlier article VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP

Here I have stored specific information about esxi host, virtual machine, and datastore in the there respective powershell variable. (I can view information about all inventory by running just Get-VMhost, Get-VM, Get-Datastore)
$vmhost = Get-VMhost Esxi001.vcloud-lab.com
$vm = Get-VM winxp001
$Datastore = $VMhost | Get-Datastore Disk1_Tier3

I want to know how much is the free space left and multipath policy about selected datastore Disk1_Tier3 can be fetched using next one liner commands.
$SCSILun = $VMhost | Get-ScsiLun -LunType Disk | Where-Object {$_.CanonicalName -eq $Datastore.extensiondata.info.vmfs.extent.Diskname}
$SCSILun | Select-Object @{N='Name'; E={$Datastore.Name}}, CanonicalName, CapacityGB,@{N='FreeSpaceGB'; E={$Datastore.FreeSpaceGB}}, @{N='MountPath'; E={$Datastore.extensiondata.Info.Url}}, MultipathPolicy

vmware vcenter vsphere powercli get-vmhost, get-vm, Get-datastore, Get-scsilun multipathPolicy, CanonicalName, extent, extensiondata, freespacegb, capacityGB datastore storage, vmfs example

I am changing multipath policy of selected datastore using command.
$SCSILun | Set-ScsiLun -MultipathPolicy RoundRobin

To view multipath status of vmhost datastore use next command, and they looks good and all active.
($SCSILun | Get-ScsiLunPath).ExtensionData | Select-Object Name, PathState

vmware powercli vsphere vcenter esxi, datastore storage lun, set-scsilun multipathpolicy roundrobin rr, fixed, mru, most recently used, psp, path selection policy satp, Get-ScsilunPath, pathstate, runtime, devicename, naa

To know IP address of virtual machine using powercli and virtual harddisk location use commands, If you see all the commands from top to bottom of this articles are connected.
$vm.ExtensionData.Guest.IpAddress
$vm | Get-HardDisk

vmware vcenter esxi powercli vm extensiondata guest ipaddress, get-harddisk, filename datastore location

I have gathered all the information and changed multipathing information as well, Now for final step I am storage vmotion VM with thin provisioned disk. Once my command is executed successfully, I can verify VM location with command $vm | Get-HardDisk.
$vm | Move-VM -Datastore Disk1_Tier3 -DiskStorageFormat Thin

Side by side while storage migration I started ping (Test-connection) to VM, I didn't get any ping loss, also I simulated physical adapter connected to storage failure by removing cable from esxi server. and checked the multipathing status as expected VM is intact and 2 paths are dead, No downtime on the VM.
($SCSILun | Get-ScsiLunPath).ExtensionData | Select-Object Name, PathState

vmware vsphere esxi vcenter powercli, move-vm datastore storage vmotion, diskstorageformat thin, migrate, Get-ScsiLunPath, extensiondata, Pathstate dead, active, test-connection -count ping vm, port binding

View older posts »