MacへのPowerShell/VMware PowerCLIの導入方法

#1. はじめに
VMware製品でちょっと細かいことをやろうとするとPowerCLIが欲しいところですが、Windowsがないとダメだよね・・・って思っていたあなた！実はMacでも使えるってご存知でしたか？

* PowerShellはMac/Linuxでもサポートされています。
* PowerCLIも10.0.0からはMac/Linuxでもサポートされるようになりました（参考: https://blogs.vmware.com/PowerCLI/2018/03/installing-powercli-10-0-0-macos.html)。

この記事では、以下の環境が構成可能であったことを確認しました。

* macOS High Sierra 10.13.6
* PowerShell 6.1.0
* VMware PowerCLI 11.0.0 build 10380590

#2. PowerShellのインストール方法
[ここ](https://docs.microsoft.com/en-us/powershell/scripting/setup/installing-powershell-core-on-macos?view=powershell-6)の手順にしたがって、PowerShellをコマンド一発でインストールできます。

```
$ brew cask install powershell
==> Tapping caskroom/cask
Cloning into '/usr/local/Homebrew/Library/Taps/caskroom/homebrew-cask'...
remote: Enumerating objects: 4136, done.
remote: Counting objects: 100% (4136/4136), done.
remote: Compressing objects: 100% (4127/4127), done.
remote: Total 4136 (delta 29), reused 462 (delta 6), pack-reused 0
Receiving objects: 100% (4136/4136), 1.31 MiB | 202.00 KiB/s, done.
Resolving deltas: 100% (29/29), done.
Checking out files: 100% (4121/4121), done.
Tapped 0 formulae (4,145 files, 4.2MB)
==> Creating Caskroom at /usr/local/Caskroom
==> We'll set permissions properly so we won't need sudo in the future
Password:
==> Satisfying dependencies
All Formula dependencies satisfied.
==> Downloading https://github.com/PowerShell/PowerShell/releases/download/v6.1.0/powershell-6.1.0-osx-x64.pkg
######################################################################## 100.0%
==> Verifying checksum for Cask powershell
==> Installing Cask powershell
==> Running installer for powershell; your password may be necessary.
==> Package installers may write to any location; options such as --appdir are ignored.
Password:
==> installer: Package name is PowerShell - 6.1.0
==> installer: Installing at base path /
==> installer: The install was successful.
🍺  powershell was successfully installed!
````

バージョンを確認して見ます。

```
$ pwsh -version
PowerShell 6.1.0

$ pwsh
PowerShell 6.1.0
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

PS /Users/yasuda> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.1.0
PSEdition                      Core
GitCommitId                    6.1.0
OS                             Darwin 17.7.0 Darwin Kernel Version 17.7.0: Thu Jun 21 22:53:14 PDT 2018; root:xnu-4570.71.2~1/RELEASE_X86_64
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

```

#3. PowerCLIのインストール方法

こちらもコマンド一発で導入可能です。。

```
PS /Users/yasuda> Install-Module -Name VMware.PowerCLI -Scope CurrentUser

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running
the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): Y
```

確認

```
PS /Users/yasuda> Get-PowerCLIVersion

PowerCLI Version
----------------
   VMware PowerCLI 11.0.0 build 10380590
---------------
Component Versions
---------------
   VMware Cis Core PowerCLI Component PowerCLI Component 11.0 build 10335701
   VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 11.0 build 10336080


PS /Users/yasuda> Get-Module -Name VMware.* -ListAvailable                                                                                                                                                                                                                                                                                                                                                                           Directory: /Users/yasuda/.local/share/powershell/Modules
ModuleType Version    Name                                PSEdition ExportedCommands
---------- -------    ----                                --------- ----------------
Script     6.7.0.8... VMware.DeployAutomation             Desk      {Add-DeployRule, Add-ProxyServer, Add-ScriptBundle, Copy-DeployRule...
Script     6.7.0.8... VMware.ImageBuilder                 Desk      {Add-EsxSoftwareDepot, Add-EsxSoftwarePackage, Compare-EsxImageProf...
Manifest   11.0.0.... VMware.PowerCLI                     Desk
Script     6.7.0.1... VMware.Vim                          Desk
Script     11.0.0.... VMware.VimAutomation.Cis.Core       Desk      {Connect-CisServer, Disconnect-CisServer, Get-CisService}
Script     11.0.0.... VMware.VimAutomation.Cloud          Desk      {Add-CIDatastore, Connect-CIServer, Disconnect-CIServer, Get-Catalo...
Script     11.0.0.... VMware.VimAutomation.Common         Desk
Script     11.0.0.... VMware.VimAutomation.Core           Desk      {Add-PassthroughDevice, Add-VirtualSwitchPhysicalNetworkAdapter, Ad...
Script     7.6.0.1... VMware.VimAutomation.HorizonView    Desk      {Connect-HVServer, Disconnect-HVServer}
Script     10.0.0.... VMware.VimAutomation.License        Desk      Get-LicenseDataManager
Script     11.0.0.... VMware.VimAutomation.Nsxt           Desk      {Connect-NsxtServer, Disconnect-NsxtServer, Get-NsxtService}
Script     11.0.0.... VMware.VimAutomation.Sdk            Desk
Script     11.0.0.... VMware.VimAutomation.Security       Desk      {Get-SecurityInfo, Get-VTpm, Get-VTpmCertificate, Get-VTpmCSR...}
Script     10.0.0.... VMware.VimAutomation.Srm            Desk      {Connect-SrmServer, Disconnect-SrmServer}
Script     11.0.0.... VMware.VimAutomation.Storage        Desk      {Add-KeyManagementServer, Copy-VDisk, Export-SpbmStoragePolicy, Get...
Script     1.3.0.0    VMware.VimAutomation.StorageUtility Desk      Update-VmfsDatastore
Script     11.0.0.... VMware.VimAutomation.Vds            Desk      {Add-VDSwitchPhysicalNetworkAdapter, Add-VDSwitchVMHost, Export-VDP...
Script     11.0.0.... VMware.VimAutomation.Vmc            Desk      {Connect-Vmc, Disconnect-Vmc, Get-VmcSddcNetworkService, Get-VmcSer...
Script     10.0.0.... VMware.VimAutomation.vROps          Desk      {Connect-OMServer, Disconnect-OMServer, Get-OMAlert, Get-OMAlertDef...
Script     6.5.1.7... VMware.VumAutomation                Desk      {Add-EntityBaseline, Copy-Patch, Get-Baseline, Get-Compliance...}

```

#4. vCenterへの接続

vCenterに接続する際には`Connect-VIServer`を利用します。
ユーザー名やパスワードに特殊文字を含んでいる場合は`'`で囲みます。

```txt:失敗ケース
PS /Users/yasuda> Connect-VIServer -Server 10.132.87.194 -Username 'Administrator@vsphere.local' -Password '*********'
Connect-VIServer : 2018/10/13 19:36:11	Connect-VIServer		The SSL connection could not be established, see inner exception.
At line:1 char:1
+ Connect-VIServer -Server 10.132.87.194 -Username Administrator@vspher ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Connect-VIServer], ViError
+ FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_Reconnect_SoapException,VMware.VimAutomation.ViCore.Cmdlets.Commands.ConnectVIServer

```

、、、失敗しますね。SSL Connectionが張れないというエラーが出ています。もしかして、自己証明書なのが原因なのかと思い、`help Connect-VIServer"を見てみると、以下のような記載がありました。ドンピシャそうですね。

>When you attempt to connect to a server, the server checks for valid certificates. To set the default behavior of VMware PowerCLI when no valid certificates are recognized, use the InvalidCertificateAction parameter of the Set-PowerCLIConfiguration cmdlet. For more information about invalid certificates, run 'Get-Help about_invalid_certificates'.

というので、-Forceオプションを付けて実行します。

```txt:成功ケース1(Forceオプションあり）
PS /Users/yasuda> Connect-VIServer -Server 10.132.87.194 -Username 'Administrator@vsphere.local' -Password 'xxxxxxx' -Force
Specify Credential
Please specify server credential
User: Administrator@vsphere.local
Password for user Administrator@vsphere.local: ********


Name                           Port  User
----                           ----  ----
10.132.87.194                  443   VSPHERE.LOCAL\Administrator

```

もしくは、設定として`Set-PowerCLIConfiguration -InvalidCertificateAction Ignore`を実行しておけば、Forceオプションは不要になります。

```txt:成功ケース2(Forceオプションなし）
PS /Users/yasuda> Set-PowerCLIConfiguration -InvalidCertificateAction Ignore

Perform operation?
Performing operation 'Update PowerCLI configuration.'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Scope    ProxyPolicy     DefaultVIServerMode InvalidCertificateAction  DisplayDeprecationWarnings WebOperationTimeout
                                                                                                  Seconds
-----    -----------     ------------------- ------------------------  -------------------------- -------------------
Session  UseSystemProxy  Multiple            Ignore                    True                       300
User                     Multiple            Ignore
AllUsers

PS /Users/yasuda> Connect-VIServer -Server 10.132.87.194 -Username 'Administrator@vsphere.local' -Password 'xxxxxxx'
Specify Credential
Please specify server credential
User: Administrator@vsphere.local
Password for user Administrator@vsphere.local: ********


Name                           Port  User
----                           ----  ----
10.132.87.194                  443   VSPHERE.LOCAL\Administrator


```

#5. おまけ
何度から操作していると、VMware Customer Experience Improvement Programに参加しないか？というWarningが出てくるようになります。

* 参加したい時：`Set-PowerCLIConfiguration -Scope User -ParticipateInCEIP $true`
* 参加しない時：`Set-PowerCLIConfiguration -Scope User -ParticipateInCEIP $false`

を実行しておくと、警告がでなくなります。