285 Commits

Author SHA1 Message Date
lyuboasenov
062749868d Add PAIF-N automation example (#629)
* Adding PAIF-N demo scripts

* Removing Confidential from headers

* Addressing review comments

---------

Co-authored-by: Lyuboslav Asenov <lasenov@vmware.com>
2024-03-28 15:50:45 +02:00
kamennikolov
9055bf72f3 Merge pull request #625 from desrosim232/master
Patch for Set-HVApplicationIcon
2023-11-24 15:58:36 +02:00
desrosim232
e02efdec9e Merge pull request #2 from desrosim232/patch-Set-HVApplicationIcon
Patch set hv application icon
2023-11-24 07:18:00 -05:00
desrosim232
346141e69e Merge branch 'master' into patch-Set-HVApplicationIcon 2023-11-24 07:17:48 -05:00
desrosim232
3c0a12f72a Update VMware.HV.Helper.psm1
Remove unnecessary Write-Host in Set-HVApplicationIvon
2023-11-24 07:15:55 -05:00
desrosim232
50ac249ec1 Merge branch 'vmware:master' into master 2023-11-23 15:58:52 -05:00
desrosim232
3634649afc Merge branch 'vmware:master' into patch-Set-HVApplicationIcon 2023-11-23 15:58:38 -05:00
desrosim232
9e4f03aebe Merge pull request #1 from desrosim232/patch-Set-HVApplicationIcon
Set-HVApplicationIcon Patch
2023-11-23 15:54:30 -05:00
desrosim232
0b3e4c9ea2 Set-HVApplicationIcon Patch
Patching a conditional issue with Set-HVApplicationIcon

Signed-off-by: Mathieu Desrosiers desrosim@gmail.com
2023-11-23 15:52:49 -05:00
Kamen Nikolov
ce06c5372b Added git sync script and fixed an issue in the
remove old snapshots script in the PowerActions folder
2023-11-21 16:55:06 +02:00
kamennikolov
20871aeffa Merge pull request #620 from Geo-Ron/instant-clone-accept-vtpm-machines
VMWare.HV.Helper - New-HVPool: implemented addVirtualTPM for instant clones
2023-09-07 12:09:52 +03:00
kamennikolov
524b0aac2f Merge pull request #619 from Geo-Ron/new-hvpool-gpu-changes
VMWare.HV.Helper - New-HVPool: implemented vGPU profile for instant clones
2023-09-07 12:08:54 +03:00
GeoRon
f748f2591e enabled addVTPM for instant clones
Signed-off-by: GeoRon <ronnie.peeters@gmail.com>
2023-09-06 16:07:06 +02:00
GeoRon
cd502a516b removed duplicate line
Signed-off-by: GeoRon <ronnie.peeters@gmail.com>
2023-09-06 15:41:49 +02:00
GeoRon
d43b7ec88b enabled vGPU profile for instant clones
Signed-off-by: GeoRon <ronnie.peeters@gmail.com>
2023-09-06 15:39:36 +02:00
Kamen Nikolov
d70d246e34 Added Power Actions sample actions
Signed-off-by: Kamen Nikolov <knikolov@vmware.com>
2023-07-31 16:23:56 +03:00
kamennikolov
d41905e00f Merge pull request #613 from desrosim232/Start-HVFarm-additions
Start hv farm additions
2023-06-27 16:57:28 +03:00
desrosim232
2be8d05707 Update VMware.HV.Helper.psm1
Encoding correction

Signed-off-by: Mathieu Desrosiers desrosim@gmail.com
2023-06-27 08:08:53 -04:00
desrosim232
356b3c4d68 Update VMware.HV.Helper.psm1
Adding new parameters for Start-HVFarm function to configure the ComputeProfile of the VMs underlying a farm:

NumCPU
Ram
CoresPerSocket

Signed-off-by: Mathieu Desrosiers desrosim@gmail.com
2023-06-27 08:07:14 -04:00
kamennikolov
52d38656ed Merge pull request #609 from desrosim232/New-HVFarm-additions
Update VMware.HV.Helper.psm1
2023-04-24 18:43:43 +03:00
desrosim232
1480fdec06 Adding infos to Ram parameter in New-HVFarm
Adding units info in the Ram parameter in New-HVFarm

Signed-off-by: Mathieu Desrosiers desrosim@gmail.com
2023-04-24 11:30:30 -04:00
desrosim232
ddc96d276e Update VMware.HV.Helper.psm1
Adding new parameters for New-HVFarm function to configure the ComputeProfile of the VMs underlying a farm:
- NumCPU
- Ram
- CoresPerSocket 

Adding the use of the parameter ReusePreExistingAccounts for INSTANT_CLONE farm

Signed-off-by: Mathieu Desrosiers <desrosim@gmail.com>
2023-04-21 10:31:32 -04:00
kamennikolov
ee6e800726 Merge pull request #605 from abidlen/master
Update README.md
2023-03-06 16:25:46 +02:00
Andy B
101b92e28d Update README.md
Fixed typo in link to Filing Issues section
Signed-off-by: Andy Bidlen <abidlen@gmail.com>
2023-03-02 20:06:07 -05:00
Nikola Klinkachev
fdebb39901 Building the SSOAdmin module with the latest changes in src and publishing the dlls. 2023-02-17 12:11:04 +02:00
kamennikolov
74f450fb75 Merge pull request #604 from Jiancao164/caojian/fixCertificateBug
Fix the bug of not creating certificates in linux
2023-02-16 09:37:35 +02:00
Jian Cao
25700a9ac2 Fix the bug of not creating certificates in linux
Signed-off-by: Jian Cao <caojian@microsoft.com>
2023-02-15 13:57:30 -08:00
Kamen Nikolov
414b6ccb62 Added VMware.VISecret module for managing secrets
Signed-off-by: Kamen Nikolov <knikolov@vmware.com>
2023-02-13 17:11:16 +02:00
kamennikolov
3c6190a2be Merge pull request #598 from bwuch/master
Updating module to resolve duplicate object bug
2022-12-21 10:47:56 +02:00
Brian Wuchner
b68077e4c3 Updating module to resolve duplicate object bug
When passing in objects to Get-SkylineAffectedObject, it was possible for duplicate queries to be invoked for the same product.  This commit fixes that by moving some of the string manipulation inside the correct loop for this function.  Additionally, the text replace lines were consolidated to reduce some confusion with variable assignment that led to this bug in the first place.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-12-20 08:52:34 -05:00
kamennikolov
c67b7d47a9 Merge pull request #592 from vmware/adatanasov/wcf-framework-dependency
Updated the SsoAdmin projects to reference WCF from the framework instead of a package.
2022-10-04 17:59:21 +03:00
Atanas Atanasov
9f468a5cc2 Updated the SsoAdmin projects to reference WCF from the framework instead of a package.
Signed-off-by: Atanas Atanasov <adatanasov@vmware.com>
2022-10-04 17:42:22 +03:00
kamennikolov
c6f51e944d Merge pull request #587 from Geo-Ron/issue-586
HV.Helper: Issue 586 - reEnable vTPM if previously defined on desktop pool
2022-08-17 14:45:21 +03:00
Ron Peeters
e9f5fa2c52 restore vTPM if previously defined
Signed-off-by: Ron Peeters <ronnie.peeters@gmail.com>
2022-08-17 13:07:41 +02:00
Ron Peeters
366aef13c2 using get-hvpool to retrieve existing settings.
Signed-off-by: Ron Peeters <r.peeters@vdl.nl>
2022-08-15 17:34:35 +02:00
kamennikolov
97799789da Merge pull request #584 from romqatt/master
Added Restart-HVMachine function
2022-08-09 13:56:45 +03:00
Гончаренко Роман Андреевич
9b62032a26 Added Restart-HVMachine function
Signed-off-by: Гончаренко Роман Андреевич <goncharenkora@nspk.ru>
2022-08-01 12:03:30 +03:00
kamennikolov
c74ae8cd7d Merge pull request #552 from DisasteR/openldap-identity-source
allow OpenLdap identity source creation
2022-06-29 13:37:11 +03:00
Benjamin SAIZ
dbd5f7e907 allow OpenLdap identity source creation
Signed-off-by: Benjamin Saiz <benj.saiz@gmail.com>
2022-06-29 11:12:31 +02:00
kamennikolov
91ab53cdf7 Merge pull request #550 from IvyPW/master
Add vCenter and collaboration support for manul pools
2022-05-31 14:55:01 +03:00
kamennikolov
51d21ca815 Merge pull request #546 from bwuch/bwuch-SkylineInsights
Timeout upates and bugfixes.
2022-05-26 09:37:56 +03:00
Brian Wuchner
e0e2d1bbdc Update VMware.Skyline.InsightsApi.psm1
I accidentally committed a version with a query problem in Get-SkylineAffectedObject.  This version does not contain that search problem.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-05-13 16:43:07 -04:00
Brian Wuchner
80622414d6 Update VMware.Skyline.InsightsApi.psm1
Apologies for the delay on getting this commit to address the final open item in the PR.  This change removes the "hit a 429 and retry" logic as it was not effective.  Replaced it with a global variable that stores the time of the last query.  If a query has happened within the last 501ms we wait before sending.  I've issued a few thousand queries with this logic added and have not yet hit the 429 error.  The logic to find and report on 429's in a more friendly way still exists, just in case.

Additionally I've implemented a counter to track number of queries that is reset by Connect-SkylineInsights, to track how many queries are executed.  This was more of a debugging tool, but felt the overhead was low enough to leave it in for future troubleshooting.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-05-13 11:14:46 -04:00
Brian Wuchner
b2e0decb68 Update VMware.Skyline.InsightsApi.psm1
Fixing minor issue uncovered by testing where only a product (vCenter Name) was passed to Get-SkylineFinding function.  When passed by pipeline, the product was applied to each pipeline input.  Making a change to require passing through pipeline by property name only.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-03-20 20:50:13 -04:00
Brian Wuchner
d85c6096a3 Update VMware.Skyline.InsightsApi.psm1
Addressing issues in PR 546.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-03-18 23:04:05 -04:00
Ivy Huang
6188524f90 support enableCollaboration parameter for new-hvpool
Function New-HVPool
1. support the setup with json object DesktopSettings.displayProtocolSettings.enableCollaboration
2. support the parameter enableCollaboration
2022-03-18 14:58:44 +08:00
Ivy Huang
d5f851339b take $jsonObject.ManualDesktopSpec.VirtualCenter
ManualDesktopSpec.VirtualCenter of json file was not taken care of. This could cause new-hvpool fail when creating with json file and there are multiple vcenters added to broker.
2022-03-17 16:11:21 +08:00
dmilov
829307318f Implement Set Default Identity Source and Get Default Identity Source (#545)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2022-02-25 11:26:10 +02:00
kamennikolov
9a302e0473 Merge pull request #543 from bwuch/master
Adding 'Get-SscFile','Set-SscFile','New-SscFile','Remove-SscFile','Get-SscLicense','Get-SscvRALicense','Get-SscMinionKey','Set-SscMinionKey' and 'Remove-SscMinionKey' cmdlets.
2022-02-24 14:54:24 +02:00
Brian Wuchner
02fd75b6a1 Updates to SaltStackConfig module
Updates to function names and parameters to ensure consistency as discussed in PR 543.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-23 15:32:31 -05:00
Brian Wuchner
3cd0fe0ca5 Update VMware.Skyline.InsightsApi.psm1
Moving the ParameterSetName checks to the process block instead of the begin block.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-23 15:18:04 -05:00
Brian Wuchner
bc6d2e8a5f Initial commit of VMware.Skyline.InsightsApi module
Initial commit of VMware.SkylineInsightsApi module, containing the following functions:
Connect-SkylineInsights, Disconnect-SkylineInsights, Invoke-SkylineInsightsApi, Get-SkylineFinding, Get-SkylineAffectedObject, Format-SkylineResult, Start-SkylineInsightsApiExplorer

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-21 12:21:45 -05:00
Brian Wuchner
b9cdded704 Update SaltStackConfig.psm1
Updates per conversation on PR 543.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-18 20:21:29 -05:00
Brian Wuchner
d23db41cfb Adding new functions to SaltStackConfig module
Adding support for new functions to SaltStackConfig module.  WIth this change items in the SSC Fileserver can get retrieved, modified, created, and removed, license details can be retrieved, and minion keys can be retrieved, modified, and removed.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-15 20:46:29 -05:00
kamennikolov
9b4ce6cf65 Fixing issues in VAMI and VMware.WorkloadManagement modules
Fixing issues in VAMI and VMware.WorkloadManagement modules
2022-02-14 16:09:44 +02:00
Brian Wuchner
38a6dea1d9 Update VAMI.psm1
Updates per conversation in PR #542.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-12 11:47:10 -05:00
Brian Wuchner
77b9db2f4e Update VMware.WorkloadManagement.psm1
Fixes #375 Adds the requested typecast to string for the MgmtNetworkNTP parameter.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-09 21:41:22 -05:00
Brian Wuchner
9964e16338 Update VAMI.psm1
Fixes #536.  The fullname vs. full_name options appear to have changed between the techpreview and GA of the API and have been accounted for in this update.  Additionally, after making a change so that the error message was present, the second issue showed to be type casting related.  For example, the input parameter for PasswordExpires is a switch, but the API was expecting a string.  This has been resolved with this commit.

When testing New-VAMIUser, I wanted to confirm success using Get-VAMIUser, but found a new bug where passing in a specific user through the Name property would fail with a vSphere 7 test environment.  This commit also includes a fix for that issue.

Changes to New-VAMIUser and Get-VAMIUser have been tested against 6.5, 6.7, and 7.0 environments and should function as expected.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-09 21:17:39 -05:00
kamennikolov
7a43b1096b Fixing instances of sort with sort-object
Fixing instances of sort with sort-object
2022-02-04 12:24:59 +02:00
Brian Wuchner
248a86f0a2 Fixing instances of sort with sort-object
Fixes #535 - module using sort instead of sort-object causing unexpected behavior on powershell core/Linux.
Instead of only addressing the issue at hand, I looked for other instances of sort being used instead of sort-object for other modules within this repo and corrected those as well.  I think I got most of them, but feel free to raise another issue if you find another.  If the sort was in an example/help statement, or was inside the logic/process of the function, I replaced sort with sort-object.  In the one case where the sort was only applied to the output I removed the statement -- this way the function user can add the sort in their script and not have to sort output twice.  I changed a couple  select/where with select-object/where-object along the way as well just as I saw them.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-02-03 20:11:02 -05:00
kamennikolov
9546f492e1 Merge pull request #526 from bwuch/master
Introduced SkipCertificateCheck and SslProtocol parameters to Connect-SSCServer
2022-01-26 15:51:37 +02:00
Brian Wuchner
de17729494 Update SaltStackConfig.psm1
Changing SslProtocol parameter from static validateset list to proper type.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-01-25 09:59:05 -05:00
kamennikolov
238adac0bd Merge pull request #529 from abidlen/master
Commit signing instructions added to the readme.
2022-01-25 11:41:37 +02:00
Andy Bidlen
054910c219 Merge branch 'vmware:master' into master
Signed-off-by: Andy B <abidlen@gmail.com>
2022-01-24 19:50:00 -05:00
Andy B
d8857e63db Update README.md
Updated Pull Request Requirements section to include examples and added a dco-required section to suggest how to respond to that error.

Signed-off-by: Andy Bidlen <abidlen@gmail.com>
2022-01-24 18:10:22 -05:00
Andy Bidlen
680ef82866 Fixes #124 - Contributor License Agreement issue.
Added information about the required DCO to submit a Pull Request and comply with the CLA.
Signed-off-by: Andy Bidlen <abidlen@gmail.com>
2022-01-24 15:30:25 -05:00
Brian Wuchner
c46d3522bd Updates to SSC Module -- provide better SSL support for Connect-SscServer
Moving the code to set SslProtocol to a separate parameter instead of hiding it under SkipCertificateCheck.
Updating Module Version to denote this minor change.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-01-24 14:48:21 -05:00
kamennikolov
fcf5ab8828 Merge pull request #525 from cadegenn/master
New-HVPool -Spec /path/to/file honor minNumberOfMachine attribute
2022-01-24 13:42:02 +02:00
Charles-Antoine Degennes
5648fe1bec [VMware.HV.Helper.psm1] New-HVPool: check for provisioningTime value
Signed-off-by: Charles-Antoine Degennes <cadegenn@univ-lr.fr>
2022-01-24 08:50:39 +01:00
Charles-Antoine Degennes
e83cfa1b0b [VMware.HV.Helper.psm1] fix issue #524
Signed-off-by: Charles-Antoine Degennes <cadegenn@univ-lr.fr>
2022-01-24 08:50:39 +01:00
Brian Wuchner
4e9093d0e5 Update SaltStackConfig.psm1
In the previous version of Connect-SscServer, we assumed that the SaltStack Config master node has an SSL certificate from an authority trusted by the powershell client and that the client supports the same TLS version as the server.  However, this may not be the case.  Therefore this commit adds support for a switch parameter named SkipCertificateCheck which ignores untrusted certificates and sets support for various TLS versions.  All SSC servers I've tested with have only supported Tls12, but lower levels were added to this function for backwards compatibility.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-01-21 15:11:17 -05:00
kamennikolov
db96e946f3 Merge pull request #512 from Ichigo49/patch-1
Modification on Get-VAMINetwork
remove write-host for hostname and DNS Servers, adding them in the $interfaceResult PSCustomObject
2022-01-14 11:36:56 +02:00
kamennikolov
6b82f226f7 Merge pull request #522 from imtrinity94/master
Added Rebuild-HVMachine function
2022-01-14 11:31:46 +02:00
Mayank Goyal
b5915de07a Merge branch 'master' of https://github.com/imtrinity94/PowerCLI-Example-Scripts
Signed-off-by: Mayank Goyal <imtrinity94@gmail.com>
2022-01-14 14:02:00 +05:30
Mayank Goyal
99674644d8 Update VMware.HV.Helper.psm1
Signed-off-by: Mayank Goyal <imtrinity94@gmail.com>
2022-01-14 14:01:18 +05:30
Mayank Goyal
8cfc5e4fa6 Update VMware.HV.Helper.psm1 2022-01-14 13:50:35 +05:30
kamennikolov
b1c98c0fa2 Merge pull request #521 from bwuch/master
SqlTimeout parameter added to Get-HVEvent
2022-01-13 17:20:55 +02:00
Brian Wuchner
5b291a5ac0 Update VMware.HV.Helper.psm1
Fixes #364 - Get-HVEvent timeout issue
Changes to line 877-879 adds help for a new SqlTimeout parameter added to Get-HVEvent
Changes to line 931-934 add support for the new SqlTimeout parameter with a default value of 30 seconds.
Changes to line 1064 implements the timeout parameter created above when executing the query.

The change to line 1031 resolves an unrelated issue where I was seeing an extra '1' in the output from Get-HVEvent.  Adding the `Out-Null` statement is similar to another example in this same function which already existed on line 1065.  Adding the `Out-Null` statement did resolve the extra '1' displayed in the output.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-01-13 07:59:41 -05:00
kamennikolov
0b5e119776 Merge pull request #520 from bwuch/master
Handling SFTP backup issue on VC 7.0
2022-01-12 09:41:22 +02:00
Brian Wuchner
33e41a756e Update Backup-VCSA.psm1
Fixes #468.  In this issue, it is noted that starting with vSphere 7 you need to use SFTP instead of SCP when calling Backup-VCSAToFile.  In this commit we are adding SFTP to the Validate Set for the Location Type.  Additionally, we add some logic to toggle between SFTP or SCP depending on appliance version and provide warning text that an adjustment was made.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2022-01-11 20:25:22 -05:00
kamennikolov
379ff32624 Merge pull request #517 from bwuch/master
Added a -Credential parameter to the Connect cmdlet.
2022-01-04 13:57:31 +02:00
Brian Wuchner
05d2016ff0 Update SaltStackConfig.psm1
Minor update to add examples of the new functionality to the help in the function.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-12-23 19:21:59 -05:00
Brian Wuchner
e293d7e365 Update SaltStackConfig.psm1
Improve Connect-SscServer to accept credentials instead of just plaintext username/password values.

We will make the PlainText parameter set items mandatory, so if you use this parameter set both values need to be provided.
However, if you don't specify any credentials at all as arguments, we will default to the optional Credential parameter set.  When the credential parameter set is used but the credential value is null, we will prompt for credentials using Get-Credential.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-12-23 14:24:17 -05:00
dmilov
1d96b6a340 Implement update authentication credential for LDAP identity sources (#516)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-12-22 12:34:59 +02:00
Ichigo49
7eb5651feb Update VAMI.psm1
Signed-off-by: Mathieu ALLEGRET <mathieu.allegret@pm.me>
2021-12-08 12:32:12 +01:00
Ichigo49
cc2c740738 Update VAMI.psm1
Modification on Get-VAMINetwork
remove write-host for hostnmae and DNS Servers, adding them in the $interfaceResult PSCustomObject
2021-12-08 12:27:50 +01:00
kamennikolov
13d0ef4b86 Merge pull request #502 from bwuch/master
vRealize Automation SaltStack Config API wrapper
2021-12-07 11:04:48 +02:00
Brian Wuchner
3b7653da71 Minor changes to Connect-SscServer output properties.
Changing returned columns from Connect-SscServer to be more in line with other PowerCLI cmdlets.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-12-06 15:49:33 -05:00
Brian Wuchner
3afa7eed5d Resolving comments from PR in SaltStackConfig module
Promoting properties on the connection object as requested in PR comment.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-12-03 12:53:37 -05:00
Brian Wuchner
96205f85b2 Updating SaltStackConfig module
Updated functions based on comments in PR502.  Updated manifest to include Get-SscActivity (previously Get-SscCommand) and reference to new Format.ps1xml, which contains custom formatting for the Connect-SscServer output.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-12-02 14:39:23 -05:00
Brian Wuchner
ded1ce575d Resolving some of the items from PR comments.
Many thanks to @kamennikolov for his time to review and provide such helpful comments!  This commit address many of the comments from PR 502 in the module psm1 file.  Also updated module manifest to rev version number, changed FunctionsToExport to address Get-SscMinion --> Get-SscMinionCache name change.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-12-01 11:58:39 -05:00
Brian Wuchner
95abde3a5a Update SaltStackConfig.psm1
Fixing help information in Connect-SscServer to be more descriptive.
Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-11-29 06:52:50 -05:00
Brian Wuchner
ba63d1643a Update SaltStackConfig.psd1
Increasing version number in manifest.
Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-11-29 06:48:29 -05:00
Brian Wuchner
38998cee05 vRealize Automation SaltStack Config API wrapper
Initial commit of SaltStackConfig module, a series of wrapper functions for the vRealize Automation SaltStack Config API.

Signed-off-by: Brian Wuchner <brian.wuchner@gmail.com>
2021-11-28 21:29:59 -05:00
Matt Frey
ccdddba4e7 Reversing 9d9ebc504b (#492)
The change made in 9d9ebc504b breaks ImagePush operations for Instant Clone pools. See the API documentation for reference.

The schema for `DesktopPushImageSpec` is as follows:

* DesktopPushImageSpec
  * Settings
    * StartTime

Signed-off-by: Matt Frey <mfrey@vmware.com>
2021-11-25 14:35:12 +02:00
Matt Frey
2ec8f92823 Address Issue 496 (#497)
Addressing Issue 496 to resolve the unintentional false condition when `-Value` is set to `$false` on `Set-HVGlobalSettings

Signed-off-by: Matt Frey <mfrey@vmware.com>
2021-11-25 14:34:40 +02:00
dmilov
8830d3ec2d Bug fixes (#499)
* Add Certificates to External Identity Source

Signed-off-by: Dimitar Milov <dmilov@vmware.com>

* Add Credential parameter to Connect-SsoAdminServer

Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-11-25 14:18:53 +02:00
ricoroodenburg
9d82c04d72 Update VMware.HV.Helper.psm1 (#489)
Fix for error Get-HVBaseImageVM - Cannot find an overload for "BaseImageVM_List" and the argument count: "1"
2021-10-01 14:31:12 +03:00
dmilov
294071df19 Remove VC IP 2021-09-16 14:53:21 +03:00
dmilov
a7cd4db523 PowerCLI 12.4 vSphere APIs through PowerCLI demo script (#486)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-09-16 14:48:11 +03:00
dmilov
5025ab9047 Add PowerCLI Logo (#485)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-09-16 13:14:33 +03:00
dmilov
173c08216e Increase the default web operation timeout (#484)
* Increase the default web operation timeout

Signed-off-by: Dimitar Milov <dmilov@vmware.com>

* Increament module version

Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-09-07 11:24:51 +03:00
Dimitar Milov
1710f7ccbd Add new PowerCLI icon in the PowerCLI Examples Repo
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-09-02 17:40:04 +03:00
Nam Tran
dbb570e009 Update VMware.HV.Helper.psm1 (#469) 2021-08-23 14:43:37 +03:00
Dan Acristinii
3c961963f1 Fixed no snapshot found error mistype (#481)
Signed-off-by: Dan Acristinii <dan.acristinii@roche.com>
2021-08-23 14:38:27 +03:00
dmilov
a62b0006b8 Update IconUri (#476)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-07-28 17:19:55 +03:00
dmilov
5b9265d0ad Update link to powercli log icon (#475)
* Implement feature issue #472

Signed-off-by: Dimitar Milov <dmilov@vmware.com>

* Fix modules manifest to point to powercli log icon

Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-07-28 16:28:41 +03:00
dmilov
2b62d20d13 Implement feature issue #472 (#474)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-07-28 16:23:54 +03:00
dmilov
0cbd85190c Implement Enable/Disable Person Uer account in the Set-SsoPersonUser cmdlet (#471)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-07-23 15:11:42 +03:00
Jimit G
246a887e84 Added VMsStatusReport file (#465)
* Added VMsStatusReport file

* fixed typo and added space before and after |

* Modified script to fuction with VIServerFilePath and OutPath parameters

* Refined help section

* Changed name from VMsStatusReport.ps1 to Get-VMSnapshotReport.ps1

* help documentation refined

* commit

* fomating corrections using prettier extension

* cmdletbinding correction

* added example and fixed parameter issue
2021-06-28 07:35:24 +03:00
Rob Nelson
3077daaeb5 DesktopRecomposeSpec does not have a Settings attribute (#464)
Similar adjustment as in #452 to another instance.
2021-06-21 11:02:04 +03:00
dmilov
1dd718eb3a Fix issue #460 adding PasswordExpirationRemainingDays property to the PersonUser object (#463)
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-06-07 10:42:18 +03:00
dmilov
fb641c8a1c License PowerCLI-Examples-Scripts repository under BSD-2 Clause (#462)
As part of the VMware open source program, we have to update this repository with the correct license and copyright information.
We add the BSD-2 Clause License for this repository.
We mark all source code provided by VMware with the Copyright notice under BSD-2 Clause license.

* Update repository license to BSD 2-Clause License

* Update Copyright
2021-06-07 09:58:47 +03:00
dmilov
db68f439a3 Merge pull request #461 from jatinpurohit92/topic/vlcm-cmdlets
adding vLCM cmdlets
2021-06-07 09:09:01 +03:00
Jatin purohit
32749fbd16 adding vLCM cmdlets 2021-06-04 08:44:12 -07:00
dmilov
af57eab8b8 Merge pull request #457 from j33tu/copy-ipsetv2t
function to move ipsets from nsx v to Nsx t
2021-06-02 09:15:46 +03:00
Joanna singh
21f4e8734c function to move ipsets from nsx v to Nsx t 2021-06-01 21:50:07 +05:30
dmilov
8de76d1327 Merge pull request #453 from MallocArray/master
Resolve issues with Backup-VCSA
2021-05-28 09:22:13 +03:00
dmilov
53ab16a241 Merge pull request #452 from rnelson0/starttimebug
Recompose with starttime generates error
2021-05-28 09:22:00 +03:00
dmilov
0c6b0b0a95 Merge pull request #454 from dmilov/topic/ssoadmin-support-groups
Group management cmdlet in SsoAdmin module
2021-05-26 11:22:38 +03:00
Dimitar Milov
7b8d982dd3 Implement Find Group By Group
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-05-26 11:11:13 +03:00
Dimitar Milov
5d221fdb15 Implement Add and Remove principal to/from SsoGroup
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-05-26 10:54:15 +03:00
Dimitar Milov
f0cf0f58bd Implement Set-SsoGroup cmdlet
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-05-26 09:44:52 +03:00
Dimitar Milov
04b0807ed5 Implement New and Remove SsoGroup cmdlets.
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-05-25 19:11:15 +03:00
Dimitar Milov
09fad317e1 Refactor advanced functions moving them to dedicated .ps1 file
Signed-off-by: Dimitar Milov <dmilov@vmware.com>
2021-05-25 15:47:52 +03:00
Joshua Post
5a45f4ec85 BackupDays must be all caps for API call to work
When days are in mixed or lower case, the schedule summary page shows
the correct day, but editing the schedule shows a blank and scheduled
executions do not happen.  API reference shows it in all caps which does work as expected.
Attempted to use .ToUpper() on line 319 but it resulted in an error
Changing validation to require it in all caps
2021-05-24 14:50:28 -05:00
Joshua Post
5df4070717 Encrypt Backup is option in VAMI
Change Mandatory to false so it can be optional as shown in the VAMI GUI
2021-05-24 14:48:19 -05:00
Joshua Post
9a02c0e1fa Correct casting of int
Interger is not a valid type, at least in Powershell 5.1
2021-05-24 14:47:07 -05:00
Joshua Post
e872cc50d1 If 'common' is not specified, it is not included
If 'common' is not included, it is unchecked when viewing in the GUI
2021-05-24 14:45:14 -05:00
Joshua Post
9519635847 Add support for SMB location 2021-05-24 14:43:39 -05:00
Joshua Post
83447772b6 Replace invalid character with ' 2021-05-24 14:41:56 -05:00
Rob Nelson
9d9ebc504b DesktopRecomposeSpec does not have a Settings attribute 2021-05-19 09:46:54 -04:00
Rob Nelson
88f15d9fe3 Some linting 2021-05-19 09:46:31 -04:00
dmilov
a8d656e879 Merge pull request #449 from rnelson0/patch-1
Better handling of module version checks
2021-05-18 07:41:12 +03:00
Rob Nelson
0a94dd4658 Better handling of module version checks
If the module is not loaded, and autoloading does not occur before the `Get-HVModuleVersion` call, the result might be an empty string. This gives a chance to force loading the module and error if it is not available.
2021-05-17 15:41:54 -04:00
Jake Robinson
8db1fe37a2 Vmware Cloud Partner Navigator Example Module 2021-04-09 00:34:58 -04:00
dmilov
bffb3f7630 Merge pull request #438 from TheRealBenForce/FullClone-New-HvPool
enhancements for full clones
2021-03-19 12:27:09 +02:00
dmilov
e308436f06 Merge pull request #435 from mtelvers/ListByDatacenter
`VmTemplate_ListByDatacenter` requires two arguments as identified by
2021-03-19 12:26:30 +02:00
dmilov
a9bc152266 Merge pull request #441 from dmilov/dmilov/new-ssoadmin-features
Add new features in Get-SsoPersonUser and new cmdlet Remove-IdentitySource
2021-03-19 09:47:51 +02:00
Dimitar Milov
ed4f05238f Implement Remove-IdentitySource
Add FailoverUrl Property to ActiveDirectory identity source
2021-03-19 09:41:19 +02:00
Dimitar Milov
5fda0c70d5 Add Locked and Disabled properties to PersonUser object 2021-03-19 08:58:40 +02:00
Dimitar Milov
bfccd7faeb Implement Get-SsoPersonUser by Group 2021-03-18 19:13:54 +02:00
Dimitar Milov
6198fffb2d Implement GetPersonUsersInGroup 2021-03-18 18:58:13 +02:00
Dimitar Milov
4f60f40a72 Remove catalog file from the output 2021-03-17 18:27:34 +02:00
Ben Force
979463b66f enhancements for full clones 2021-03-09 11:46:22 -07:00
dmilov
0e8d0d9cf5 Merge pull request #434 from mtelvers/syslog
Added functions Get-HvSyslog and Set-HvSyslog to manage the UDP
2021-03-09 16:08:32 +02:00
mtelvers
cbd9a9594c VmTemplate_ListByDatacenter requires two arguments as identified by
@TheRealBenForce in #431.  I have looked back to PowerCLI 6.5 and this
was the case back then as well and not a new 12.2 change.

    VmTemplate_ListByDatacenter            Method
    VMware.Hv.VmTemplateInfo[] VmTemplate_ListByDatacenter(
      VMware.Hv.Services service, VMware.Hv.DatacenterId datacenter
      )

Without wanting to steal anyones credit I've created a PR for this change.
2021-03-08 09:52:11 +00:00
mtelvers
0f6839ba68 Added functions Get-HvSyslog and Set-HvSyslog to manage the UDP
syslog server settings on Horizon.
2021-03-08 08:53:39 +00:00
dmilov
7dd8f4cabc Merge pull request #430 from mtelvers/HostOrCluster
Removed duplicate calculation of HostClusterID
2021-03-08 08:40:51 +02:00
dmilov
63655338ee Merge pull request #428 from mtelvers/master
Address changes to BaseImageVm_List()
2021-03-08 08:39:38 +02:00
dmilov
cf7277cf7c Merge pull request #425 from ricoroodenburg/patch-2
Get-NetworkLabels function
2021-03-08 08:39:27 +02:00
mtelvers
0dd8b6f046 Removed duplicate calculation of HostClusterID 2021-03-05 19:14:34 +00:00
mtelvers
9f78104a1f Address changes to BaseImageVm_List()
Address issue #397
2021-03-02 14:54:26 +00:00
ricoroodenburg
30b8fa5c6d Update VMware.HV.Helper.psm1 2021-02-25 18:16:44 +01:00
ricoroodenburg
dc51c284da Get-NetworkLabels function
Can be used for the future, for assigning Network Labels to a a nic for new Horizon farm of desktop pool
2021-02-25 18:12:50 +01:00
dmilov
d3848a097f Merge pull request #421 from ricoroodenburg/patch-1
Added Load Balancing Settings
2021-02-24 07:20:14 +02:00
ricoroodenburg
38b3524beb Added Load Balancing Settings
- Added 2 lines within "Get-FarmSpec" (3281 + 3282)
- Added new parameters within "New-HVFarm" (2282 till 2312)
- Added new coding within "New-HVFarm" (2856 till 2866)
2021-02-23 23:05:27 +01:00
dmilov
fd9c63825c Merge pull request #419 from dmilov/topic/dmilov/reset-self-password
Implement Set-SsoSelfPersonUserPassword
2021-02-19 09:15:22 +02:00
Dimitar Milov
59f562d9ed Implement Set-SsoSelfPersonUserPassword 2021-02-19 09:14:32 +02:00
dmilov
7766772353 Merge pull request #409 from ashishsharma-git/patch-1
Update vRealize Operations Maintenance Mode.ps1
2021-02-17 16:45:46 +02:00
dmilov
e52b7dab53 Merge pull request #412 from bitszor/issue-400
Fix issue #400 - New-HVFarm fails when maxSessionsType is LIMITED
2021-02-17 16:44:41 +02:00
dmilov
6ebbad11e9 Merge pull request #418 from dmilov/topic/dmilov/failoverurl
Add SecondaryUrl parameter to Add-LDAPIdentitySource
2021-02-17 16:40:18 +02:00
Dimitar Milov
8606722f6e Add SecondaryUrl parameter to Add-LDAPIdentitySource 2021-02-17 16:38:46 +02:00
dmilov
13dc050dd2 Update README.md 2021-02-17 11:12:14 +02:00
dmilov
80509a18a5 Merge pull request #417 from dmilov/topic/dmilov/ssoadmin-externaldomain
Implement prepare for publishing funcitonality
2021-02-17 10:59:05 +02:00
Dimitar Milov
f07791e1dd Implement prepare for publishing funcitonality 2021-02-17 10:56:22 +02:00
dmilov
19e507581f Update README.md 2021-02-17 10:13:31 +02:00
dmilov
a31276bcdb Merge pull request #416 from dmilov/topic/dmilov/ssoadmin-externaldomain
Add LDAP Identity Source Functions
2021-02-17 10:12:17 +02:00
Dimitar Milov
16b3a0fe05 Add Set-LdapIdentitySource functionality 2021-02-17 10:10:39 +02:00
Dimitar Milov
fa518f99ee Fix certificate formatting before send them to the server 2021-02-17 09:26:23 +02:00
Dimitar Milov
1e8308d84c Fix tests taht use old pester syntax 2021-02-16 19:15:49 +02:00
Dimitar Milov
ef804e6a05 Migrated to Pester 5.1
Migrated to netcoreapp3.1
2021-02-16 19:10:43 +02:00
Dimitar Milov
5426af92b7 Fix LDAP register MoRef 2021-02-16 18:11:27 +02:00
Dimitar Milov
ac6c923e90 Implement Add-LDAPIdentitySource 2021-02-11 16:26:04 +02:00
dmilov
ec2ffb87ae Merge pull request #414 from dmilov/topic/dmilov/ssoadmin-externaldomain
New features and bug fixes
2021-02-11 11:44:14 +02:00
Dimitar Milov
f5a4dbf4cd Rebase on upstream master 2021-02-11 11:41:11 +02:00
Dimitar Milov
bda716b560 Rebase 2021-02-11 11:11:18 +02:00
Dimitar Milov
25f21ecfb5 Update binaries 2021-02-11 11:10:14 +02:00
Dimitar Milov
3f43eed119 Improve error handling. Added ref counting of server connections. Extended Add-ExternalDomainIdentitySource 2021-02-11 11:07:52 +02:00
Dimitar Milov
176590fb66 Update binaries 2021-02-11 10:33:33 +02:00
Dimitar Milov
775498aa8a Improve error handling. Added ref counting of server connections. Extended Add-ExternalDomainIdentitySource 2021-02-11 10:31:03 +02:00
Ben Blier
cb6076ac60 Fix issue #400 - New-HVFarm fails when maxSessionsType is LIMITED 2021-02-04 11:03:40 -07:00
ashishsharma-git
066dbb25f7 Update vRealize Operations Maintenance Mode.ps1
Since Get-Inventory does not return Datastore Objects, added switch "IsDatastore" to specify Datastore Objects being passed to the function.
2021-01-25 21:37:23 +05:30
dmilov
29c2cc0221 Merge pull request #406 from vmware/topic/dmilov/fix-addactivedirectory-for-67
Fix issue #405
2020-12-15 13:56:19 +02:00
dmilov
dcfd1c6caf Fix issue #405 2020-12-15 13:54:16 +02:00
dmilov
b2498a3fc3 Merge pull request #404 from vmware/topic/dmilov/fix-vsphere-sso-module
Remove searchAllDomains files from lookup service filter
2020-12-10 09:24:56 +02:00
dmilov
837d98960c Remove searchAllDomains files from lookup service filter 2020-12-10 09:21:55 +02:00
dmilov
c5d2cb9f09 Merge pull request #399 from dmilov/topic/dmilov/get-identity-source-cmdlet
Implement Get-IdnetitySource advanced function
2020-11-26 17:44:08 +02:00
dmilov
c212b24cbb Implement Get-IdnetitySource advanced function 2020-11-26 17:41:10 +02:00
dmilov
791f976665 Merge pull request #393 from antracey/patch-1
Update VMware.HV.Helper.psm1
2020-10-14 10:39:49 +03:00
dmilov
023edb4959 Merge pull request #391 from shidouli/master
Update the module to support the new feature introduced in PowerCLI
2020-10-14 10:38:36 +03:00
antracey
c1e8ee9ab9 Update VMware.HV.Helper.psm1
Fix New-HvManualApplication to support MultiSessionMode and MaxMultiSessions VMware.Hv.ApplicationData properties and validation of MaxMultiSessions param.
2020-10-13 17:55:08 -04:00
Carrie Yang
f4eb24821f Update the module to support the new feature introduced in PowerCLI
12.1.0 for vCenter Server 7.0.1: Add-TrustedHost should be used only for
   7.0.0, use 'Set-TrustedCluster -Remediate' for 7.0.1 for
     TrustedCluster adding a new host
2020-10-13 10:57:36 +08:00
dmilov
dc5a755805 Merge pull request #390 from dmilov/topic/type-name-typo-fix
Fix typo 'Stirng' to 'String' in argument transformation type names
2020-10-06 21:15:40 +03:00
dmilov
9abd96740a Fix typo 'Stirng' to 'String' in argument transformation type names 2020-10-06 21:11:24 +03:00
dmilov
acc1ab14bf Merge pull request #389 from dmilov/topic/obn-for-server-parameter
Implement OBN for -Server parameter of Disconnect-SsoAdminServer funstion. Fixes https://github.com/vmware/PowerCLI-Example-Scripts/issues/387
2020-10-06 11:01:17 +03:00
dmilov
c1e3e1936e Merge 2020-10-06 10:57:00 +03:00
dmilov
8aa673e375 Add tests for String to SsoAdminServer argument transformation in Disconnect-SsoAdminServer funciton 2020-10-06 10:56:00 +03:00
dmilov
927d5de17c Implement String to SsoAdmin server argument transformation attribute 2020-10-06 10:45:13 +03:00
dmilov
67529beefa Merge pull request #388 from qlikq/master
Enable quick disconnect for Disconnect-SsoAdminServer
2020-10-06 10:40:07 +03:00
dmilov
8621610ed8 Implement String to SsoAdmin server argument transformation attribute 2020-10-06 10:38:38 +03:00
Grzegorz Kulikowski
2c1eafde18 Modify test disconnect-ssoadminserver with throw msg 2020-10-06 08:59:32 +02:00
Grzegorz Kulikowski
7832d6e7ae Use Throw instead of ThrowTerminatingError() 2020-10-06 08:50:50 +02:00
Grzegorz Kulikowski
d6565f9e26 fix test for Disconnect-SsoAdminServer 2020-10-05 20:38:37 +02:00
Grzegorz Kulikowski
ca508570fb Add support for quick disconnect to Disconnect-SsoAdminServer
In case one is connected just to one SSO server the cmdlet does not
need to take the -server parameter as it will be discovered from
$DefaultSsoAdminServers. In case there are more than 1 SSO servers
it will not disconnect any connection, instead it will ask to be more
precise using the Server parameter.
2020-10-05 20:28:40 +02:00
Grzegorz Kulikowski
b03c1a536d Add pester tests for Disconnect-SsoaAminServer 2020-10-05 20:16:36 +02:00
dmilov
eb827499cd Merge pull request #386 from dmilov/topic/dmilov/SsoAdminModule
PowerShell Module for managing VMware vSphere SSO Admin functionality
2020-10-05 10:50:25 +03:00
dmilov
b2934bcbf1 Rename module's exported functions with Sso prefix on the noun part 2020-10-05 10:48:36 +03:00
dmilov
68e777357c Address PR discussions 2020-10-05 10:39:52 +03:00
dmilov
4ca1a612ab Update copyright info 2020-10-01 17:16:16 +03:00
dmilov
def74388ce Update README with required build and test tools 2020-09-30 16:00:09 +03:00
dmilov
69975a39ff Fix net45 assmeblies publishing 2020-09-30 15:44:01 +03:00
dmilov
63d52d4e60 Fix global defaultSsoAdminServers variable 2020-09-30 15:28:34 +03:00
dmilov
6148e8ff89 Implement Add-ActiveDirectoryIdentitySource 2020-09-30 15:19:54 +03:00
dmilov
14e81f78af Implement Get/Set-TokenLifetime 2020-09-30 14:26:31 +03:00
dmilov
5abdbe9702 Implement Get/Set-LockoutPolicy cmdlets 2020-09-30 13:48:01 +03:00
dmilov
88648e2db2 Implement Get/Set-PasswordPolicy cmdlets 2020-09-30 12:17:56 +03:00
dmilov
c53453abb2 Implement Get/Set-PasswordPolicy cmdlets 2020-09-30 12:17:36 +03:00
dmilov
b8030e4272 Implement ResetPassword and Unlock for PersonUser accounts. 2020-09-29 17:16:47 +03:00
dmilov
5fb63bb345 Implement Add/Remove User to/from Group 2020-09-29 16:52:17 +03:00
dmilov
0cf0626f4c Implement Get-Group advanced function 2020-09-29 16:01:37 +03:00
dmilov
48df3710fd Implement Get/New/Remove-PersonUser 2020-09-29 14:39:30 +03:00
dmilov
bac4cf704c Implement Connad/Disconnect-SsoAdminServer finctions 2020-09-29 09:53:29 +03:00
dmilov
8599b67b81 Implement SsoAdminServer data type
Implement GetLocalUsers
Add inntegration tests for GetLocalUsers
2020-09-29 08:18:49 +03:00
dmilov
391660cdf4 Implement Create/Delete/List person users functionality in ssoAdminClient 2020-09-28 17:59:13 +03:00
dmilov
64e0b52224 Adds module code structure, build script, test script, and API bindings 2020-09-28 11:25:47 +03:00
dmilov
35859f68ba Merge pull request #381 from CTip/master
Update VMware.HV.Helper.psm1 - expanded manual pool options
2020-09-23 10:17:17 +03:00
dmilov
1a7acd4812 Merge pull request #370 from saintdle/master
Edits to VMC NSX-T module
2020-09-23 10:15:55 +03:00
dmilov
d5abcdfbbe Merge branch 'master' into master 2020-09-23 10:15:25 +03:00
dmilov
f685181096 Merge pull request #380 from dunsdon/patch-3
Update Backup-VCSA.psm1
2020-09-23 10:13:00 +03:00
dmilov
f6f10d1738 Merge pull request #382 from dunsdon/patch-4
Update VAMI.psm1
2020-09-23 10:07:29 +03:00
Michael Dunsdon
0c3cad8410 Update VAMI.psm1
Made some additional Changes and adjusted the Case of Variables.
2020-09-22 13:10:16 -05:00
CTip
3c45bbc117 Update VMware.HV.Helper.psm1 2020-09-21 15:38:51 -05:00
Michael Dunsdon
368ec747ac Update Backup-VCSA.psm1
Updated Code based on Comments
2020-09-21 14:35:17 -05:00
dmilov
d64e0fbdc0 Merge pull request #373 from vMarkusK/Apply-OMRightsizing
Apply-OMRightsizing
2020-08-03 09:47:50 +03:00
Markus Kraus
9532ea9fac pply-OMRightsizing 2020-07-30 20:45:13 +02:00
dmilov
b78fb11206 Merge pull request #369 from mycloudrevolution/Set-VMHostSecureNTP.ps1
New Function Set-VMHostSecureNTP
2020-06-01 09:36:05 +03:00
Markus Kraus
b0dcb843aa Fix tab alignments 2020-05-30 21:02:25 +02:00
Markus Kraus
d2544c9418 Other loop for "Remove all existing NTP Servers" 2020-05-30 20:59:57 +02:00
Markus Kraus
8de5885437 Change NTP input to type ipaddress 2020-05-30 20:51:00 +02:00
Markus Kraus
7ecfd1309d ReOrg the inline function 2020-05-30 20:48:19 +02:00
Markus Kraus
91053171e7 Add Parameter Position 2020-05-29 19:17:01 +02:00
Markus Kraus
dd4bb2f415 fix Typos 2020-05-28 21:06:40 +02:00
Markus Kraus
4d1436b857 Fix Var Naming 2020-05-28 21:01:09 +02:00
Markus Kraus
4af6de8e1d Add MetaData 2020-05-28 20:58:53 +02:00
Markus Kraus
3a91b48f15 Add Secure Operation 2020-05-28 20:45:46 +02:00
Markus Kraus
91cac83589 Fix for existing configurations 2020-05-28 20:38:09 +02:00
Markus Kraus
222f75a6ca Workaround for duplicate IP 2020-05-27 18:59:32 +02:00
Markus Kraus
9a7dc6dd59 Added Error Handling and Pre-Checks 2020-05-26 22:37:26 +02:00
Markus Kraus
bd70bfb5dc processing for SetSecure 2020-05-25 21:45:13 +02:00
Markus Kraus
5c3e80bbf6 SetSecure inlline function 2020-05-25 21:41:22 +02:00
dmilov
f0e801fceb Merge pull request #368 from lamw/master
Add Workload Management module for vSphere with Kubernetes
2020-05-21 07:59:31 +03:00
William Lam
29b3b75604 Added Workload Management module for vSphere with Kubernetes
Updating Banner
2020-05-20 07:57:54 -07:00
dmilov
efef60d86a Merge pull request #265 from ctolan/Pester-Test-Coverage
Pester test coverage
2020-05-18 09:03:05 +03:00
dmilov
0500e52750 Merge pull request #358 from lamw/master
Add support for pagination for retrieving NSX-T Segments
2020-05-15 16:31:26 +03:00
dmilov
cfd3ca222d Merge pull request #365 from mycloudrevolution/Get-UplinkDetails
New Function Get-VMHostUplinkDetails
2020-05-08 08:40:07 +03:00
Markus Kraus
ca6f6abeb7 remove reporting array and sort 2020-05-07 20:42:54 +02:00
Markus Kraus
f53c09ae03 Replace % with Foreach-Object. 2020-05-07 20:35:44 +02:00
Markus Kraus
0c3ff917d0 Replace where with Where-Object 2020-05-07 20:34:28 +02:00
Markus Kraus
228de51f25 Fix code formatting 2020-05-07 20:33:25 +02:00
Markus Kraus
e24187a954 rename VMHost Parameter 2020-05-07 20:32:06 +02:00
Markus Kraus
be7f982767 Update Parameter 2020-05-07 20:25:40 +02:00
Markus Kraus
3a4dada48d Rename Function 2020-05-07 20:20:13 +02:00
Markus Kraus
a918eacdad Rename Get-UplinkDetail.ps1 to Get-UplinkDetails.ps1 2020-04-29 23:04:44 +02:00
Markus Kraus
76d01e7eb8 Create Get-UplinkDetail.ps1 2020-04-29 23:04:18 +02:00
Markus Kraus
1191cf6f75 Merge pull request #2 from vmware/master
Update Fork
2020-04-29 23:01:45 +02:00
saintdle
a4d766922a Update VMware.VMC.NSXT.psm1
By adding the validation 'EQUALS' to line 881, this allows for the creating of a Group using the virtual machine member type. This change works for creating a single virtual machine using this type. Cannot quite figure out how to fix this to work for adding multiple machines at once.
2020-04-20 21:47:22 +01:00
saintdle
4b2113d44f Merge pull request #1 from saintdle/saintdle-patch-1
Update VMware.VMC.NSXT.psm1
2020-04-20 20:15:20 +01:00
saintdle
d6b02fb0ad Update VMware.VMC.NSXT.psm1
Corrected spelling mistake on like 93 + 104
Retrievig 
To;
retrieving
2020-04-20 20:14:43 +01:00
Alan Renouf
f4ef4b0e07 Merge pull request #362 from vmware/AccessUpdates
Updated Workspace One Access module
2020-04-15 15:04:44 -07:00
William Lam
1e7033a66f Add support for pagination for retrieving NSX-T Segments 2020-03-07 13:39:29 -08:00
Conor Tolan
bbc6d0f775 Started tests for VMCFirewall.
Fixed incorrect function call in sddc version test.
2019-02-27 22:23:05 +00:00
Conor Tolan
3e09f0a601 Wrote tests covering get VMC SDDC Version
Fixed up get VMC Hosts a bit.
2019-02-25 22:28:23 +00:00
Conor Tolan
f926508d1f Added test for Get-VMCVMHost, complicated object mocking. 2019-02-25 21:09:18 +00:00
Conor Tolan
c01427f6f4 Added new tests. 2019-02-24 16:06:47 +00:00
Conor Tolan
2bb82249ca Added new tests for get default creds
Added test for not connected route in functions to increase coverage.
2019-02-24 14:41:16 +00:00
Conor Tolan
b5111e1fab Adding a VMC code coverage script to invoke the coverage report. 2019-02-23 19:33:24 +00:00
Conor Tolan
5c833d4ce5 Wraped all the tests inModuleScope for invoke-pester invocation.
Moved function name into module scope.
2019-02-23 18:56:44 +00:00
Conor Tolan
b90c83ac56 Created tests for get VMC Task
Trimed out excess fom get SDDC parameters in the object.
2019-02-23 18:06:09 +00:00
Conor Tolan
f642290b2d Tidied up the object creation in tests. 2019-02-23 17:41:23 +00:00
Conor Tolan
a95e01066d Renamed VMC Org test file.
Added VMC Sddc test file.
2019-02-23 16:40:31 +00:00
Conor Tolan
6c578f7b78 Added mock write-host to clean up output.
Added the general creation of the $object needed to mock the function.
2019-02-23 16:37:03 +00:00
Conor Tolan
3a61850b41 Randomly wrote over import. undone. 2019-02-20 22:26:26 +00:00
Conor Tolan
783319a624 Finished org tests 2019-02-20 22:17:59 +00:00
Conor Tolan
f9ca007ae5 Added two pester tests for Get-VMCCommand and Connect-VMCVIServer. 2019-02-18 21:57:52 +00:00
191 changed files with 29545 additions and 1593 deletions

2
.gitignore vendored
View File

@@ -5,6 +5,7 @@
#VS Code Files
*.vscode
/.vs
# Windows image file caches
Thumbs.db
@@ -49,3 +50,4 @@ $RECYCLE.BIN/
Network Trash Folder
Temporary Items
.apdisk
/Modules/VMware.vSphere.SsoAdmin/ForPSGallery/VMware.vSphere.SsoAdmin

View File

@@ -1,42 +0,0 @@
# PowerCLI-Example-Scripts
VMWARE TECHNOLOGY PREVIEW LICENSE AGREEMENT
Notice to User: This Technology Preview License Agreement (the “Agreement”) is a CONTRACT between you (either an individual or a single entity) (“you” or “Licensee”) and VMware, Inc. (“VMware”), which covers your use of the Technology Preview Software (as defined below). If you do not agree to the terms of this Agreement, then do not install or use the Technology Preview Software. By explicitly accepting this Agreement, however, or by installing, copying, downloading, accessing, or otherwise using the Technology Preview Software, you are acknowledging and agreeing to be bound by the following terms.
1. DEFINITIONS. (a) “Technology Preview Software” means the unreleased, concept version of VMwares software, in object form only, excluding any Open Source Software provided with the such software, and the media and Documentation provided by VMware to Licensee and for which Licensee is granted a use license pursuant to this Agreement. (b) “Documentation” means the printed and online written reference material furnished to Licensee in conjunction with the Technology Preview Software, including, without limitation, instructions, testing guidelines, and end user guides. (c) “Intellectual Property Rights” shall mean all intellectual property rights, including, without limitation, patent, copyright, trademark, and trade secret. (d) “Open Source Software” means various open source software components provided with the Technology Preview Software that are licensed to you under the terms of the applicable license agreements included with such open source software components or other materials for the Technology Preview Software. (e) “Updates” means a modification, error correction, bug fix, new release, or other update to or for the Technology Preview Software.
2. LICENSE GRANT, USE AND OWNERSHIP.
(a) Limited License. Subject to the terms and conditions of this Agreement, VMware grants to Licensee a non-exclusive, non-transferable license (without the right to sublicense) (i) to use the Technology Preview Software in accordance with the Documentation solely for purposes of internal testing and evaluation, (ii) to use the Documentation provided with the Technology Preview Software in support of Licensees authorized use of the Technology Preview Software, and (iii) to copy the Technology Preview Software for archival or backup purposes, provided that all titles and trademarks, copyright, and restricted rights notices are reproduced on such copies.
(b) Evaluation Feedback. The purpose of this limited license is the testing and evaluation of the Technology Preview Software as set forth above. In furtherance of this purpose, Licensee shall provide feedback to VMware concerning the functionality and performance of the Technology Preview Software from time to time as reasonably requested by VMware, including, without limitation, identifying potential errors and improvements. Licensee will provide the requested feedback in a manner that is convenient to Licensee subject to reasonable availability of Licensees personnel. Notwithstanding the foregoing, prior to Licensee disclosing to VMware any information under this Agreement that Licensee considers proprietary or confidential, Licensee shall obtain VMwares prior written approval to disclose such information to VMware, and without such prior written approval from VMware, Licensee shall not disclose any such information to VMware. VMware may use feedback to improve or enhance its products and, accordingly, you hereby grant to VMware a non-exclusive, perpetual, irrevocable, royalty-free, transferable, worldwide right and license, with the right to sublicense, to use, reproduce, disclose, distribute, perform, display, modify, prepare derivative works of and otherwise exploit the feedback and other information without restriction in any manner now known or in the future conceived and to make, use, sell, offer to sell, import and export any product or service that incorporates the feedback and other information.
(c) Restrictions. Licensee shall not copy or use the Technology Preview Software (including the Documentation) except as expressly permitted in this Agreement. Except to the extent that any applicable mandatory laws prevent VMware restraining Licensee from doing so, Licensee will not, and will not permit any third party to, sublicense, rent, copy, modify, create derivative works of, translate, reverse engineer, decompile, disassemble, or otherwise reduce to human perceivable form any portion of the Technology Preview Software or accompanying Documentation. Without limiting the generality of the foregoing, Licensee shall not use the Technology Preview Software for Licensees product development or any other commercial purpose. The Technology Preview Software and all performance data and test results, including without limitation, benchmark test results (collectively “Performance Data”) relating to the Technology Preview Software are the Confidential Information of VMware, and will be treated in accordance with the terms of Section 4 of this Agreement. Accordingly, Licensee shall not publish or disclose to any third party any Performance Data relating to the Technology Preview Software.
(d) Ownership. VMware shall own and retain all right, title and interest in and to the Intellectual Property Rights in the Technology Preview Software, subject only to the limited license expressly set forth in Section 2(a) hereof. Licensee does not acquire any other rights, express or implied, in the Technology Preview Software. ALL RIGHTS NOT EXPRESSLY GRANTED HEREUNDER ARE RESERVED TO VMWARE.
(e) No Support Services. VMware is under no obligation to support the Technology Preview Software in any way or to provide any Updates to Licensee. In the event VMware, in its sole discretion, supplies any Update to Licensee, the Update shall be deemed Technology Preview Software under this Agreement and shall be subject to the terms and conditions of this Agreement.
(f) Third-Party Software. The Technology Preview Software may enable a computer to run multiple instances of third-party guest operating systems and application programs. Licensee acknowledges that Licensee is responsible for obtaining any licenses necessary to operate any third-party software, including guest operating systems and application programs.
(g) Open Source Software. Except for Sections 5, 6 and 7, the terms and conditions of this Agreement shall not apply to any Open Source Software accompanying the Technology Preview Software. Any such Open Source Software is provided under the terms of the open source license agreement or copyright notice accompanying such Open Source Software or in the open source licenses file accompanying the Technology Preview Software.
3. TERM AND TERMINATION. Licensees rights with respect to the Technology Preview Software will terminate upon the earlier of (a) automatic expiration of the Technology Preview Software based on the system date, or (b) termination by VMware, in its sole discretion, of Licensees rights with respect to the Technology Preview Software provided under this Agreement upon notice on the VMware website. Upon any expiration or termination of rights with respect to the Technology Preview Software under this Agreement, the rights and licenses granted to Licensee under this Agreement shall immediately terminate, and Licensee shall immediately cease using, and will destroy or render practically inaccessible the Technology Preview Software, Documentation, and all other tangible items in Licensees possession or control that contain Confidential Information. The rights and obligations of the parties set forth in Sections 2(b), 2(c), 2(d), 2(e), 2(f), 2(g), 3, 4, 5, 6 and 7 shall survive termination or expiration of this Agreement for any reason.
4. CONFIDENTIALITY. (a) Confidentiality. "Confidential Information" means the Technology Preview Software, all information regarding the Technology Preview Software (including any trade secrets, know-how, inventions, techniques, processes, and algorithms embodied in the Technology Preview Software), Documentation, Performance Data, any Updates, and other information provided by VMware to Licensee under this Agreement, whether disclosed orally, in writing, or by examination or inspection, other than information that Licensee can demonstrate (i) was already known to Licensee, other than under an obligation of confidentiality, at the time of disclosure; (ii) was generally available in the public domain at the time of disclosure to Licensee; (iii) became generally available in the public domain after disclosure other than through any act or omission of Licensee; (iv) was subsequently lawfully disclosed to Licensee by a third party without any obligation of confidentiality; or (v) was independently developed by Licensee without use of or reference to any information or materials disclosed by VMware or its suppliers. If Licensee is required to disclose Confidential Information by applicable law or court order, Licensee shall notify VMware of the required disclosure promptly in writing and shall cooperate with VMware in any lawful action to contest or limit the scope of the required disclosure. Confidential Information shall include, without limitation, any information relating to VMware products, product roadmaps, and other technical, business, financial and product development plans, forecasts and strategies. Licensee shall not use any Confidential Information for any purpose other than as expressly authorized under this Agreement. In no event shall Licensee use the Technology Preview Software or any Confidential Information to develop, manufacture, market, sell, or distribute any product or service, including any VMware products. Licensee shall not disclose any Confidential Information to any third party. Without limiting the foregoing, Licensee shall use at least the same degree of care that it uses to prevent the disclosure of its own confidential information of like importance, but in no event less than reasonable care, to prevent the disclosure of such Confidential Information. (b) Additional Confidentiality Restrictions for Highly Confidential Technology Preview Software. For certain Technology Preview Software designated by VMware as highly confidential (“Highly Confidential Technology Preview Software”) in VMwares correspondence to you regarding this Technology Preview Software or in any Documentation, additional heightened confidentiality restrictions designated below will apply. (i) Licensee shall limit dissemination of Highly Confidential Technology Preview Software and related information concerning product features, future technologies and roadmaps only to Information Technology teams and/or software/solutions development teams of Licensee designated by VMware, and only to individuals on those teams who have a need to know the Confidential Information for purposes expressly authorized under this Agreement. For clarity and without limiting the generality of the foregoing, Licensee shall not disseminate any Highly Confidential Technology Preview Software to Licensee's sales and marketing field organizations. Licensee will assign an employee who will be primarily responsible (“Primary Contact”) for ensuring that the terms of this Agreement are complied with. (ii) Licensee acknowledges that damages for improper disclosure of Highly Confidential Technology Preview Software or related information concerning product features, future technologies and roadmaps may be irreparable and that monetary damages would be inadequate to compensate VMware for any breach of this Agreement. In the event that VMware reasonably believes that Licensee has disseminated certain of such Highly Confidential Technology Preview Software or related information concerning product features, future technologies and roadmaps to an unauthorized party, Licensee will be immediately removed from VMwares Technology Preview Software program and will not be permitted to participate in any VMware Technology Preview Software program in the future. Additionally, all rights and licenses granted to Licensee under this Agreement shall immediately terminate in accordance with Section 3 herein (Term and Termination). (c) Remedies. In addition to all other remedies available in law or otherwise, VMware is entitled to seek equitable relief, including injunctive relief, against the threatened breach of this Agreement or the continuation of any such breach.
5. LIMITATION OF LIABILITY. IT IS UNDERSTOOD THAT THE TECHNOLOGY PREVIEW SOFTWARE IS PROVIDED WITHOUT CHARGE FOR LIMITED EVALUATION PURPOSES. ACCORDINGLY, THE TOTAL LIABILITY OF VMWARE AND ITS LICENSORS ARISING OUT OF OR RELATED TO THIS AGREEMENT SHALL NOT EXCEED US$100.00. TO THE FULLEST EXTENT PERMITTED BY LAW, IN NO EVENT SHALL VMWARE OR ITS LICENSORS HAVE LIABILITY FOR ANY INDIRECT, INCIDENTAL, PUNITIVE, SPECIAL, OR CONSEQUENTIAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, OR LOSS OF BUSINESS INFORMATION), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY (INCLUDING WITHOUT LIMITATION, TORT, STATUTE, CONTRACT OR OTHER), EVEN IF VMWARE AND ITS LICENSORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS SHALL APPLY NOTWITHSTANDING ANY FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY.
6. WARRANTY DISCLAIMER. IT IS UNDERSTOOD THAT THE TECHNOLOGY PREVIEW SOFTWARE, OPEN SOURCE SOFTWARE, DOCUMENTATION, AND ANY UPDATES MAY CONTAIN ERRORS AND ARE PROVIDED FOR LIMITED EVALUATION ONLY. THE TECHNOLOGY PREVIEW SOFTWARE, THE OPEN SOURCE SOFTWARE, THE DOCUMENTATION, AND ANY UPDATES ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE. VMWARE AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. Licensee acknowledges that VMware has not publicly announced the availability of the Technology Preview Software, that such Technology Preview Software may contain features currently under development, that VMware has not promised or guaranteed to Licensee that such Technology Preview Software will be announced or made available to anyone in the future, that VMware has no express or implied obligation to Licensee to announce or introduce the Technology Preview Software, that VMware has no obligation to introduce a product similar to or compatible with the Technology Preview Software, and that any version number (if any) referenced is subject to change and does not in any way represent VMwares commitment to release any product in the future. Accordingly, Licensee acknowledges that any research or development that it performs regarding the Technology Preview Software or any product associated with the Technology Preview Software is done entirely at Licensees own risk. Specifically, the Technology Preview Software may contain features, functionality or modules that will not be included in the production version of the Technology Preview Software, if released, or that will be marketed separately for additional fees.
7. OTHER PROVISIONS. (a) Governing Law. This Agreement, and all disputes arising out of or related thereto, shall be governed by and construed under the laws of the State of California without reference to conflict of laws principles. All such disputes shall be subject to the exclusive jurisdiction of the state and federal courts located in Santa Clara County, California, and the parties agree and submit to the personal and exclusive jurisdiction and venue of these courts. The United Nations Convention for the International Sale of Goods shall not apply. (b) Export Control.  The Technology Preview Software is of United States origin and is provided subject to the U.S. Export Administration Regulations. Diversion contrary to U.S. law is prohibited. Without limiting the foregoing, you agree that (i) you are not, and are not acting on behalf of, any person who is a citizen, national, or resident of, or who is controlled by the government of, Cuba, Iran, North Korea, Sudan, or Syria, or any other country to which the United States has prohibited export transactions; (ii) you are not, and are not acting on behalf of, any person or entity listed on the U.S. Treasury Department list of Specially Designated Nationals and Blocked Persons, or the U.S. Commerce Department Denied Persons List or Entity List; and (iii) you will not use the Technology Preview Software for, and will not permit the Technology Preview Software to be used for, any purposes prohibited by law, including, without limitation, for any prohibited development, design, manufacture or production of missiles or nuclear, chemical or biological weapons. U.S. Export Control Classification Numbers (ECCNs) may be found at VMware help page: http://www.vmware.com/help/export-control. (c) Modification. This is the entire agreement between the parties relating to the subject matter hereof and all other terms are rejected. No waiver or modification of this Agreement shall be valid unless in writing signed by each party. The waiver of a breach of any term hereof shall in no way be construed as a waiver of any other term or breach hereof. If any provision of this Agreement is held by a court of competent jurisdiction to be contrary to law, the remaining provisions of this Agreement shall remain in full force and effect. (d) Data Privacy. Licensee agrees that VMware may process technical and related usage information about Licensees use of the Technology Preview Software for statistical and analytical purposes. Usage information is collected strictly for internal statistical and analytical purposes for the development of VMware products and services. Licensee understands that any log files generated in order to obtain support from VMware may contain sensitive, confidential or personal information. Licensee should consider obfuscating any logs before sending them to VMware. VMwares privacy policy (http://www.vmware.com/help/privacy.html) shall apply.
8. ASSIGNMENT. Licensee shall not assign this Agreement or any rights or obligations hereunder, directly or indirectly, by operation of law, merger, acquisition of stock or assets, or otherwise, without the prior written consent of VMware. Any attempted assignment or transfer in violation of the foregoing will be null and void. Subject to the foregoing, this Agreement shall inure to the benefit of and be binding upon the parties and their respective successors and permitted assigns.
9. CONTACT INFORMATION. If you have any questions about this Agreement, please direct all correspondence to: VMware, Inc., 3401 Hillview Avenue, Palo Alto, CA 94304, United States of America or email info@vmware.com. VMware is a trademark of VMware, Inc. and is registered in the U.S. and numerous other countries.
Rev. 2014Mar10

12
LICENSE.txt Normal file
View File

@@ -0,0 +1,12 @@
PowerCLI-Example-Scripts
Copyright 2021 VMware, Inc.
BSD 2-Clause License
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -1,4 +1,8 @@
Function Backup-VCSAToFile {
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Backup-VCSAToFile {
<#
.NOTES
===========================================================================
@@ -7,15 +11,16 @@
Organization: VMware
Blog: www.vtagion.com
Twitter: @vBrianGraf
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function will allow you to create a full or partial backup of your
VCSA appliance. (vSphere 6.5 and higher)
.DESCRIPTION
Use this function to backup your VCSA to a remote location
.EXAMPLE
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$BackupPassword = "VMw@re123"
$Comment = "First API Backup"
@@ -24,43 +29,62 @@
$LocationUser = "admin"
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$locationPassword = "VMw@re123"
PS C:\> Backup-VCSAToFile -BackupPassword $BackupPassword -LocationType $LocationType -Location $location -LocationUser $LocationUser -LocationPassword $locationPassword -Comment "This is a demo" -ShowProgress -FullBackup
.NOTES
Credit goes to @AlanRenouf for sharing the base of this function with me which I was able to take and make more robust as well as add in progress indicators
You must be connected to the CisService for this to work, if you are not connected, the function will prompt you for your credentials
A CisService can also be supplied as a parameter.
If a -LocationType is not chosen, the function will default to FTP.
The destination location for a backup must be an empty folder (easiest to use the get-date cmdlet in the location)
-ShowProgress will give you a progressbar as well as updates in the console
-CommonBackup will only backup the config whereas -Fullbackup grabs the historical data as well
#>
param (
[Parameter(ParameterSetName=FullBackup)]
[Parameter(ParameterSetName='FullBackup')]
[switch]$FullBackup,
[Parameter(ParameterSetName=CommonBackup)]
[Parameter(ParameterSetName='CommonBackup')]
[switch]$CommonBackup,
[ValidateSet('FTPS', 'HTTP', 'SCP', 'HTTPS', 'FTP')]
[ValidateSet('FTPS', 'HTTP', 'SCP', 'HTTPS', 'FTP', 'SMB', 'SFTP')]
$LocationType = "FTP",
$Location,
$LocationUser,
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$LocationPassword,
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$BackupPassword,
$Comment = "Backup job",
[Parameter(Mandatory=$false)]$CisServer = $global:DefaultCisServers,
[switch]$ShowProgress
)
Begin {
if (!($global:DefaultCisServers)){
Add-Type -Assembly System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("It appears you have not created a connection to the CisServer. You will now be prompted to enter your vCenter credentials to continue" , "Connect to CisServer") | out-null
if ($CisServer.IsConnected) {
Write-Verbose "Connected to $($CisServer.Name)"
$connection = $CisServer
} elseif ($CisServer.gettype().name -eq "String") {
Write-Host "Prompting for CIS Server credentials. Connecting to $($CisServer)."
$Connection = Connect-CisServer $CisServer
} elseif ($global:DefaultCisServers) {
$connection = $global:DefaultCisServers
} elseif ($global:DefaultVIServer) {
Write-Host "Prompting for CIS Server credentials. Connecting to $($global:DefaultVIServer.name)."
$Connection = Connect-CisServer $global:DefaultVIServer
} else {
$Connection = $global:DefaultCisServers
}
if (!$Connection) {
Write-Error "It appears you have not created a connection to the CisServer. Please Connect First and try command again. (Connect-CisServer)"
}
if ($FullBackup) {$parts = @("common","seat")}
if ($CommonBackup) {$parts = @("common")}
# Per github issue 468 (https://github.com/vmware/PowerCLI-Example-Scripts/issues/468) adding some logic to account for SFTP/SCP handling in versions after VC 7.0.
$vCenterVersionNumber = (Get-CisService -Name 'com.vmware.appliance.system.version').get().version
if ( ($vCenterVersionNumber -ge 6.5 -AND $vCenterVersionNumber -lt 7.0 ) -AND $LocationType -eq 'SFTP' ) {
write-warning 'VCSA Backup for versions 6.5 and 6.7 use SCP, not SFTP. Adjusting the LocationType accordingly.'
$LocationType = 'SCP'
}
if ( $vCenterVersionNumber -ge 7.0 -AND $LocationType -eq 'SCP' ) {
write-warning 'VCSA Backup starting with version 7.0 use SFTP and not SCP. Adjusting the LocationType accordingly.'
$LocationType = 'SFTP'
}
}
Process{
$BackupAPI = Get-CisService com.vmware.appliance.recovery.backup.job
$BackupAPI = Get-CisService 'com.vmware.appliance.recovery.backup.job'
$CreateSpec = $BackupAPI.Help.create.piece.CreateExample()
$CreateSpec.parts = $parts
$CreateSpec.backup_password = $BackupPassword
@@ -71,25 +95,20 @@
$CreateSpec.comment = $Comment
try {
$BackupJob = $BackupAPI.create($CreateSpec)
}
catch {
} catch {
throw $_.Exception.Message
}
If ($ShowProgress){
do {
$BackupAPI.get("$($BackupJob.ID)") | select id, progress, state
$BackupAPI.get("$($BackupJob.ID)") | Select-Object id, progress, state
$progress = ($BackupAPI.get("$($BackupJob.ID)").progress)
Write-Progress -Activity "Backing up VCSA" -Status $BackupAPI.get("$($BackupJob.ID)").state -PercentComplete ($BackupAPI.get("$($BackupJob.ID)").progress) -CurrentOperation "$progress% Complete"
start-sleep -seconds 5
Start-Sleep -seconds 5
} until ($BackupAPI.get("$($BackupJob.ID)").progress -eq 100 -or $BackupAPI.get("$($BackupJob.ID)").state -ne "INPROGRESS")
Write-Progress -Activity "Backing up VCSA" -Completed
$BackupAPI.get("$($BackupJob.ID)") | select id, progress, state
}
Else {
$BackupJob | select id, progress, state
$BackupAPI.get("$($BackupJob.ID)") | Select-Object id, progress, state
} Else {
$BackupJob | Select-Object id, progress, state
}
}
End {}
@@ -104,17 +123,19 @@ Function Get-VCSABackupJobs {
Organization: VMware
Blog: www.vtagion.com
Twitter: @vBrianGraf
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
Get-VCSABackupJobs returns a list of all backup jobs VCSA has ever performed (vSphere 6.5 and higher)
.DESCRIPTION
Get-VCSABackupJobs returns a list of all backup jobs VCSA has ever performed
.EXAMPLE
PS C:\> Get-VCSABackupJobs
.EXAMPLE
PS C:\> Get-VCSABackupJobs -ShowNewest -CisServer "vcserver.sphere.local"
.NOTES
The values returned are read as follows:
YYYYMMDD-hhmmss-vcsabuildnumber
@@ -122,20 +143,28 @@ Function Get-VCSABackupJobs {
Get-VCSABackupJobs | select -First 1 | Get-VCSABackupStatus <- Most recent backup
#>
param (
[switch]$ShowNewest
[Parameter(Mandatory=$false)][switch]$ShowNewest,
[Parameter(Mandatory=$false)]$CisServer = $global:DefaultCisServers
)
Begin {
if (!($global:DefaultCisServers)){
[System.Windows.Forms.MessageBox]::Show("It appears you have not created a connection to the CisServer. You will now be prompted to enter your vCenter credentials to continue" , "Connect to CisServer") | out-null
if ($CisServer.IsConnected) {
Write-Verbose "Connected to $($CisServer.Name)"
$connection = $CisServer
} elseif ($CisServer.gettype().name -eq "String") {
Write-Host "Prompting for CIS Server credentials. Connecting to $($CisServer)."
$Connection = Connect-CisServer $CisServer
} elseif ($global:DefaultCisServers) {
$connection = $global:DefaultCisServers
} elseif ($global:DefaultVIServer) {
Write-Host "Prompting for CIS Server credentials. Connecting to $($global:DefaultVIServer.name)."
$Connection = Connect-CisServer $global:DefaultVIServer
} else {
$Connection = $global:DefaultCisServers
}
if (!$Connection) {
Write-Error "It appears you have not created a connection to the CisServer. Please Connect First and try command again. (Connect-CisServer)"
}
}
Process{
$BackupAPI = Get-CisService com.vmware.appliance.recovery.backup.job
$BackupAPI = Get-CisService 'com.vmware.appliance.recovery.backup.job'
try {
if ($ShowNewest) {
$results = $BackupAPI.list()
@@ -143,13 +172,10 @@ Function Get-VCSABackupJobs {
} else {
$BackupAPI.list()
}
}
catch {
} catch {
Write-Error $Error[0].exception.Message
}
}
End {}
}
@@ -162,43 +188,367 @@ Function Get-VCSABackupStatus {
Organization: VMware
Blog: www.vtagion.com
Twitter: @vBrianGraf
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
Returns the ID, Progress, and State of a VCSA backup (vSphere 6.5 and higher)
.DESCRIPTION
Returns the ID, Progress, and State of a VCSA backup
.EXAMPLE
PS C:\> $backups = Get-VCSABackupJobs
$backups[0] | Get-VCSABackupStatus
.NOTES
The BackupID can be piped in from the Get-VCSABackupJobs function and can return multiple job statuses
#>
Param (
[parameter(ValueFromPipeline=$True)]
[string[]]$BackupID
[parameter(Mandatory=$false,ValueFromPipeline=$True)][string[]]$BackupID,
[Parameter(Mandatory=$false)]$CisServer = $global:DefaultCisServers
)
Begin {
if (!($global:DefaultCisServers)){
[System.Windows.Forms.MessageBox]::Show("It appears you have not created a connection to the CisServer. You will now be prompted to enter your vCenter credentials to continue" , "Connect to CisServer") | out-null
if ($CisServer.IsConnected) {
Write-Verbose "Connected to $($CisServer.Name)"
$connection = $CisServer
} elseif ($CisServer.gettype().name -eq "String") {
Write-Host "Prompting for CIS Server credentials. Connecting to $($CisServer)."
$Connection = Connect-CisServer $CisServer
} elseif ($global:DefaultCisServers) {
$connection = $global:DefaultCisServers
} elseif ($global:DefaultVIServer) {
Write-Host "Prompting for CIS Server credentials. Connecting to $($global:DefaultVIServer.name)."
$Connection = Connect-CisServer $global:DefaultVIServer
} else {
$Connection = $global:DefaultCisServers
}
$BackupAPI = Get-CisService com.vmware.appliance.recovery.backup.job
if (!$Connection) {
Write-Error "It appears you have not created a connection to the CisServer. Please Connect First and try command again. (Connect-CisServer)"
}
}
Process{
foreach ($id in $BackupID) {
$BackupAPI.get("$id") | select id, progress, state
$BackupAPI = Get-CisService 'com.vmware.appliance.recovery.backup.job'
Foreach ($id in $BackupID) {
$BackupAPI.get("$id") | Select-Object id, progress, state
}
}
End {}
}
Function New-VCSASchedule {
<#
.NOTES
===========================================================================
Original Created by: Brian Graf
Blog: www.vtagion.com
Twitter: @vBrianGraf
Organization: VMware
Created / Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function will allow you to create a scheduled to backup your
VCSA appliance. (vSphere 6.7 and higher)
.DESCRIPTION
Use this function to create a schedule to backup your VCSA to a remote location
.EXAMPLE
The Below Create a schedule on Monday @11:30pm to FTP location 10.1.1.10:/vcsabackup/vcenter01
and keep 4 backups with a Encryption Passowrd of "VMw@re123"
$location = "ftp://10.1.1.10/vcsabackup/vcenter01"
$LocationUser = "admin"
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$locationPassword = "VMw@re123"
$BHour = 23
$BMin = 30
$BDays = @("Monday")
$MaxCount = 4
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$BackupPassword = "VMw@re123"
PS C:\> New-VCSASchedule -Location $location -LocationUser $LocationUser -LocationPassword $locationPassword -BackupHour $BHour -BackupMinute $BMin -backupDays $BDays -MaxCount $MaxCount -BackupPassword $BackupPassword
.EXAMPLE
The Below Create a schedule on Sunday & Wednesday @5:15am
to NFS location 10.1.1.10:/vcsabackup/vcenter01
keep 10 backups with a Encryption Passowrd of "VMw@re123"
with Event Data included (Seat) and will delete any existing schedule.
$location = "nfs://10.1.1.10/vcsabackup/vcenter01"
$LocationUser = "admin"
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$locationPassword = "VMw@re123"
$BHour = 5
$BMin = 15
$BDays = @("Sunday", "Monday")
$MaxCount = 10
[VMware.VimAutomation.Cis.Core.Types.V1.Secret]$BackupPassword = "VMw@re123"
PS C:\> New-VCSASchedule -IncludeSeat -force -Location $location -LocationUser $LocationUser -LocationPassword $locationPassword -BackupHour $BHour -BackupMinute $BMin -backupDays $BDays -MaxCount $MaxCount -BackupPassword $BackupPassword -CisServer "vcserver.sphere.local"
.NOTES
Credit goes to @AlanRenouf & @vBrianGraf for sharing the base of this function.
You must be connected to the CisService for this to work, if you are not connected, the function will prompt you for your credentials
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
param (
[Parameter(Mandatory=$true)]$Location,
[Parameter(Mandatory=$true)]$LocationUser,
[Parameter(Mandatory=$true)][VMware.VimAutomation.Cis.Core.Types.V1.Secret]$LocationPassword,
[Parameter(Mandatory=$false)][VMware.VimAutomation.Cis.Core.Types.V1.Secret]$BackupPassword,
[Parameter(Mandatory=$true)][ValidateRange(0,23)]$BackupHour,
[Parameter(Mandatory=$true)][ValidateRange(0,59)]$BackupMinute,
[Parameter(Mandatory=$true)][ValidateSet('MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY', IgnoreCase = $False)][Array]$BackupDays = $null,
[Parameter(Mandatory=$true)][Int]$MaxCount,
[Parameter(Mandatory=$false)]$BackupID = "default",
[Parameter(Mandatory=$false)]$CisServer = $global:DefaultCisServers,
[Parameter(Mandatory=$false)][switch]$IncludeSeat,
[Parameter(Mandatory=$false)][switch]$Force
)
Begin {
if ($CisServer.IsConnected) {
Write-Verbose "Connected to $($CisServer.Name)"
$connection = $CisServer
} elseif ($CisServer.gettype().name -eq "String") {
Write-Host "Prompting for CIS Server credentials. Connecting to $($CisServer)."
$Connection = Connect-CisServer $CisServer
} elseif ($global:DefaultCisServers) {
$connection = $global:DefaultCisServers
} elseif ($global:DefaultVIServer) {
Write-Host "Prompting for CIS Server credentials. Connecting to $($global:DefaultVIServer.name)."
$Connection = Connect-CisServer $global:DefaultVIServer
}
if (!$Connection) {
Write-Error "It appears you have not created a connection to the CisServer. Please Connect First and try command again. (Connect-CisServer)"
}
}
Process{
if (!(Test-VCSAScheduleSupport)) {
Write-Error "This VCSA does not support Backup Schedules."
return
}
$BackupAPI = Get-CisService -name 'com.vmware.appliance.recovery.backup.schedules'
$CreateSpec = $BackupAPI.Help.create.spec.Create()
$CreateSpec.backup_password = $BackupPassword
$CreateSpec.location = $Location
$CreateSpec.location_user = $LocationUser
$CreateSpec.location_password = $LocationPassword
$CreateSpec.Enable = $true
$CreateSpec.recurrence_info.Hour = $BackupHour
$CreateSpec.recurrence_info.Minute = $BackupMinute
$CreateSpec.recurrence_info.Days = $BackupDays
$CreateSpec.retention_info.max_count = $MaxCount
if ($IncludeSeat) {
$CreateSpec.parts = @("seat","common")
} else {
$CreateSpec.parts = @("common")
}
$CurrentSchedule = $BackupAPI.list()
if ($CurrentSchedule.keys.value) {
if($Force -or $PSCmdlet.ShouldContinue($CurrentSchedule.keys.value,'Delete Old Schedule')){
$BackupAPI.delete($CurrentSchedule.keys.value)
} else {
Write-Error "There is an exisiting Schedule. Please delete before Creating a new one."
return
}
}
if ($PSCmdlet.ShouldProcess($BackupID, 'Create New Schedule.')) {
try {
$BackupJob = $BackupAPI.create($BackupID, $CreateSpec)
}
catch {
throw $_.Exception.Message
}
}
if ($BackupJob) {
Write-Host "Backup up Job Created."
return $BackupJob
}
}
End {}
}
Function Get-VCSASchedule {
<#
.NOTES
===========================================================================
Original Created by: Brian Graf
Blog: www.vtagion.com
Twitter: @vBrianGraf
Organization: VMware
Created / Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function will allow you to Get the scheduled backup of your
VCSA appliance. (vSphere 6.7 and higher)
.DESCRIPTION
Use this function to Get the backup schedule for your VCSA appliance.
.EXAMPLE
PS C:\> Get-VCSASchedule
.EXAMPLE
PS C:\> Get-VCSASchedule -ScheduleID 1 -CisServer "vcserver.sphere.local"
.NOTES
Credit goes to @AlanRenouf & @vBrianGraf for sharing the base of this function.
Returns a simplified object with the schedule details.
You must be connected to the CisService for this to work, if you are not connected, the function will prompt you for your credentials
#>
param (
[Parameter(Mandatory=$False,HelpMessage="Will Filter List By ScheduleID")]$ScheduleID,
[Parameter(Mandatory=$false)]$CisServer = $global:DefaultCisServers
)
Begin {
if ($CisServer.IsConnected) {
Write-Verbose "Connected to $($CisServer.Name)"
$connection = $CisServer
} elseif ($CisServer.gettype().name -eq "String") {
Write-Host "Prompting for CIS Server credentials. Connecting to $($CisServer)."
$Connection = Connect-CisServer $CisServer
} elseif ($global:DefaultCisServers) {
$connection = $global:DefaultCisServers
} elseif ($global:DefaultVIServer) {
Write-Host "Prompting for CIS Server credentials. Connecting to $($global:DefaultVIServer.name)."
$Connection = Connect-CisServer $global:DefaultVIServer
}
if (!$Connection) {
Write-Error "It appears you have not created a connection to the CisServer. Please Connect First and try command again. (Connect-CisServer)"
}
}
Process{
if (!(Test-VCSAScheduleSupport)) {
Write-Error "This VCSA does not support Backup Schedules."
return
}
$BackupAPI = Get-CisService -name 'com.vmware.appliance.recovery.backup.schedules'
$Schedules = $BackupAPI.list()
if ($Schedules.count -ge 1) {
$ObjSchedule = @()
foreach ($Schedule in $Schedules) {
$ObjSchedule += $Schedule.values | Select-Object *,@{N = "ID"; e = {"$($schedule.keys.value)"}} -ExpandProperty recurrence_info -ExcludeProperty Help | Select-Object * -ExcludeProperty recurrence_info,Help | Select-Object * -ExpandProperty retention_info | Select-Object * -ExcludeProperty retention_info,Help
}
if ($ScheduleID) {
$ObjSchedule = $ObjSchedule | Where-Object {$_.ID -eq $ScheduleID}
}
return $ObjSchedule
} else {
Write-Information "No Schedule Defined."
}
}
End {}
}
Function Remove-VCSASchedule {
<#
.NOTES
===========================================================================
Original Created by: Brian Graf
Blog: www.vtagion.com
Twitter: @vBrianGraf
Organization: VMware
Created / Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
============================================================================
.SYNOPSIS
This function will remove any scheduled backups of your
VCSA appliance. (vSphere 6.7 and higher)
.DESCRIPTION
Use this function to remove the backup schedule for your VCSA appliance.
.EXAMPLE
PS C:\> Remove-VCSASchedule
.EXAMPLE
PS C:\> Remove-VCSASchedule -ScheduleID 1 -CisServer "vcserver.sphere.local"
.NOTES
Credit goes to @AlanRenouf & @vBrianGraf for sharing the base of this function.
You must be connected to the CisService for this to work, if you are not connected, the function will prompt you for your credentials
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param (
[Parameter(Mandatory=$false)]$ScheduleID = "default",
[Parameter(Mandatory=$false)]$CisServer = $global:DefaultCisServers
)
Begin {
if ($CisServer.IsConnected) {
Write-Verbose "Connected to $($CisServer.Name)"
$connection = $CisServer
} elseif ($CisServer.gettype().name -eq "String") {
Write-Host "Prompting for CIS Server credentials. Connecting to $($CisServer)."
$Connection = Connect-CisServer $CisServer
} elseif ($global:DefaultCisServers) {
$connection = $global:DefaultCisServers
} elseif ($global:DefaultVIServer) {
Write-Host "Prompting for CIS Server credentials. Connecting to $($global:DefaultVIServer.name)."
$Connection = Connect-CisServer $global:DefaultVIServer
}
if (!$Connection) {
Write-Error "It appears you have not created a connection to the CisServer. Please Connect First and try command again. (Connect-CisServer)"
}
}
Process{
if (!(Test-VCSAScheduleSupport)) {
Write-Error "This VCSA does not support Backup Schedules."
return
}
if ($PSCmdlet.ShouldProcess($ScheduleID, "Removes Current Backup Schedule")) {
$BackupAPI = Get-CisService -name 'com.vmware.appliance.recovery.backup.schedules'
$BackupAPI.delete($ScheduleID)
}
}
End {}
}
Function Test-VCSAScheduleSupport {
<#
.NOTES
===========================================================================
Original Created by: Brian Graf
Blog: www.vtagion.com
Twitter: @vBrianGraf
Organization: VMware
Created / Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function will check to see if your VCSA supports Scheduled Backups.
(vSphere 6.7 and higher)
.DESCRIPTION
Use this function to check if your VCSA supports Scheduled Backups.
.EXAMPLE
PS C:\> Test-VCSAScheduleSupport
.EXAMPLE
PS C:\> Test-VCSAScheduleSupport -CisServer "vcserver.sphere.local"
.NOTES
Credit goes to @AlanRenouf & @vBrianGraf for sharing the base of this function.
You must be connected to the CisService for this to work, if you are not connected, the function will prompt you for your credentia
#>
param (
[Parameter(Mandatory=$false)]$CisServer = $global:DefaultCisServers
)
Begin {
if ($CisServer.IsConnected) {
Write-Verbose "Connected to $($CisServer.Name)"
$connection = $CisServer
} elseif ($CisServer.gettype().name -eq "String") {
Write-Host "Prompting for CIS Server credentials. Connecting to $($CisServer)."
$Connection = Connect-CisServer $CisServer
} elseif ($global:DefaultCisServers) {
$connection = $global:DefaultCisServers
} elseif ($global:DefaultVIServer) {
Write-Host "Prompting for CIS Server credentials. Connecting to $($global:DefaultVIServer.name)."
$Connection = Connect-CisServer $global:DefaultVIServer
}
if (!$Connection) {
Write-Error "It appears you have not created a connection to the CisServer. Please Connect First and try command again. (Connect-CisServer)"
}
}
Process{
if ((Get-CisService).name -contains "com.vmware.appliance.recovery.backup.schedules" ) {
Write-Verbose "This VCSA does supports Backup Schedules."
return $true
} else {
Write-Verbose "This VCSA does not support Backup Schedules."
return $false
}
}
End {}
}

View File

@@ -1,4 +1,8 @@
Function Get-ContentLibrary {
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-ContentLibrary {
<#
.NOTES
===========================================================================

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-XVCMStatus {
<#
.NOTES

View File

@@ -34,7 +34,7 @@ Function Get-HostViews {
Throw "No Datastores found.`nIs ""$Datastore"" a Datastore Object?"
}
$allHosts = @()
$DShostsKeys = $allDatastores.extensiondata.host.key.value | sort | get-unique -asstring
$DShostsKeys = $allDatastores.extensiondata.host.key.value | sort-object | get-unique -asstring
$DShosts = foreach ($thisKey in $DShostsKeys) {($allDatastores.extensiondata.host | ? {$_.key.value -eq $thisKey})[0]}
$i = 1
foreach ($DSHost in $DSHosts){

View File

@@ -125,7 +125,7 @@ Begin {
process {
$result = Get-VIEventPlus -Start ((get-date).adddays(-$Days)) -EventType @("VmCreatedEvent", "VmBeingClonedEvent", "VmBeingDeployedEvent","VmRemovedEvent")
$sortedResult = $result | Select CreatedTime, @{N='Cluster';E={$_.ComputeResource.Name}}, @{Name="VMName";Expression={$_.vm.name}}, UserName, @{N='Type';E={$_.GetType().Name}}, FullFormattedMessage | Sort CreatedTime
$sortedResult | where {$_.Cluster -like $ClusterName}
$sortedResult = $result | Select-Object CreatedTime, @{N='Cluster';E={$_.ComputeResource.Name}}, @{Name="VMName";Expression={$_.vm.name}}, UserName, @{N='Type';E={$_.GetType().Name}}, FullFormattedMessage
$sortedResult | where-object {$_.Cluster -like $ClusterName}
}
}

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
@{
ModuleToProcess = 'NSXT.psm1'
ModuleVersion = '1.0.0.0'

View File

@@ -1,4 +1,8 @@
Function Get-NSXTController {
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-NSXTController {
Param (
[parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id
)

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Get-VMEvcMode {
<#
.SYNOPSIS

View File

@@ -1,4 +1,8 @@
Function New-PHAProvider {
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function New-PHAProvider {
<#
.NOTES
===========================================================================

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Recommend-Sizing {
<#
.NOTES

View File

@@ -1,4 +1,13 @@
# Depends on SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
Copyright 2017-2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
#>
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# Depends on SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
# It is assumed that the connection to VC and SRM Server have already been made
Function Get-SrmConfigReportSite {

View File

@@ -1,4 +1,13 @@
# Depends on SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
Copyright 2017-2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
#>
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# Depends on SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
# It is assumed that the connections to active VC and SRM Server have already been made
Import-Module Meadowcroft.SRM -Prefix Srm

View File

@@ -55,7 +55,7 @@ APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Copyright 2017-2021 VMware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

View File

@@ -1,4 +1,13 @@
# SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
Copyright 2017-2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
#>
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
.SYNOPSIS

View File

@@ -1,4 +1,13 @@
# SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
Copyright 2017-2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
#>
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
.SYNOPSIS

View File

@@ -1,4 +1,13 @@
# SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
Copyright 2017-2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
#>
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#
.SYNOPSIS

View File

@@ -1,4 +1,13 @@
#
<#
Copyright 2017-2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
#>
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'Meadowcroft.Srm'
#

View File

@@ -1,3 +1,11 @@
<#
Copyright 2017-2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
#>
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# SRM Helper Methods - https://github.com/benmeadowcroft/SRM-Cmdlets
<#

View File

@@ -1,7 +1,10 @@
Copyright (c) 2017 VMware, Inc. All Rights Reserved.
Copyright (c) 2017-2021 VMware, Inc. All Rights Reserved.
This product is licensed to you under the Apache License version 2.0 (the "License"). You may not use this product except in compliance with the License.
This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file.
Copyright (c) 2021 VMware, Inc. All Rights Reserved.
This product is licensed to you under the BSD-2-Clause License. You may not use this product except in compliance with the License.

View File

@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>SscConnection</Name>
<ViewSelectedBy>
<TypeName>SscConnection</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Width>30</Width>
<Label>Name</Label>
</TableColumnHeader>
<TableColumnHeader>
<Width>30</Width>
<Label>User</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>Authenticated</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>User</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Authenticated</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@@ -0,0 +1,129 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'SaltStackConfig'
#
# Generated by: Brian Wuchner
#
# Generated on: 11/28/2021
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'SaltStackConfig.psm1'
# Version number of this module.
ModuleVersion = '0.0.8'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '9a36e984-2f63-450e-8c14-a6bccb18f87a'
# Author of this module
Author = 'Brian Wuchner'
# Company or vendor of this module
CompanyName = 'VMware'
# Copyright statement for this module
Copyright = '(c) VMware. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Community sourced PowerShell wrapper module for the vRealize Automation SaltStack Config API.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '4.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @('SaltStackConfig.Format.ps1xml')
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @('Connect-SscServer', 'Disconnect-SscServer', 'Get-SscActivity', 'Get-SscData', 'Get-SscJob', 'Get-SscMaster', 'Get-SscMinionCache', 'Get-SscReturn',
'Get-SscSchedule','Get-SscFile','Set-SscFile','New-SscFile','Remove-SscFile','Get-SscLicense','Get-SscvRALicense','Get-SscMinionKey','Set-SscMinionKey',
'Remove-SscMinionKey')
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}

View File

@@ -0,0 +1,640 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Connect-SscServer {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to create the cookie/header to connect to SaltStack Config RaaS API
.DESCRIPTION
This function will allow you to connect to a vRealize Automation SaltStack Config RaaS API.
A global variable will be set with the Servername & Cookie/Header value for use by other functions.
.EXAMPLE
PS C:\> Connect-SscServer -Server 'salt.example.com' -Username 'root' -Password 'VMware1!'
This will default to internal user authentication.
.EXAMPLE
PS C:\> Connect-SscServer -Server 'salt.example.com' -Username 'bwuchner' -Password 'MyPassword1!' -AuthSource 'LAB Directory'
This will use the 'Lab Directory' LDAP authentication source.
.EXAMPLE
PS C:\> Connect-SscServer -Server 'salt.example.com'
This will prompt for credentials
.EXAMPLE
$creds = Get-Credential
PS C:\> Connect-SscServer -Server 'salt.example.com' -Credential $creds -AuthSource 'LAB Directory'
This will connect to the 'LAB Directory' LDAP authentication source using a specified credential.
#>
param(
[Parameter(Mandatory=$true, Position=0)][string]$server,
[Parameter(Mandatory=$true, ParameterSetName='PlainText', Position=1)][string]$username,
[Parameter(Mandatory=$true, ParameterSetName='PlainText', Position=2)][ValidateNotNullOrEmpty()][string]$password,
[Parameter(Mandatory=$false, Position=3)][string]$AuthSource='internal',
[Parameter(Mandatory=$false, ParameterSetName='Credential')][PSCredential]$Credential,
[Parameter(Mandatory=$false)][Switch]$SkipCertificateCheck,
[Parameter(Mandatory=$false)][System.Net.SecurityProtocolType]$SslProtocol
)
if ($PSCmdlet.ParameterSetName -eq 'Credential' -AND $Credential -eq $null) { $Credential = Get-Credential}
if ($Credential) {
$username = $Credential.GetNetworkCredential().username
$password = $Credential.GetNetworkCredential().password
}
if ($SkipCertificateCheck) {
# This if statement is using example code from https://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
} # end if SkipCertificate Check
if ($SslProtocol) {
[System.Net.ServicePointManager]::SecurityProtocol = $SslProtocol
}
$loginBody = @{'username'=$username; 'password'=$password; 'config_name'=$AuthSource}
try {
$webRequest = Invoke-WebRequest -Uri "https://$server/account/login" -SessionVariable ws
$ws.headers.Add('X-Xsrftoken', $webRequest.headers.'x-xsrftoken')
$webRequest = Invoke-WebRequest -Uri "https://$server/account/login" -WebSession $ws -method POST -body (ConvertTo-Json $loginBody)
$webRequestJson = ConvertFrom-JSON $webRequest.Content
$global:DefaultSscConnection = New-Object psobject -property @{ 'SscWebSession'=$ws; 'Name'=$server; 'ConnectionDetail'=$webRequestJson;
'User'=$webRequestJson.attributes.config_name +'\'+ $username; 'Authenticated'=$webRequestJson.authenticated; PSTypeName='SscConnection' }
# Return the connection object
$global:DefaultSscConnection
} catch {
Write-Error ("Failure connecting to $server. " + $_)
} # end try/catch block
}
Function Disconnect-SscServer {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This function clears a previously created cookie/header used to connect to SaltStack Config
.DESCRIPTION
This function will clear the global variable used to connect to the vRealize Automation SaltStack Config RaaS API
.EXAMPLE
PS C:\> Disconnect-SscServer
#>
if ($global:DefaultSscConnection) {
$global:DefaultSscConnection = $null
} else {
Write-Error 'Could not find an existing connection.'
} # end if
}
Function Get-SscData {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to call the SaltStack Config API.
Additional helper functions will call this function, this is where the majority of the logic will happen.
.DESCRIPTION
This function will pass resource/method/arguments to the vRealize Automation SaltStack Config RaaS API.
It depends on a global variable created by Connect-SscServer.
.EXAMPLE
PS C:\> Get-SscData -Resource 'minions' -Method 'get_minion_cache'
#>
param(
[Parameter(Mandatory=$true)][string]$resource,
[Parameter(Mandatory=$true)][string]$method,
[System.Collections.Hashtable]$kwarg
)
if (!$global:DefaultSscConnection) {
Write-Error 'You are not currently connected to any servers. Please connect first using Connect-SscServer.'
return;
} # end if
if (!$kwarg) {
$body = @{'resource'=$resource; 'method'=$method }
} else {
$body = @{'resource'=$resource; 'method'=$method; 'kwarg'=$kwarg }
}
try{
$jsonBody = $(ConvertTo-Json $body -Depth 4 -Compress )
write-debug "JSON Body: $jsonBody"
$output = Invoke-WebRequest -WebSession $global:DefaultSscConnection.SscWebSession -Method POST -Uri "https://$($global:DefaultSscConnection.Name)/rpc" -body $jsonBody -ContentType 'application/json'
$outputJson = (ConvertFrom-Json $output.Content)
if ($outputJson.error) { Write-Error $outputJson.error }
if ($outputJson.warnings) { Write-Warning $outputJson.warnings }
return $outputJson.ret
} catch {
Write-Error $_.Exception.Message
}
}
# Lets include a couple sample/helper functions wrappers
Function Get-SscMaster {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return grain details about the SaltStack Config master node.
.DESCRIPTION
This wrapper function will call Get-SscData master.get_master_grains.
.EXAMPLE
PS C:\> Get-SscMaster
#>
(Get-SscData master get_master_grains).salt.grains
}
Function Get-SscMinionCache {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return the grain property cache of SaltStack Config minions.
.DESCRIPTION
This wrapper function will call Get-SscData minions.get_minion_cache.
.EXAMPLE
PS C:\> Get-SscMinion
#>
(Get-SscData minions get_minion_cache).results
}
Function Get-SscJob {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return configured SatlStack Config jobs.
.DESCRIPTION
This wrapper function will call Get-SscData job.get_jobs.
.EXAMPLE
PS C:\> Get-SscJob
#>
(Get-SscData job get_jobs).results
}
Function Get-SscSchedule {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return schedules for SaltStack Config.
.DESCRIPTION
This wrapper function will call Get-SscData schedule.get.
.EXAMPLE
PS C:\> Get-SscSchedule
#>
(Get-SscData schedule get).results
}
Function Get-SscReturn {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return job results from the job cache based on the provided arguments.
.DESCRIPTION
This wrapper function will call Get-SscData ret.get_returns with either Jid or MinionID.
.EXAMPLE
PS C:\> Get-SscReturn
.EXAMPLE
PS C:\> Get-SscReturn -Jid '20211122160147314949'
.EXAMPLE
PS C:\> Get-SscReturn -MinionID 't147-win22-01.lab.enterpriseadmins.org'
.EXAMPLE
PS C:\> Get-SscReturn -MinionID 't147-win22-01.lab.enterpriseadmins.org' -Jid '20211122160147314949'
#>
param(
[string]$jid,
[string]$MinionID
)
$kwarg = @{}
if ($jid) { $kwarg += @{'jid'=$jid} }
if ($MinionID) { $kwarg += @{'minion_id'=$MinionID} }
(Get-SscData ret get_returns $kwarg).results
}
Function Get-SscActivity {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: November 27, 2021
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return SaltStack Config commands that have been issued.
In the web interface this is similar to the Activity button.
.DESCRIPTION
This wrapper function will call Get-SscData cmd.get_cmds.
.EXAMPLE
PS C:\> Get-SscActivity
#>
(Get-SscData cmd get_cmds).results
}
Function Get-SscFile {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return file contents from the file server based on the provided arguments.
.DESCRIPTION
This wrapper function will call Get-SscData fs get_file and pass in specified saltenv and path parameters.
.EXAMPLE
PS C:\> Get-SscFile -saltenv 'sse' -path '/myfiles/file.sls'
.EXAMPLE
PS C:\> Get-SscFile -fileuuid '5e2483e8-a981-4e8c-9e83-01d1930413db'
#>
param(
[Parameter(Mandatory=$true, ParameterSetName='ByFileUUID', ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][Alias('fileuuid')][string]$uuid,
[Parameter(Mandatory=$true, ParameterSetName='ByFilePath')][string]$saltenv,
[Parameter(Mandatory=$true, ParameterSetName='ByFilePath')][string]$path
)
$kwarg = @{}
if ($uuid) { $kwarg += @{'file_uuid'=$uuid } }
if ($saltenv) {
$kwarg += @{'saltenv'=$saltenv}
$kwarg += @{'path'=$path}
}
if ( Get-SscData fs file_exists $kwarg ) {
Get-SscData fs get_file $kwarg
} else {
if ($uuid) { Write-Error "File with UUID: $uuid not found." } else { Write-Error "File at path $saltenv $path not found." }
}
}
Function Set-SscFile {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will update file contents on the file server based on the provided arguments.
.DESCRIPTION
This wrapper function will call Get-SscData fs update_file and pass in specified fileuuid or saltenv and path parameters.
.EXAMPLE
PS C:\> Set-SscFile -saltenv 'sse' -path '/myfiles/file.sls' "#This is my content. `n#And so is this"
.EXAMPLE
PS C:\> Get-SscFile -saltenv 'sse' -path '/myfiles/file.sls' | Set-SscFile -contenttype 'text/x-yaml'
#>
[cmdletbinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
param(
[Parameter(Mandatory=$true, ParameterSetName='ByFileUUID', ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][Alias('fileuuid')][string]$uuid,
[Parameter(Mandatory=$true, ParameterSetName='ByFilePath')][string]$saltenv,
[Parameter(Mandatory=$true, ParameterSetName='ByFilePath')][string]$path,
[string]$content,
[ValidateSet('text/plain','text/x-python','application/json','text/x-yaml')][string]$contenttype
)
$kwarg = @{}
if ($uuid) { $kwarg += @{'file_uuid'=$uuid } }
if ($saltenv) {
$kwarg += @{'saltenv'=$saltenv}
$kwarg += @{'path'=$path}
}
# if the file exists, get its contents based on the correct parameterset. If it does not exist recommend the correct function.
if ( Get-SscData fs file_exists $kwarg ) {
if ( $PSCmdlet.ParameterSetName -eq 'ByFileUUID' ) {
$currentFile = Get-SscFile -fileuuid $uuid
} else {
$currentFile = Get-SscFile -saltenv $saltenv -path $path
}
} else {
Write-Error "Specified file does not exist, use New-SscFile instead."
return $null
}
if (!$content) { $content = $currentFile.contents }
$kwarg += @{'contents'=$content}
if (!$contenttype) { $contenttype = $currentfile.content_type }
$kwarg += @{'content_type'=$contenttype}
if ($PSCmdlet.ShouldProcess( "$($currentFile.saltenv)$($currentFile.path) ($($currentFile.uuid))" , 'update')) {
Get-SscData fs update_file $kwarg
}
}
Function New-SscFile {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will create a new file on the file server based on the provided arguments.
.DESCRIPTION
This wrapper function will call Get-SscData fs save_file and pass in specified saltenv and path parameters.
.EXAMPLE
PS C:\> New-SscFile -saltenv 'sse' -path '/myfiles/file.sls' -content '#this is my file content' -contenttype 'text/plain'
#>
param(
[Parameter(Mandatory=$true)][string]$saltenv,
[Parameter(Mandatory=$true)][string]$path,
[string]$content,
[ValidateSet('text/plain','text/x-python','application/json','text/x-yaml')][string]$contenttype
)
$kwarg = @{}
$kwarg += @{'saltenv'=$saltenv}
$kwarg += @{'path'=$path}
# if the file exists, get its contents based on the correct parameterset. If it does not exist recommend the correct function.
if ( Get-SscData fs file_exists $kwarg ) {
Write-Error "Specified file already exists, use Set-SscFile instead."
return $null
}
if ($content) { $kwarg += @{'contents'=$content} }
if ($contenttype) {
# if a contenttype is passed to the function we'll use it
$kwarg += @{'content_type'=$contenttype}
} else {
# and finally we'll default to text
$kwarg += @{'content_type' = 'text/plain' }
}
Get-SscData fs save_file $kwarg
}
Function Remove-SscFile {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will delete a specified file from the file server based on the provided arguments.
.DESCRIPTION
This wrapper function will call Get-SscData fs delete_file and pass in specified fileuuid or saltenv and path parameters.
.EXAMPLE
PS C:\> Remove-SscFile -saltenv 'sse' -path '/myfiles/file.sls'
.EXAMPLE
PS C:\> Get-SscFile -saltenv 'sse' -path '/myfiles/file.sls' | Remove-SscFile
#>
[cmdletbinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
param(
[Parameter(Mandatory=$true, ParameterSetName='ByFileUUID', ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][Alias('fileuuid')][string]$uuid,
[Parameter(Mandatory=$true, ParameterSetName='ByFilePath')][string]$saltenv,
[Parameter(Mandatory=$true, ParameterSetName='ByFilePath')][string]$path
)
$kwarg = @{}
if ($uuid) { $kwarg += @{'file_uuid'=$uuid } }
if ($saltenv) {
$kwarg += @{'saltenv'=$saltenv}
$kwarg += @{'path'=$path}
}
if ( Get-SscData fs file_exists $kwarg ) {
if ($PSCmdlet.ShouldProcess( $(if ($uuid) {$uuid} else {"$saltenv $path"}) , 'delete')) {
Get-SscData fs delete_file $kwarg
}
} else {
Write-Error "Specified file does not exist."
return $null
}
}
Function Get-SscLicense {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return license information for SaltStack Config.
.DESCRIPTION
This wrapper function will call Get-SscData license.get_current_license and return the desc property.
.EXAMPLE
PS C:\> Get-SscLicense
#>
(Get-SscData license get_current_license).desc
}
Function Get-SscvRALicense {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return vRealize Automation license information for SaltStack Config.
.DESCRIPTION
This wrapper function will call Get-SscData license.get_vra_license and return the serial and edition property.
.EXAMPLE
PS C:\> Get-SscvRALicense
#>
Get-SscData license get_vra_license
}
Function Get-SscMinionKey {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will return minion key state information for SaltStack Config.
.DESCRIPTION
This wrapper function will call Get-SscData minions.get_minion_key_state and return the minions key states.
Optionally a key state can be provided and the results will be filtered to only return the requested state.
.EXAMPLE
PS C:\> Get-SscMinionKeyState
.EXAMPLE
PS C:\> Get-SscMinionKeyState -key_state pending
#>
param(
[ValidateSet('accepted','rejected','pending','denied')][string]$state
)
$kwarg = @{}
if ($state) { $kwarg.add('key_state',$state) }
(Get-SscData minions get_minion_key_state $kwarg).results
}
Function Set-SscMinionKey {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will set minion key state information for SaltStack Config.
.DESCRIPTION
This wrapper function will call Get-SscData minions.set_minion_key_state and update the states for specific minions.
.EXAMPLE
PS C:\> Get-SscMinionKeyState |?{$_.name -eq 'server2022a'} | Set-SscMinionKeyState -state accept
.EXAMPLE
PS C:\> Set-SscMinionKeyState -master 'salt' -minion 'server2022a' -state reject -confirm:$false
#>
[cmdletbinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string]$master,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string]$minion,
[Parameter(Mandatory, ParameterSetName='accept')][switch]$accept,
[Parameter(Mandatory, ParameterSetName='reject')][switch]$reject
)
begin {
$collection = @()
}
process {
if ($PSCmdlet.ParameterSetName -eq 'accept') { $state = 'accept'}
if ($PSCmdlet.ParameterSetName -eq 'reject') { $state = 'reject'}
if ($PSCmdlet.ShouldProcess("$master : $minion" , $state)) {
$collection += ,@($master, $minion)
}
}
end {
$kwarg = @{}
$kwarg.Add('state', $state)
if ($state -eq 'reject') {$kwarg.Add('include_accepted', $true)}
if ($state -eq 'accept') {$kwarg.Add('include_rejected', $true)}
if ($state -eq 'accept' -OR $state -eq 'reject') {$kwarg.Add('include_denied',$true)}
$kwarg.Add('minions', @( $collection ) )
(Get-SscData minions set_minion_key_state $kwarg).task_ids
}
}
Function Remove-SscMinionKey {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 12, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
This wrapper function will delete a minion key for SaltStack Config.
.DESCRIPTION
This wrapper function will call Get-SscData minions.set_minion_key_state and remove the specified minion keys.
.EXAMPLE
PS C:\> Get-SscMinionKeyState |?{$_.name -eq 'server2022a'} | Remove-SscMinionKeyState
.EXAMPLE
PS C:\> Remove-SscMinionKeyState -master 'salt' -minion 'server2022a' -confirm:$false
#>
[cmdletbinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string]$master,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string]$minion
)
begin {
$collection = @()
}
process {
if ($PSCmdlet.ShouldProcess("$master : $minion" , 'delete')) {
$collection += ,@($master, $minion)
}
}
end {
$kwarg = @{}
$kwarg.Add('state','delete')
$kwarg.Add('minions', @( $collection ) )
(Get-SscData minions set_minion_key_state $kwarg).task_ids
}
}

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Start-UNMAP {
<#
.SYNOPSIS

View File

@@ -1,4 +1,9 @@
Function Get-VAMISummary {
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-VAMISummary {
<#
.NOTES
===========================================================================
@@ -17,7 +22,7 @@
Get-VAMISummary
#>
$systemVersionAPI = Get-CisService -Name 'com.vmware.appliance.system.version'
$results = $systemVersionAPI.get() | select product, type, version, build, install_time
$results = $systemVersionAPI.get() | select product, type, version, build, install_time, releasedate
$systemUptimeAPI = Get-CisService -Name 'com.vmware.appliance.system.uptime'
$ts = [timespan]::fromseconds($systemUptimeAPI.get().toString())
@@ -29,6 +34,7 @@
Version = $results.version;
Build = $results.build;
InstallTime = $results.install_time;
ReleaseDate = $results.releasedate;
Uptime = $uptime
}
$summaryResult
@@ -109,6 +115,7 @@ Function Get-VAMIAccess {
Console = $consoleAccess;
DCUI = $dcuiAccess;
BashShell = $shellAccess.enabled;
BashTimeout = $shellAccess.timeout;
SSH = $sshAccess
}
$accessResult
@@ -122,6 +129,9 @@ Function Get-VAMITime {
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 16, 2020
===========================================================================
.SYNOPSIS
This function retrieves the time and NTP info from VAMI interface (5480)
@@ -131,12 +141,16 @@ Function Get-VAMITime {
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMITime
.NOTES
Modified script to account for Newer VCSA. Script supports 6.5 and 6.7 VCSAs
#>
$systemTimeAPI = Get-CisService -Name 'com.vmware.appliance.system.time'
$systemTimeAPI = ( Get-VAMIServiceAPI -NameFilter "system.time")
$timeResults = $systemTimeAPI.get()
$timeSync = (Get-CisService -Name 'com.vmware.appliance.techpreview.timesync').get()
$timeSyncMode = ( Get-VAMIServiceAPI -NameFilter "timesync").get()
if ($timeSyncMode.mode) {
$timeSyncMode = $timeSync.mode
}
$timeResult = [pscustomobject] @{
Timezone = $timeResults.timezone;
@@ -148,13 +162,84 @@ Function Get-VAMITime {
}
if($timeSyncMode -eq "NTP") {
$ntpServers = (Get-CisService -Name 'com.vmware.appliance.techpreview.ntp').get()
$ntpServers = ( Get-VAMIServiceAPI -NameFilter "ntp").get()
if ($ntpServers.servers) {
$timeResult.NTPServers = $ntpServers.servers
$timeResult.NTPStatus = $ntpServers.status
} else {
$timeResult.NTPServers = $ntpServers
$timeResult.NTPStatus = ( Get-VAMIServiceAPI -NameFilter "ntp").test(( Get-VAMIServiceAPI -NameFilter "ntp").get()).status
}
}
$timeResult
}
Function Set-VAMITimeSync {
<#
.NOTES
===========================================================================
Inspired by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Created by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function sets the time and NTP info from VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return current Time and NTP information
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Set-VAMITimeSync -SyncMode "NTP" -TimeZone "US/Pacific" -NTPServers "10.0.0.10,10.0.0.11,10.0.0.12"
.NOTES
Create script to Set NTP for Newer VCSA. Script supports 6.7 VCSAs
#>
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Disabled', 'NTP', 'Host')]
[String]$SyncMode,
[Parameter(Mandatory=$False,HelpMessage="TimeZone Name needs to be in Posix Naming / Unix format")]
[String]$TimeZone,
[Parameter(Mandatory=$false,HelpMessage="NTP Servers need to be either a string separated by ',' or an array of servers")]
$NTPServers
)
$timeSyncMode = ( Get-VAMIServiceAPI -NameFilter "timesync").get()
if ($timeSyncMode.gettype().name -eq "PSCustomObject") {
if ($SyncMode.ToUpper() -ne $timeSyncMode.mode.toupper()) {
$timesyncapi = (Get-VAMIServiceAPI -NameFilter "timesync")
$timesyncconfig = $timesyncapi.help.set.config.createexample()
$timesyncconfig = $Sync
$timesyncapi.set($timesyncconfig)
}
} else {
if ($SyncMode.ToUpper() -ne $timeSyncMode.toupper()) {
$timesyncapi = (Get-VAMIServiceAPI -NameFilter "timesync")
$timesyncapi.set($Sync)
}
if ($NTPServers) {
$ntpapi = (Get-VAMIServiceAPI -NameFilter "ntp")
if ($NTPServers.gettype().Name -eq "String") {
$NTPServersArray = ($NTPServers -split ",").trim()
} else {
$NTPServersArray = $NTPServers
}
if ($NTPServersArray -ne $ntpapi.get()) {
$ntpapi.set($NTPServersArray)
}
}
if ($TimeZone) {
$timezoneapi = (Get-VAMIServiceAPI -NameFilter "timezone")
if ($TimeZone -ne ($timezoneapi.get())) {
$timezoneapi.set($TimeZone)
}
}
}
}
Function Get-VAMINetwork {
<#
.NOTES
@@ -163,6 +248,9 @@ Function Get-VAMINetwork {
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Modifed by: Michael Dunsdon, Mathieu Allegret
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function retrieves network information from VAMI interface (5480)
@@ -172,31 +260,35 @@ Function Get-VAMINetwork {
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMINetwork
.NOTES
Modified script to account for Newer VCSA. Script supports 6.5 and 6.7 VCSAs
#>
$netResults = @()
$Hostname = (Get-CisService -Name 'com.vmware.appliance.networking.dns.hostname').get()
$dns = (Get-CisService -Name 'com.vmware.appliance.networking.dns.servers').get()
$Hostname = (Get-VAMIServiceAPI -NameFilter "dns.hostname").get()
$dns = (Get-VAMIServiceAPI -NameFilter "dns.servers").get()
Write-Host "Hostname: " $hostname
Write-Host "DNS Servers: " $dns.servers
$interfaces = (Get-CisService -Name 'com.vmware.appliance.networking.interfaces').list()
$interfaces = (Get-VAMIServiceAPI -NameFilter "interfaces").list()
foreach ($interface in $interfaces) {
$ipv4API = (Get-CisService -Name 'com.vmware.appliance.techpreview.networking.ipv4')
$spec = $ipv4API.Help.get.interfaces.CreateExample()
$spec+= $interface.name
$ipv4result = $ipv4API.get($spec)
$ipv4API = (Get-VAMIServiceAPI -NameFilter "ipv4")
if ($ipv4API.help.get.psobject.properties.name -like "*_*") {
$ipv4result = $ipv4API.get($interface.Name)
$Updateable = $ipv4result.configurable
} else {
$ipv4result = $ipv4API.get(@($interface.Name))
$Updateable = $ipv4result.updateable
}
$interfaceResult = [pscustomobject] @{
Inteface = $interface.name;
MAC = $interface.mac;
Status = $interface.status;
Mode = $ipv4result.mode;
IP = $ipv4result.address;
Prefix = $ipv4result.prefix;
Gateway = $ipv4result.default_gateway;
Updateable = $ipv4result.updateable
Hostname = $Hostname
Inteface = $interface.name
MAC = $interface.mac
Status = $interface.status
Mode = $ipv4result.mode
IP = $ipv4result.address
Prefix = $ipv4result.prefix
Gateway = $ipv4result.default_gateway
DNSServers = $dns.servers
Updateable = $Updateable
}
$netResults += $interfaceResult
}
@@ -224,8 +316,8 @@ Function Get-VAMIDisks {
$storageAPI = Get-CisService -Name 'com.vmware.appliance.system.storage'
$disks = $storageAPI.list()
foreach ($disk in $disks | sort {[int]$_.disk.toString()}) {
$disk | Select Disk, Partition
foreach ($disk in $disks | Sort-Object {[int]$_.disk.toString()}) {
$disk | Select-Object Disk, Partition
}
}
@@ -286,6 +378,9 @@ Function Get-VAMIStorageUsed {
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 16, 2020
===========================================================================
.SYNOPSIS
This function retrieves the individaul OS partition storage utilization
@@ -295,70 +390,49 @@ Function Get-VAMIStorageUsed {
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIStorageUsed
.NOTES
Modified script to account for Newer VCSA. Script supports 6.5 and 6.7 VCSAs.
Also modifed the static list of filesystems to be more dynamic in nature to account for the differences in VCSA versions.
#>
$monitoringAPI = Get-CisService 'com.vmware.appliance.monitoring'
$querySpec = $monitoringAPI.help.query.item.CreateExample()
# List of IDs from Get-VAMIStatsList to query
$querySpec.Names = @(
"storage.used.filesystem.autodeploy",
"storage.used.filesystem.boot",
"storage.used.filesystem.coredump",
"storage.used.filesystem.imagebuilder",
"storage.used.filesystem.invsvc",
"storage.used.filesystem.log",
"storage.used.filesystem.netdump",
"storage.used.filesystem.root",
"storage.used.filesystem.updatemgr",
"storage.used.filesystem.vcdb_core_inventory",
"storage.used.filesystem.vcdb_seat",
"storage.used.filesystem.vcdb_transaction_log",
"storage.totalsize.filesystem.autodeploy",
"storage.totalsize.filesystem.boot",
"storage.totalsize.filesystem.coredump",
"storage.totalsize.filesystem.imagebuilder",
"storage.totalsize.filesystem.invsvc",
"storage.totalsize.filesystem.log",
"storage.totalsize.filesystem.netdump",
"storage.totalsize.filesystem.root",
"storage.totalsize.filesystem.updatemgr",
"storage.totalsize.filesystem.vcdb_core_inventory",
"storage.totalsize.filesystem.vcdb_seat",
"storage.totalsize.filesystem.vcdb_transaction_log"
)
$querySpec.Names = ($monitoringAPI.list() | Where-Object {($_.name -like "*storage.used.filesystem*") -or ($_.name -like "*storage.totalsize.filesystem*") } | Select-Object id | Sort-Object -Property id).id.value
# Tuple (Filesystem Name, Used, Total) to store results
$storageStats = @{
"archive"=@{"name"="/storage/archive";"used"=0;"total"=0};
"autodeploy"=@{"name"="/storage/autodeploy";"used"=0;"total"=0};
"boot"=@{"name"="/boot";"used"=0;"total"=0};
"coredump"=@{"name"="/storage/core";"used"=0;"total"=0};
"core"=@{"name"="/storage/core";"used"=0;"total"=0};
"imagebuilder"=@{"name"="/storage/imagebuilder";"used"=0;"total"=0};
"invsvc"=@{"name"="/storage/invsvc";"used"=0;"total"=0};
"log"=@{"name"="/storage/log";"used"=0;"total"=0};
"netdump"=@{"name"="/storage/netdump";"used"=0;"total"=0};
"root"=@{"name"="/";"used"=0;"total"=0};
"updatemgr"=@{"name"="/storage/updatemgr";"used"=0;"total"=0};
"vcdb_core_inventory"=@{"name"="/storage/db";"used"=0;"total"=0};
"vcdb_seat"=@{"name"="/storage/seat";"used"=0;"total"=0};
"vcdb_transaction_log"=@{"name"="/storage/dblog";"used"=0;"total"=0}
"db"=@{"name"="/storage/db";"used"=0;"total"=0};
"seat"=@{"name"="/storage/seat";"used"=0;"total"=0};
"dblog"=@{"name"="/storage/dblog";"used"=0;"total"=0};
"swap"=@{"name"="swap";"used"=0;"total"=0}
}
$querySpec.interval = "DAY1"
$querySpec.function = "MAX"
$querySpec.start_time = ((get-date).AddDays(-1))
$querySpec.start_time = ((Get-Date).AddDays(-1))
$querySpec.end_time = (Get-Date)
$queryResults = $monitoringAPI.query($querySpec) | Select * -ExcludeProperty Help
$queryResults = $monitoringAPI.query($querySpec) | Select-Object * -ExcludeProperty Help
foreach ($queryResult in $queryResults) {
# Update hash if its used storage results
if($queryResult.name -match "used") {
$key = (($queryResult.name).toString()).split(".")[-1]
$key = ((($queryResult.name).toString()).split(".")[-1]) -replace "coredump","core" -replace "vcdb_","" -replace "core_inventory","db" -replace "transaction_log","dblog"
$value = [Math]::Round([int]($queryResult.data[1]).toString()/1MB,2)
if($queryResult.name -match "used") {
$storageStats[$key]["used"] = $value
# Update hash if its total storage results
} else {
$key = (($queryResult.name).toString()).split(".")[-1]
$value = [Math]::Round([int]($queryResult.data[1]).toString()/1MB,2)
$storageStats[$key]["total"] = $value
}
}
@@ -406,7 +480,6 @@ Function Get-VAMIService {
if($Name -ne "") {
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
try {
$serviceStatus = $vMonAPI.get($name,0)
$serviceString = [pscustomobject] @{
@@ -423,7 +496,6 @@ Function Get-VAMIService {
} else {
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
$services = $vMonAPI.list_details()
$serviceResult = @()
foreach ($key in $services.keys | Sort-Object -Property Value) {
$serviceString = [pscustomobject] @{
@@ -470,8 +542,8 @@ Function Start-VAMIService {
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
try {
Write-Host "Starting $name service ..."
$vMonAPI.start($name)
Write-Host "Starting $Name service ..."
$vMonAPI.start($Name)
} catch {
Write-Error $Error[0].exception.Message
}
@@ -507,8 +579,8 @@ Function Stop-VAMIService {
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
try {
Write-Host "Stopping $name service ..."
$vMonAPI.stop($name)
Write-Host "Stopping $Name service ..."
$vMonAPI.stop($Name)
} catch {
Write-Error $Error[0].exception.Message
}
@@ -556,6 +628,9 @@ Function Get-VAMIUser {
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 16, 2020
===========================================================================
.SYNOPSIS
This function retrieves VAMI local users using VAMI interface (5480)
@@ -565,6 +640,8 @@ Function Get-VAMIUser {
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIUser
.NOTES
Modified script to account for Newer VCSA. Script supports 6.5 and 6.7 VCSAs.
#>
param(
[Parameter(
@@ -575,42 +652,57 @@ Function Get-VAMIUser {
[String]$Name
)
$userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user'
$userAPI = Get-VAMIServiceAPI -NameFilter "accounts"
$UserResults = @()
$userResults = @()
if($Name -ne "") {
# Get a list of users
try {
$user = $userAPI.get($name)
$userString = [pscustomobject] @{
User = $user.username
Name = $user.fullname
Email = $user.email
Status = $user.status
PasswordStatus = $user.passwordstatus
Role = $user.role
}
$userResults += $userString
$Users = $UserAPI.list()
} catch {
Write-Error $Error[0].exception.Message
write-error $_
}
# Apply filtering if Name input is provided
if ($Name -ne '' -AND $Name -ne $null) {
# For 6.5 API, the username is part of the list returnset; for 6.7/7.x API the value from the list is the username. Because of this we will use an OR filter to account for either case.
$Users = $Users | Where-Object {$_.username -eq $name -OR $_.value -eq $name}
}
if ($Users.status) {
# This is for 6.5 API, which has a status property; in newer API response there is an enabled property with values of True/False
foreach ($User in $Users) {
$UserString = [pscustomobject] @{
User = $User.username
Name = $User.fullname
Email = $User.email
Enabled = if ($User.status -eq 'enabled' ) { $true } else { $false }
Status = $User.status
LastPasswordChange = $null
PasswordExpiresAt = $null
PasswordStatus = $User.passwordstatus
Roles = @($User.role)
}
$UserResults += $UserString
}
} else {
$users = $userAPI.list()
foreach ($user in $users) {
$userString = [pscustomobject] @{
User = $user.username
Name = $user.fullname
Email = $user.email
Status = $user.status
PasswordStatus = $user.passwordstatus
Role = $user.role
# This is for 6.7/7.0+ API response
foreach ($User in $Users) {
$UserInfo = $userAPI.get($User.Value)
$UserString = [pscustomobject] @{
User = $User.value
Name = $UserInfo.fullname
Email = $UserInfo.email
Enabled = $UserInfo.enabled
Status = if ($userInfo.enabled ) { 'enabled' } else { 'disabled' }
LastPasswordChange = $UserInfo.last_password_change
PasswordExpiresAt = $UserInfo.password_expires_at
PasswordStatus = if ($UserInfo.has_password) { if ((!!$UserInfo.password_expires_at) -and ( (Get-Date) -lt [datetime]$UserInfo.password_expires_at)) {'valid'} else {'expired'}} else { 'notset'}
Roles = $UserInfo.roles
}
$userResults += $userString
$UserResults += $UserString
}
}
$userResults
$UserResults
}
Function New-VAMIUser {
@@ -621,6 +713,9 @@ Function New-VAMIUser {
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 16, 2020
===========================================================================
.SYNOPSIS
This function to create new VAMI local user using VAMI interface (5480)
@@ -629,46 +724,138 @@ Function New-VAMIUser {
Function to create a new VAMI local user
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
New-VAMIUser -name lamw -fullname "William Lam" -role "operator" -email "lamw@virtuallyghetto.com" -password "VMware1!"
New-VAMIUser -name lamw -fullname "William Lam" -role "operator" -email "lamw@virtuallyghetto.com" -password "VMware1!" -passwordexpires -passwordexpiresat "1/1/1970" -maxpasswordage 90
.NOTES
Modified script to account for Newer VCSA. Script supports 6.5 and 6.7 VCSAs.
Also added new Parameters to script.
#>
param(
[Parameter(
Mandatory=$true)
]
[String]$name,
[Parameter(
Mandatory=$true)
]
[String]$fullname,
[Parameter(
Mandatory=$true)
]
[ValidateSet("admin","operator","superAdmin")][String]$role,
[Parameter(
Mandatory=$false)
]
[String]$email="",
[Parameter(
Mandatory=$true)
]
[String]$password
[Parameter(Mandatory=$true)]
[String]$Name,
[Parameter(Mandatory=$true)]
[String]$FullName,
[Parameter(Mandatory=$true)]
[ValidateSet("admin","operator","superAdmin")]
[String]$Role,
[Parameter(Mandatory=$false)]
[String]$Email="",
[Parameter(Mandatory=$true)]
[String]$Password,
[Parameter(Mandatory=$false)]
[switch]$PasswordExpires,
[Parameter(Mandatory=$false)]
[String]$PasswordExpiresAt = $null,
[Parameter(Mandatory=$false)]
[String]$MaxPasswordAge = 90
)
$userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user'
$createSpec = $userAPI.Help.add.config.CreateExample()
$userAPI = Get-VAMIServiceAPI -NameFilter "accounts"
if ($userAPI.name -eq 'com.vmware.appliance.techpreview.localaccounts.user') {
$CreateSpec = $UserAPI.Help.add.config.Create()
} else {
$CreateSpec = $UserAPI.Help.create.config.Create()
}
$createSpec.username = $name
$createSpec.fullname = $fullname
$createSpec.role = $role
$createSpec.email = $email
$createSpec.password = [VMware.VimAutomation.Cis.Core.Types.V1.Secret]$password
$CreateSpec.email = $Email
$CreateSpec.password = [VMware.VimAutomation.Cis.Core.Types.V1.Secret]$Password
if ($CreateSpec.psobject.properties.name -contains "username") {
# This is for 6.5 API
$CreateSpec.username = $Name
$CreateSpec.fullname = $FullName
$CreateSpec.role = $Role
try {
Write-Host "Creating new user $name ..."
$userAPI.add($createSpec)
Write-Host "Creating new user $Name ..."
$UserAPI.add($CreateSpec)
} catch {
Write-Error $Error[0].exception.Message
}
} else {
# This is for 6.7/7.0+ API
$CreateSpec.full_name = $FullName
$CreateSpec.roles = @($Role)
$CreateSpec.password_expires = [string]$PasswordExpires
$CreateSpec.password_expires_at = $PasswordExpiresAt
$CreateSpec.max_days_between_password_change = $MaxPasswordAge
try {
Write-Host "Creating new user $Name ..."
$UserAPI.create($Name, $CreateSpec)
} catch {
Write-Error $_
}
}
}
Function Update-VAMIUser {
<#
.NOTES
===========================================================================
Inspired by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Created by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function to update fields of a VAMI local user using VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to update fields of a VAMI local user
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Update-VAMIUser -name lamw -fullname "William Lam" -role "operator" -email "lamw@virtuallyghetto.com" -password "VMware1!" -passwordexpires -passwordexpiresat "1/1/1970" -maxpasswordage 90
.NOTES
Created script to allow updating of an exisiting user account. Script supports 6.5 and 6.7 VCSAs.
#>
param(
[Parameter(Mandatory=$true)]
[String]$Name,
[Parameter(Mandatory=$false)]
[String]$FullName,
[Parameter(Mandatory=$false)]
[ValidateSet("admin","operator","superAdmin")]
[String]$Role,
[Parameter(Mandatory=$false)]
[String]$Email="",
[Parameter(Mandatory=$false)]
[String]$Password = $null,
[Parameter(Mandatory=$false)]
[switch]$PasswordExpires,
[Parameter(Mandatory=$false)]
[String]$PasswordExpiresAt = $null,
[Parameter(Mandatory=$false)]
[String]$MaxPasswordAge = 90
)
$userAPI = Get-VAMIServiceAPI -NameFilter "accounts"
$UpdateSpec = $UserAPI.Help.set.config.CreateExample()
$UpdateSpec.fullname = $FullName
$UpdateSpec.role = $Role
$UpdateSpec.email = $Email
if ($UpdateSpec.psobject.properties.name -contains "username") {
$UpdateSpec.username = $Name
try {
Write-Host "Updating Settings for user $Name ..."
$UserAPI.set($UpdateSpec)
} catch {
Write-Error $Error[0].exception.Message
}
} else {
$UpdateSpec.password = [VMware.VimAutomation.Cis.Core.Types.V1.Secret]$Password
$UpdateSpec.password_expires = $PasswordExpires
$UpdateSpec.password_expires_at = $PasswordExpiresAt
$UpdateSpec.max_days_between_password_change = $MaxPasswordAge
try {
Write-Host "Updating Settings for user $Name ..."
$UserAPI.update($Name, $UpdateSpec)
} catch {
Write-Error $Error[0].exception.Message
}
}
}
Function Remove-VAMIUser {
@@ -679,6 +866,9 @@ Function Remove-VAMIUser {
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Modifed by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function to remove VAMI local user using VAMI interface (5480)
@@ -688,23 +878,18 @@ Function Remove-VAMIUser {
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIAccess
.NOTES
Modified script to account for Newer VCSA. Script supports 6.5 and 6.7 VCSAs.
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter(
Mandatory=$true)
]
[String]$name,
[Parameter(
Mandatory=$false)
]
[boolean]$confirm=$false
[Parameter(Mandatory=$true)]
[String]$Name
)
if(!$confirm) {
$answer = Read-Host -Prompt "Do you want to delete user $name (Y or N)"
if($answer -eq "Y" -or $answer -eq "y") {
$userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user'
Begin {}
Process{
if($PSCmdlet.ShouldProcess($Name,'Delete')) {
$userAPI = Get-VAMIServiceAPI -NameFilter "accounts"
try {
Write-Host "Deleting user $name ..."
$userAPI.delete($name)
@@ -713,4 +898,41 @@ Function Remove-VAMIUser {
}
}
}
End{}
}
Function Get-VAMIServiceAPI {
<#
.NOTES
===========================================================================
Inspired by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
Created by: Michael Dunsdon
Twitter: @MJDunsdon
Date: September 21, 2020
===========================================================================
.SYNOPSIS
This function returns the Service Api Based on a String of Service Name.
.DESCRIPTION
Function to find and get service api based on service name string
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIUser -NameFilter "accounts"
.NOTES
Script supports 6.5 and 6.7 VCSAs.
Function Gets all Service Api Names and filters the list based on NameFilter
If Multiple Serivces are returned it takes the Top one.
#>
param(
[Parameter(Mandatory=$true)]
[String]$NameFilter
)
$ServiceAPI = Get-CisService | Where-Object {$_.name -like "*$($NameFilter)*"}
if (($ServiceAPI.count -gt 1) -and $NameFilter) {
$ServiceAPI = ($ServiceAPI | Sort-Object -Property Name)[0]
}
return $ServiceAPI
}

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-VCHAConfig {
<#
.NOTES

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-VCSAPasswordPolicy {
<#
.DESCRIPTION Retrieves vCenter Server Appliance SSO and Local OS Password Policy Configuration

View File

@@ -0,0 +1,7 @@
# Example module for using SecretManagement and SecretStore to save PowerCLI credentials
This module demonstrates how users can use the the Microsoft.PowerShell.SecretManagement and Microsoft.PowerShell.SecretStore modules to save their PowerCLI credentials.
The module supports PowerShell 5.1 and PowerShell 7.0 and above.

View File

@@ -0,0 +1,138 @@
#
# Module manifest for module 'VMware.VISecret'
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'VMware.VISecret.psm1'
# Version number of this module.
ModuleVersion = '1.0.0.0'
# Supported PSEditions
CompatiblePSEditions = @('Desktop', 'Core')
# ID used to uniquely identify this module
GUID = '66124b00-4095-4a1f-9940-f91622009b15'
# Author of this module
Author = 'VMware'
# Company or vendor of this module
CompanyName = 'VMware'
# Copyright statement for this module
Copyright = 'Copyright (c) VMware, Inc. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Module to enable easy use of Microsoft.PowerShell.SecretManagement module in VMware context'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '5.1'
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @(
@{"ModuleName"="VMware.VimAutomation.Core";"ModuleVersion"="1.0.0.0"}
@{"ModuleName"="Microsoft.PowerShell.SecretManagement";"ModuleVersion"="1.1.2"}
@{"ModuleName"="Microsoft.PowerShell.SecretStore";"ModuleVersion"="1.0.6"}
)
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
#FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @(
'Initialize-VISecret',
'New-VISecret',
'Get-VISecret',
'Remove-VISecret',
'Connect-VIServerWithSecret'
)
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = @()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
# Prerelease string of this module
# Prerelease = ''
# Flag to indicate whether the module requires explicit user acceptance for install/update/save
# RequireLicenseAcceptance = $false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}

View File

@@ -0,0 +1,314 @@
<#
.SYNOPSIS
This cmdlet downloads the dependencies and intializes the default settings of the VISecret module
.PARAMETER Vault
The vault to save the credentials to. The default value is "VMwareSecretStore"
.DESCRIPTION
This cmdlet downloads the dependecies and initializes the default settings of the VISecret module.
It uses Microsoft.PowerShell.SecretStore as a default vault and sets it in no password mode, so that
the credentials are encrypted, but the user is not prompted for a password. If you want to use a different
vault or to use it with a password you should initialize those settings manually and not use this cmdlet.
.EXAMPLE
PS C:\> Initialize-VISecret
Initializes the default settings of the VISecret module
#>
function Initialize-VISecret {
[CmdletBinding()]
param(
[string]$Vault = "VMwareSecretStore"
)
process {
Set-SecretStoreConfiguration -Scope CurrentUser -Authentication None -Interaction None -Confirm:$false
Register-SecretVault -Name $Vault -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault
}
}
<#
.SYNOPSIS
This cmdlet saves new credential in the secret vault or updates it if it already exists.
.DESCRIPTION
This cmdlet saves new credential in the secret vault or updates it if it already exists.
.PARAMETER Server
The IP address or the hostname of the server to save the credential for
.PARAMETER Password
The password to be saved in the secret vault
.PARAMETER SecureStringPassword
The SecureString password to be saved in the secret vault
.PARAMETER User
The username for which to save the credential
.PARAMETER Vault
The vault to save the credential to. The default value is "VMwareSecretStore"
.EXAMPLE
PS C:\> New-VISecret -Server 10.10.10.10 -User administrator@vsphere.local -password pass
Saves the password for the administrator@vsphere.local user on the 10.10.10.10 server in the secret vault
#>
function New-VISecret {
[CmdletBinding()]
[Alias("Set-VISecret")]
param (
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[string]$User,
[string]$Password,
[securestring]$SecureStringPassword,
[string]$Vault
)
begin {
if ([string]::IsNullOrWhiteSpace($password) -and (-not $secureStringPassword)) {
Throw "Either Password or SecureStringPassword parameter needs to be specified"
}
if (-not [string]::IsNullOrWhiteSpace($password) -and $secureStringPassword) {
Throw "Password and SecureStringPassword parameters cannot be both specified at the same time"
}
}
process {
$params = @{
"Name" = "VISecret|"+$server+"|"+$User
}
if ($password) {
$params += @{"Secret" = $password}
} elseif ($secureStringPassword) {
$params += @{"SecureStringSecret" = $secureStringPassword}
} elseif ($Vault) {
$params += @{"Vault" = $Vault}
}
Set-Secret @params
}
}
<#
.SYNOPSIS
Retrieves a credential from the secret store vault.
.DESCRIPTION
Retrieves a credential from the secret store vault.
.PARAMETER Server
The IP address or the hostname of the server to retrieve the credential for
.PARAMETER User
The username for which to retrieve the credential
.PARAMETER AsPlainText
Specifies that a credential should be returned as a String (in plain text) instead of a SecureString.
To ensure security, you should avoid using plaintext strings whenever possible.
.PARAMETER Vault
The vault to retrieve the credential from. The default value is "VMwareSecretStore"
.EXAMPLE
PS C:\> $securePassword = Get-VISecret -Server 10.10.10.10 -User administrator@vsphere.local
Retrieves the password for the administrator@vsphere.local user on the 10.10.10.10 server from the secret vault
#>
function Get-VISecret {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[string]$User,
[switch]$AsPlainText,
[string]$Vault
)
process {
$params = @{
"Name" = "VISecret|"+$server+"|"+$User
}
if ($AsPlainText.IsPresent) {
$params += @{"AsPlainText" = $AsPlainText.ToBool()}
} elseif ($Vault) {
$params += @{"Vault" = $Vault}
}
Get-Secret @params
}
}
<#
.SYNOPSIS
Removes a credential from the vault.
.DESCRIPTION
Removes a credential from the vault.
.PARAMETER Server
The IP address or the hostname of the server to remove the credential for
.PARAMETER User
The username for which to remove the credential
.PARAMETER Vault
The vault to remove the credential from. The default value is "VMwareSecretStore"
.EXAMPLE
PS C:\> Remove-VISecret -Server 10.10.10.10 -User administrator@vsphere.local
Removes the password for the administrator@vsphere.local user on the 10.10.10.10 server from the vault
#>
function Remove-VISecret {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[string]$User,
[string]$Vault
)
process {
$params = @{
"Name" = "VISecret|"+$server+"|"+$User
}
if ($Vault) {
$params += @{"Vault" = $Vault}
}
Remove-Secret @params
}
}
<#
.SYNOPSIS
This cmdlet establishes a connection to a vCenter Server system.
.DESCRIPTION
This cmdlet establishes a connection to a vCenter Server system.
If a credential object or username and password the cmdlet uses them to connect and if the
-SaveCredential parameter is specified saves them in the vault. If only username
is specified the cmdlet uses the server name and the user name to search for the password in the
vault.
.PARAMETER Server
Specifies the IP address or the DNS name of the vSphere server to which you want to connect.
.PARAMETER User
Specifies the user name you want to use for authenticating with the server.
.PARAMETER Password
Specifies the password you want to use for authenticating with the server.
.PARAMETER Credential
Specifies a PSCredential object that contains credentials for authenticating with the server.
.PARAMETER AllLinked
Indicates whether you want to connect to vCenter Server in linked mode. If you specify $true
for the -AllLinked parameter and the server to which you want to connect is a part of a federation
vCenter Server, you'll be connected to all members of the linked vCenter Server. To use this
option, PowerCLI must be configured to work in multiple servers connection mode. To configure
PowerCLI to support multiple servers connection, specify Multiple for the DefaultVIServerMode
parameter of the Set-PowerCLIConfiguration cmdlet.
.PARAMETER Force
Suppresses all user interface prompts during the cmdlet execution.
.PARAMETER NotDefault
Indicates that you do not want to include the server to which you connect into the $defaultVIServers variable.
.PARAMETER Port
Specifies the port on the server you want to use for the connection.
.PARAMETER Protocol
Specifies the Internet protocol you want to use for the connection. It can be either http or https.
.PARAMETER SaveCredentials
Indicates that you want to save the specified credentials in the vault.
.PARAMETER Vault
The vault to save the credential to. The default value is "VMwareSecretStore"
.EXAMPLE
Connect-VIServer -Server 10.10.10.10 -User administrator@vsphere.local
Connects to a vSphere server using the saved credential for the specified user
.EXAMPLE
Connect-VIServer -Server 10.10.10.10 -User administrator@vsphere.local -Password pass -SaveCredential
Connects to a vSphere server using the specified username and password and saves them in the vault
#>
function Connect-VIServerWithSecret {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$Server,
[string]$User,
[string]$Password,
[pscredential]$Credential,
[switch]$AllLinked,
[switch]$Force,
[switch]$NotDefault,
[int]$Port,
[string]$Protocol,
[switch]$SaveCredentials,
[string]$Vault
)
begin {
if ([string]::IsNullOrWhiteSpace($User) -and (-not $Credential)) {
if ($global:defaultUser) {
$User = $global:defaultUser
} else {
Throw "Either User or Credential parameters needs to be specified"
}
}
if ((-not [string]::IsNullOrWhiteSpace($User) -or -not [string]::IsNullOrWhiteSpace($Password)) -and $Credential) {
Throw "User/Password and Credential parameters cannot be both specified at the same time"
}
}
process {
$params = @{
"Server" = $Server
"AllLinked" = $AllLinked
"Force" = $Force
"NotDefault" = $NotDefault
}
if ($Protocol) {
$params += @{"Protocol" = $Protocol}
}
if ($Port) {
$params += @{"Port" = $Port}
}
if ($User) {
if (-not $Password) {
if ($Vault) {
$secret = Get-Secret -Name ("VISecret|"+$server+"|"+$User) -Vault $Vault -ErrorAction SilentlyContinue
} else {
$secret = Get-Secret -Name ("VISecret|"+$server+"|"+$User) -ErrorAction SilentlyContinue
}
if (-not $secret) {
Throw "No password has been found for this server and user in the password vault"
}
$Credential = New-Object System.Management.Automation.PSCredential ($User, $secret)
}
else {
$securePass = ConvertTo-SecureString -String $Password -AsPlainText
$Credential = New-Object System.Management.Automation.PSCredential ($User, $securePass)
}
}
$params += @{"Credential" = $Credential}
Connect-VIServer @params
if ($SaveCredentials) {
New-VISecret -Server $Server -User $User -SecureStringPassword $Credential.Password -Vault $Vault
}
}
}

View File

@@ -1,4 +1,8 @@
function Get-VMCPSettings {
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Get-VMCPSettings {
<#
.NOTES
===========================================================================

View File

@@ -1,4 +1,8 @@
Function Get-CSPAccessToken {
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-CSPAccessToken {
<#
.NOTES
===========================================================================

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'VMware.Community.CISTag'
#

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Get-CISTag {
<#
.SYNOPSIS

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Connect-DRaas {
<#
.NOTES

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'VMware.HCX'
#

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Connect-HcxServer {
<#
.NOTES

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>SkylineConnection</Name>
<ViewSelectedBy>
<TypeName>SkylineConnection</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Width>30</Width>
<Label>Name</Label>
</TableColumnHeader>
<TableColumnHeader>
<Width>30</Width>
<Label>APIKey</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>CSPName</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>APIKey</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>CSPName</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>

View File

@@ -0,0 +1,128 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'VMware.Skyline.InsightsApi'
#
# Generated by: Brian Wuchner
#
# Generated on: 2/21/2022
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'VMware.Skyline.InsightsApi.psm1'
# Version number of this module.
ModuleVersion = '1.0.1'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '4dfcb1e5-69b9-405d-aecd-06119ec12649'
# Author of this module
Author = 'Brian Wuchner'
# Company or vendor of this module
CompanyName = 'VMware'
# Copyright statement for this module
Copyright = '(c) VMware. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Community sourced PowerShell wrapper module for the Skyline Insights API.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '4.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @('VMware.Skyline.InsightsApi.Format.ps1xml')
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @('Connect-SkylineInsights','Disconnect-SkylineInsights','Invoke-SkylineInsightsApi','Get-SkylineFinding',
'Get-SkylineAffectedObject','Format-SkylineResult','Start-SkylineInsightsApiExplorer')
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}

View File

@@ -0,0 +1,422 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Connect-SkylineInsights {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 21, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to create the auth header to connect to Skyline Insights API
.DESCRIPTION
This function will allow you to connect to a Skyline Insights API.
A global variable will be set with the Servername & Header value for use by other functions.
.EXAMPLE
PS C:\> Connect-SkylineInsights -apiKey 'my-key-from-csp'
This will use the provided API key to create a connection to Skyline Insights.
.EXAMPLE
PS C:\> Connect-SkylineInsights -apiKey 'my-key-from-csp' -SaveCredentials
This will use the PowerCLI VICredentialStore Item to save the provided API key. On next use this key will be provided automatically.
#>
param(
[string]$apiKey,
[switch]$SaveCredentials,
[Parameter(DontShow)]$cspApi = 'console.cloud.vmware.com',
[Parameter(DontShow)]$skylineApi = 'skyline.vmware.com'
)
if ($PSEdition -eq 'Core' -And $SaveCredentials) {
write-error 'The parameter SaveCredentials of Connect-SkylineInsights cmdlet is not supported on PowerShell Core.'
return
}
if ($PSEdition -eq 'Core' -AND !$apiKey) {
write-error 'An API key is required.'
return
}
# Create VICredentialStore item to save the API key
if ($apiKey -AND $SaveCredentials) {
if ( (Get-Command Get-VICredentialStoreItem -ErrorAction:SilentlyContinue | Measure-Object).Count -gt 0 ) {
$savedCred = Get-VICredentialStoreItem -host $skylineApi -ErrorAction:SilentlyContinue
if ($savedCred) {
$savedCred | Remove-VICredentialStoreItem -Confirm:$false
}
New-VICredentialStoreItem -Host $skylineApi -User 'api-key' -Password $apiKey
} else {
Write-Warning 'Use of -SaveCredentials requires the PowerCLI VICredentialStoreItem cmdlets.'
}
}
if (!$apiKey) {
if ( (Get-Command Get-VICredentialStoreItem -ErrorAction:SilentlyContinue | Measure-Object).Count -gt 0 ) {
$savedCred = Get-VICredentialStoreItem -host $skylineApi -ErrorAction:SilentlyContinue
}
if ( ($savedCred | Measure-Object).Count -eq 1) {
$apiKey = $savedCred.Password
} else {
write-error 'An API key is required.'
return
}
}
$loginHeader = @{
'Accept' = 'application/json'
'Content-Type' = 'application/x-www-form-urlencoded'
}
$loginBody = @{'refresh_token' = $apiKey }
try {
$webRequest = Invoke-RestMethod -Uri "https://$cspApi/csp/gateway/am/api/auth/api-tokens/authorize?grant_type=refresh_token" -method POST -Headers $loginHeader -Body $loginBody
$global:DefaultSkylineConnection = New-Object psobject -property @{ 'Name'=$skylineApi; 'CSPName'=$cspApi; 'ConnectionDetail'=$webRequest; APIKey = $apiKey;
'Refresh_Token'=$webRequest.refresh_token; 'SkylineAPI'="https://$skylineApi/public/api/data"; PSTypeName='SkylineConnection' }
# Return the connection object
$global:SkylineInsightsApiQueryCount = 0
$global:SkylineInsightsApiQueryLastTime = $null
$global:DefaultSkylineConnection
} catch {
Write-Error ("Failure connecting to $skylineAPI. Posted $loginBody " + $_)
} # end try/catch block
}
Function Disconnect-SkylineInsights {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 21, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to disconnect from Skyline Insights API
.DESCRIPTION
This function will allow you to disconnect from a Skyline Insights API.
The global variable will be set with the Servername & Header value for use by other functions.
.EXAMPLE
PS C:\> Disconnect-SkylineInsights
This will remove a connection to Skyline Insights.
#>
if ($global:DefaultSkylineConnection) {
$global:DefaultSkylineConnection = $null
} else {
Write-Error 'Could not find an existing connection to SkylineInsights API.'
}
}
Function Invoke-SkylineInsightsApi {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 21, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to post a query to the Skyline Insights API.
.DESCRIPTION
This function will allow you to query the Skyline Insights API.
Proper headers will be formatted and posted if a DefaultSkylineConnection is present.
This is primarily a helper function used by other functions included in the module.
It is exported in the module manifest to be used for any custom queries.
.EXAMPLE
PS C:\> Invoke-SkylineInsightsApi -queryBody '{formatted-query-string-converted-to-json}'
#>
param(
[Parameter(Mandatory=$true)][string]$queryBody,
[Parameter(DontShow=$true)][int]$sleepTimerMs=501
)
if ( !$global:DefaultSkylineConnection ) {
Write-Error 'You are not currently connected to any servers. Please connect first using Connect-SkylineInsights.'
return;
}
write-debug "Querybody: $queryBody"
try {
if ($global:SkylineInsightsApiQueryLastTime) {
$timeSinceLastQuery = (New-TimeSpan $global:SkylineInsightsApiQueryLastTime (Get-Date)).TotalMilliseconds
if ($timeSinceLastQuery -lt $sleepTimerMs) {
Write-Debug "Waiting $($sleepTimerMs-$timeSinceLastQuery)ms to prevent HTTP 429 TOO_MANY_REQUESTS error"
Start-Sleep -Milliseconds ($sleepTimerMs-$timeSinceLastQuery)
}
}
$restCall = invoke-restmethod -method post -Uri $($global:DefaultSkylineConnection.SkylineAPI) -Headers @{Authorization = "Bearer $($global:DefaultSkylineConnection.ConnectionDetail.access_token)"} -body $queryBody -ContentType "application/json"
$global:SkylineInsightsApiQueryCount++
$global:SkylineInsightsApiQueryLastTime = Get-Date
if ($restCall.errors) {
Write-Error $restCall.errors.Message
}
return $restCall
} catch {
$incomingError = $_
try {
# are nested try/catch blocks the powershell equilivent of vbscript On Error Resume Next?
$errorStatusAsJson = ($incomingError | ConvertFrom-Json).status
if ($errorStatusAsJson -eq '429 TOO_MANY_REQUESTS') {
write-error 'Encountered HTTP 429 TOO_MANY_REQUESTS error, consider increasing sleepTimerMs value.'
start-sleep -Milliseconds (2*$sleepTimerMs)
break
}
} catch {
# this was the error from trying to cast the incoming error to Json
}
if (!$errorStatusAsJson) { write-error $incomingError }
}
}
Function Get-SkylineFinding {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 21, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to query findings from the Skyline Insights API.
.DESCRIPTION
This function will allow you to query the Skyline Insights API for Findings.
As described in the documentation, the maximum limit per page is 200 records. This function provides
an optional pagesize parameter to request smaller batches, but by default assumes 200 records.
.EXAMPLE
PS C:\> Get-SkylineFinding
#>
[cmdletbinding()]
param(
[Parameter(ValueFromPipelineByPropertyName=$true)][string]$findingId,
[Parameter(ValueFromPipelineByPropertyName=$true)][string[]]$products,
[Parameter(ValueFromPipelineByPropertyName=$true)][ValidateSet('CRITICAL','MODERATE','TRIVIAL')][string]$severity,
[Parameter(DontShow=$true)][ValidateRange(1,200)][int]$pagesize=200
)
begin {
$queryBody = @"
{
activeFindings(limit: $pagesize, start: 0 filter: {}) {
findings {
findingId
accountId
findingDisplayName
severity
products
findingDescription
findingImpact
recommendations
kbLinkURLs
recommendationsVCF
kbLinkURLsVCF
categoryName
findingTypes
firstObserved
totalAffectedObjectsCount
}
totalRecords
timeTaken
}
}
"@
}
process {
if (!$products) { $products = 'NO_PRODUCT_FILTER'}
foreach ($thisProduct in $products) {
if ($findingId) { $filterString = "findingId: `"$findingId`"," }
if ($thisProduct -ne 'NO_PRODUCT_FILTER') { $filterString += "product: `"$thisProduct`"," }
# Try to get results the first time
$results = @()
$thisIteration = 0
do {
$thisQueryBody = $queryBody -Replace 'filter: {}', "filter: { $filterString }" -Replace 'start: 0', "start: $thisIteration"
Write-Debug $thisQueryBody
$thisResult = Invoke-SkylineInsightsApi -queryBody (@{'query' = $thisQueryBody} | ConvertTo-Json -Compress)
$totalRecords = $thisResult.data.activeFindings.totalRecords
if ($severity) {
$thisResult.data.activeFindings.Findings | Where-Object {$_.severity -eq $severity}
} else {
$thisResult.data.activeFindings.Findings
}
$results += ($thisResult.data.activeFindings.Findings)
$thisIteration += $pageSize
} while ($results.count -lt $totalRecords ) # end do/while loop
#return $results
}
}
end {
}
}
Function Get-SkylineAffectedObject {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 21, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to query affected objects from the Skyline Insights API.
.DESCRIPTION
This function will allow you to query the Skyline Insights API for affected objects.
Input parameters are required for the findingId and product. Products can be provided as an object (from Get-SkylineFinding) or
a single product can be specified by name (or delimited list).
As described in the documentation, the maximum limit per page is 200 records. This function provides
an optional pagesize parameter to request smaller batches, but by default assumes 200 records.
.EXAMPLE
PS C:\> Get-SkylineAffectedObject -findingId 'vSphere-Vmtoolsmemoryleak-KB#76163' -product 'core-vcenter01.lab.enterpriseadmins.org'
This example uses the ByName parameter set to pass in specific findings/product and expects either a single product or a 'separator' delimited list
.EXAMPLE
PS C:\> Get-SkylineFinding | Select-Object -First 2 | Get-SkylineAffectedObject
This example uses the ByObject parameter set to pass in products as an object from Get-SkylineFinding
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string]$findingId,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string[]]$products,
[Parameter(DontShow=$true)][ValidateRange(1,200)][int]$pagesize=200
)
begin {
$queryBody = @"
{
activeFindings(
filter: {
findingId: "",
product: "",
}) {
findings {
totalAffectedObjectsCount
affectedObjects(start: 0, limit: $pagesize) {
sourceName
objectName
objectType
version
buildNumber
solutionTags {
type
version
}
firstObserved
}
}
totalRecords
timeTaken
}
}
"@
# Try to get results the first time
}
process {
foreach ( $thisProduct in $products ) {
$thisIteration = 0
$results = @() # reset results variable between products
do {
$thisQueryBody = $queryBody -Replace 'product: "",', "product: `"$thisProduct`"," -Replace 'start: 0', "start: $thisIteration" -Replace 'findingId: "",', "findingId: `"$findingId`","
Write-Debug $thisQueryBody
$thisResult = Invoke-SkylineInsightsApi -queryBody (@{'query' = $thisQueryBody} | ConvertTo-Json -Compress)
$totalRecords = $thisResult.data.activeFindings.Findings.totalAffectedObjectsCount
$thisResult.data.activeFindings.Findings.affectedObjects | Select-Object @{N='findingId';E={$findingId}}, *
$results += ($thisResult.data.activeFindings.Findings.affectedObjects) | Select-Object @{N='findingId';E={$findingId}}, *
$thisIteration += $pagesize
} while ($results.count -lt $totalRecords ) # end do/while loop
} # end foreach product loop
}
}
Function Format-SkylineResult {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 21, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to format results from the Skyline Insights API
.DESCRIPTION
This function will format the output from the Skyline Insights API.
For example, Get-SkylineFinding and Get-SkylineAffectedObject will return some strings, date values as numbers, and object properties.
This function will convert date numbers to powershell dates and objects to delimiter separated stings. This should help with exporting
results to CSV files for example.
.EXAMPLE
PS C:\> Get-SkylineFinding | Format-SkylineResult | Export-Csv c:\temp\findings.csv -NoTypeInformation
This will return Skyline Findings, format them as needed, and export results to a CSV file.
#>
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)][PSCustomObject]$inputObject,
[string]$separator = '; '
)
begin {
$results = @()
# To format the dates, we need to add the value returned by the API to the begining of time
$startOfTime = Get-Date '1970-01-01'
}
process {
if ( $inputObject.accountId ) {
#This appears to be a Finding
$results += $inputObject | Select-Object findingId, accountId, findingDisplayName, severity, @{N='product';E={[string]::join($separator, $_.products)}}, findingDescription,
findingImpact, @{N='recommendations';E={[string]::Join($separator,$_.recommendations)}}, @{N='kbLinkURLs';E={[string]::Join($separator, $_.kbLinkURLs)}},
@{N='recommendationsVCF';E={[string]::Join($separator,$_.recommendationsVCF)}}, @{N='kbLinkURLsVCF';E={[string]::Join($separator, $_.kbLinkURLsVCF)}},
categoryName, @{N='findingTypes';E={[string]::Join($sep, $_.findingTypes)}}, @{N='firstObserved';E={ $startOfTime+[timespan]::FromMilliseconds($_.firstObserved) }},
totalAffectedObjectsCount
} elseif ( $inputObject.objectName ) {
#This appears to be an AffectedObject
$results += $inputObject | Select-Object findingId, sourceName, objectName, objectType, version, buildNumber, @{N='solutionTags-Type';E={$_.solutionTags.type}},
@{N='solutionTags-Version';E={$_.solutionTags.version}}, @{N='firstObserved';E={ $startOfTime+[timespan]::FromMilliseconds($_.firstObserved) }}
} else {
write-warning "Unable to determine input object type."
} # end inputobject evaluation
} #end process
end {
return $results
}
}
Function Start-SkylineInsightsApiExplorer {
<#
.NOTES
===========================================================================
Created by: Brian Wuchner
Date: February 21, 2022
Blog: www.enterpriseadmins.org
Twitter: @bwuch
===========================================================================
.SYNOPSIS
Use this function to launch the Skyline Insights API in a browser.
.DESCRIPTION
This function will open the Skyline Insights API explorer in the default web browser and populate
the clipboard with the necessary authorization header value to enable interactive queries.
.EXAMPLE
PS C:\> Start-SkylineInsightsApiExplorer
#>
if ( !$global:DefaultSkylineConnection ) {
Write-Error 'You are not currently connected to any servers. Please connect first using Connect-SkylineInsights.'
return;
}
"Default web browser will launch to the Skyline Insights API explorer. In the lower left select 'Request Headers' and paste the authorization/bearer token into the text box. `nNote: this script has updated your clipboard with the required auth token."
"{`"Authorization`":`"Bearer $($global:DefaultSkylineConnection.ConnectionDetail.access_token)`"}" | Set-Clipboard
Start-Process "https://$($global:DefaultSkylineConnection.Name)/public/api/docs"
}

View File

@@ -1,11 +1,11 @@
Prerequisites/Steps to use this module:
1. You must be a Trust Authority Administrator, a part of the TrustedAdmins group and also have the "Host.Inventory.Add Host To Cluster" privilege on vCenter system.
2. The ESXi host must be wiped from existing Trusted Infrastructure configuration. If the ESXi host has been previously configured as part of vSphere Trust Authority (part of a vCenter configured for vSphere Trust Authority, a Trust Authority Cluster or Trusted Cluster), you must use the decommission script first.
3. Clusters should be in a healthy state (check all vSphere Trust Authority APIs which return Health field).
3. TrustAuthorityCluster and TrustedCluster should be in a healthy state (check all vSphere Trust Authority APIs which return Health field).
4. The ESXi host must be removed from vCenter.
5. You must know the ESXi host root credentials (username and password).
6. You must have purchased sufficient license for vSphere Trust Authority.
7. You must have PowerCLI 12.0.0 and above.
7. You must have PowerCLI 12.1.0 and above.
8. Following PowerCLI module is required to be imported: VMware.VimAutomation.Security.
9. Run the command Get-Command -Module VMware.TrustedInfrastructure.Helper. This should inform the following functions are available:
- Add-TrustAuthorityVMHost

View File

@@ -53,7 +53,7 @@ Copyright = 'Copyright (c) 2020 VMware, Inc. All rights reserved.'
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @(
@{"ModuleName"="VMware.VimAutomation.Security";"ModuleVersion"="12.0.0.15939672"}
@{"ModuleName"="VMware.VimAutomation.Security";"ModuleVersion"="12.1.0.17009493"}
)
@@ -126,10 +126,10 @@ PrivateData = @{
}
# SIG # Begin signature block
# MIIi9AYJKoZIhvcNAQcCoIIi5TCCIuECAQExDzANBglghkgBZQMEAgEFADB5Bgor
# MIIhmQYJKoZIhvcNAQcCoIIhijCCIYYCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBpNQqsdVk1BjVn
# MMKwrDCn/ghozrgmuT8MkgPS925Zl6CCD8swggTMMIIDtKADAgECAhBdqtQcwalQ
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCD1J+i48Lf7YHut
# tHoAX/uG5pY2Z1O+6f9dCc3MyP4DB6CCD8swggTMMIIDtKADAgECAhBdqtQcwalQ
# C13tonk09GI7MA0GCSqGSIb3DQEBCwUAMH8xCzAJBgNVBAYTAlVTMR0wGwYDVQQK
# ExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3Qg
# TmV0d29yazEwMC4GA1UEAxMnU3ltYW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBT
@@ -213,104 +213,97 @@ PrivateData = @{
# yfcjKDJ2+aSDVshIzlqWqqDMDMR/tI6Xr23jVCfDn4bA1uRzCJcF29BUYl4DSMLV
# n3+nZozQnbBP1NOYX0t6yX+yKVLQEoDHD1S2HmfNxqBsEQOE00h15yr+sDtuCjqm
# a3aZBaPxd2hhMxRHBvxTf1K9khRcSiRqZ4yvjZCq0PZ5IRuTJnzDzh69iDiSrkXG
# GWpJULMF+K5ZN4pqJQOUsVmBUOi6g4C3IzX0drlnHVkYrSCNlDGCEn8wghJ7AgEB
# GWpJULMF+K5ZN4pqJQOUsVmBUOi6g4C3IzX0drlnHVkYrSCNlDGCESQwghEgAgEB
# MIGTMH8xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlv
# bjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEwMC4GA1UEAxMnU3lt
# YW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBAhBdqtQcwalQC13t
# onk09GI7MA0GCWCGSAFlAwQCAQUAoIGWMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3
# AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCoGCisGAQQBgjcCAQwx
# HDAaoRiAFmh0dHA6Ly93d3cudm13YXJlLmNvbS8wLwYJKoZIhvcNAQkEMSIEIM0S
# yl+DLO5/G6CpV6dDnBERqJttAW4XXH7Aky0XuDpFMA0GCSqGSIb3DQEBAQUABIIB
# AFFIiFbh7hbtFYhpRzq2TM3DZ2R+LpRz2DdVTOR8iLirTkwcZvCMbsx4wZbcoDpQ
# uldpdbJS1CuXAX+TW48NtE/ph0wA+c2D5CgAvyamV9Zz/Jog9W8bYrytl3A1JNCk
# cT6xdg8L+E6OAx1L4ls8giqJXOoJSpFX4fD8Wzdd2cA4GgfPSZ3V+KahgxnOmglp
# rVcsFfdMywtGyfVyYU5ZP/a2Wo9uGioZVYaRuW6gUc8aziUWpeeUCPDeOMTpRCVE
# Hu4YO7usse7/W2c4sQGe273k/AYyyVf1pLQrmoW5Q453KcpiZa3FJAPBoyamCO2i
# 0b1IdrfRwgriLapWu2Qv4SyhghAjMIIQHwYKKwYBBAGCNwMDATGCEA8wghALBgkq
# hkiG9w0BBwKggg/8MIIP+AIBAzEPMA0GCWCGSAFlAwQCAQUAMIHmBgsqhkiG9w0B
# CRABBKCB1gSB0zCB0AIBAQYJKwYBBAGgMgIDMDEwDQYJYIZIAWUDBAIBBQAEIPY5
# SN6u90hWWtb8WksRwND3bUpYHl/udJrlk3gg43Q7Ag4BbKiJKXgAAAAAAKUUyRgT
# MjAyMDA0MDIxMDI5MTcuMjUzWjADAgEBoGOkYTBfMQswCQYDVQQGEwJKUDEcMBoG
# A1UEChMTR01PIEdsb2JhbFNpZ24gSy5LLjEyMDAGA1UEAxMpR2xvYmFsU2lnbiBU
# U0EgZm9yIEFkdmFuY2VkIC0gRzMgLSAwMDMtMDGgggxqMIIE6jCCA9KgAwIBAgIM
# M5Agd2HEJt2UUAMNMA0GCSqGSIb3DQEBCwUAMFsxCzAJBgNVBAYTAkJFMRkwFwYD
# VQQKExBHbG9iYWxTaWduIG52LXNhMTEwLwYDVQQDEyhHbG9iYWxTaWduIFRpbWVz
# dGFtcGluZyBDQSAtIFNIQTI1NiAtIEcyMB4XDTE4MDYxNDEwMDAwMFoXDTI5MDMx
# ODEwMDAwMFowXzELMAkGA1UEBhMCSlAxHDAaBgNVBAoTE0dNTyBHbG9iYWxTaWdu
# IEsuSy4xMjAwBgNVBAMTKUdsb2JhbFNpZ24gVFNBIGZvciBBZHZhbmNlZCAtIEcz
# IC0gMDAzLTAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv3Gj+IDO
# E5Be8KfdP9KY8kE6Sdp/WC+ePDoBE8ptNJlbDCccROdW4wkv9W+rTr4nYmbGuLKH
# x2W+xsBeqT6u+yR0iyv4aARkhqo64qohj/rxnbkYMF6afAf1O3Uu2gklGav+c+lx
# neyq9j4ShYEUJPjmPpnfrvO5i9UmywSommFW7yhwqEtqKyVq5aA2ny25mofcdA4f
# QqBBOpYHDst7MtUBC1ORfVY0T7S8sHRHnKp6bF/kjlGfk5BhAz6PX0FBUHg5LRIS
# 3OvqADCyP+FtE7d1SBVrTg7Rl+NO25bZ0WKvCEHPIg/o3c7Y6pNWbtM6j2dKaki6
# /GHlbFmzEi0CgQIDAQABo4IBqDCCAaQwDgYDVR0PAQH/BAQDAgeAMEwGA1UdIARF
# MEMwQQYJKwYBBAGgMgEeMDQwMgYIKwYBBQUHAgEWJmh0dHBzOi8vd3d3Lmdsb2Jh
# bHNpZ24uY29tL3JlcG9zaXRvcnkvMAkGA1UdEwQCMAAwFgYDVR0lAQH/BAwwCgYI
# KwYBBQUHAwgwRgYDVR0fBD8wPTA7oDmgN4Y1aHR0cDovL2NybC5nbG9iYWxzaWdu
# LmNvbS9ncy9nc3RpbWVzdGFtcGluZ3NoYTJnMi5jcmwwgZgGCCsGAQUFBwEBBIGL
# MIGIMEgGCCsGAQUFBzAChjxodHRwOi8vc2VjdXJlLmdsb2JhbHNpZ24uY29tL2Nh
# Y2VydC9nc3RpbWVzdGFtcGluZ3NoYTJnMi5jcnQwPAYIKwYBBQUHMAGGMGh0dHA6
# Ly9vY3NwMi5nbG9iYWxzaWduLmNvbS9nc3RpbWVzdGFtcGluZ3NoYTJnMjAdBgNV
# HQ4EFgQUeaezg3HWs0B2IOZ0Crf39+bd3XQwHwYDVR0jBBgwFoAUkiGnSpVdZLCb
# tB7mADdH5p1BK0wwDQYJKoZIhvcNAQELBQADggEBAIc0fm43ZxsIEQJttimYchTL
# SH7IyY8viQ2vD/IsIZBuO7ccAaqBaMQQI0v4CeOrX+pFps4O/qSA6WtqDAD5yoYQ
# DD7/HxrpHOUil2TZrOnj6NpTYGMLt45P3NUh9J3eE2o4NeVs4yZM29Z0Z0W5TwTE
# WAgam2ZFPSQaGpJXyV8oR3hn21zKrQvotw/RthYyNCIENnJM73umvLauBMDZeKCI
# yIZrGNqWjStuIlzLf70XvZ63toZNgxBNsDKy4BOgy2DihHUU6SG9EKKktgjPOw0p
# WVmp08NMDX9CzIgUtELlugTVmEqkjQc9SR94bWVtYL38zlnrLOnFqtqt7taTrBUw
# ggQVMIIC/aADAgECAgsEAAAAAAExicZQBDANBgkqhkiG9w0BAQsFADBMMSAwHgYD
# VQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2ln
# bjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xMTA4MDIxMDAwMDBaFw0yOTAzMjkx
# MDAwMDBaMFsxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNh
# MTEwLwYDVQQDEyhHbG9iYWxTaWduIFRpbWVzdGFtcGluZyBDQSAtIFNIQTI1NiAt
# IEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqpuOw6sRUSUBtpaU
# 4k/YwQj2RiPZRcWVl1urGr/SbFfJMwYfoA/GPH5TSHq/nYeer+7DjEfhQuzj46FK
# bAwXxKbBuc1b8R5EiY7+C94hWBPuTcjFZwscsrPxNHaRossHbTfFoEcmAhWkkJGp
# eZ7X61edK3wi2BTX8QceeCI2a3d5r6/5f45O4bUIMf3q7UtxYowj8QM5j0R5tnYD
# V56tLwhG3NKMvPSOdM7IaGlRdhGLD10kWxlUPSbMQI2CJxtZIH1Z9pOAjvgqOP1r
# oEBlH1d2zFuOBE8sqNuEUBNPxtyLufjdaUyI65x7MCb8eli7WbwUcpKBV7d2ydiA
# CoBuCQIDAQABo4HoMIHlMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/
# AgEAMB0GA1UdDgQWBBSSIadKlV1ksJu0HuYAN0fmnUErTDBHBgNVHSAEQDA+MDwG
# BFUdIAAwNDAyBggrBgEFBQcCARYmaHR0cHM6Ly93d3cuZ2xvYmFsc2lnbi5jb20v
# cmVwb3NpdG9yeS8wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz
# aWduLm5ldC9yb290LXIzLmNybDAfBgNVHSMEGDAWgBSP8Et/qC5FJK5NUPpjmove
# 4t0bvDANBgkqhkiG9w0BAQsFAAOCAQEABFaCSnzQzsm/NmbRvjWek2yX6AbOMRhZ
# +WxBX4AuwEIluBjH/NSxN8RooM8oagN0S2OXhXdhO9cv4/W9M6KSfREfnops7yyw
# 9GKNNnPRFjbxvF7stICYePzSdnno4SGU4B/EouGqZ9uznHPlQCLPOc7b5neVp7uy
# y/YZhp2fyNSYBbJxb051rvE9ZGo7Xk5GpipdCJLxo/MddL9iDSOMXCo4ldLA1c3P
# iNofKLW6gWlkKrWmotVzr9xG2wSukdduxZi61EfEVnSAR3hYjL7vK/3sbL/RlPe/
# UOB74JD9IBh4GCJdCC6MHKCX8x2ZfaOdkdMGRE4EbnocIOM28LZQuTCCA18wggJH
# oAMCAQICCwQAAAAAASFYUwiiMA0GCSqGSIb3DQEBCwUAMEwxIDAeBgNVBAsTF0ds
# b2JhbFNpZ24gUm9vdCBDQSAtIFIzMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYD
# VQQDEwpHbG9iYWxTaWduMB4XDTA5MDMxODEwMDAwMFoXDTI5MDMxODEwMDAwMFow
# TDEgMB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkds
# b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wggEiMA0GCSqGSIb3DQEBAQUA
# A4IBDwAwggEKAoIBAQDMJXaQeQZ4Ihb1wIO2hMoonv0FdhHFrYhy/EYCQ8eyip0E
# XyTLLkvhYIJG4VKrDIFHcGzdZNHr9SyjD4I9DCuul9e2FIYQebs7E4B3jAjhSdJq
# Yi8fXvqWaN+JJ5U4nwbXPsnLJlkNc96wyOkmDoMVxu9bi9IEYMpJpij2aTv2y8go
# keWdimFXN6x0FNx04Druci8unPvQu7/1PQDhBjPogiuuU6Y6FnOM3UEOIDrAtKeh
# 6bJPkC4yYOlXy7kEkmho5TgmYHWyn3f/kRTvriBJ/K1AFUjRAjFhGV64l++td7dk
# mnq/X8ET75ti+w1s4FRpFqkD2m7pg5NxdsZphYIXAgMBAAGjQjBAMA4GA1UdDwEB
# /wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSP8Et/qC5FJK5NUPpj
# move4t0bvDANBgkqhkiG9w0BAQsFAAOCAQEAS0DbwFCq/sgM7/eWVEVJu5YACUGs
# sxOGhigHM8pr5nS5ugAtrqQK0/Xx8Q+Kv3NnSoPHRHt44K9ubG8DKY4zOUXDjuS5
# V2yq/BKW7FPGLeQkbLmUY/vcU2hnVj6DuM81IcPJaP7O2sJTqsyQiunwXUaMld16
# WCgaLx3ezQA3QY/tRG3XUyiXfvNnBB4V14qWtNPeTCekTBtzc3b0F5nCH3oO4y0I
# rQocLP88q1UOD5F+NuvDV0m+4S4tfGCLw0FREyOdzvcya5QBqJnnLDMfOjsl0oZA
# zjsshnjJYS8Uuu7bVW/fhO4FCU29KNhyztNiUGUe65KXgzHZs7XKR1g/XzGCAokw
# ggKFAgEBMGswWzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt
# c2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gU0hBMjU2
# IC0gRzICDDOQIHdhxCbdlFADDTANBglghkgBZQMEAgEFAKCB8DAaBgkqhkiG9w0B
# CQMxDQYLKoZIhvcNAQkQAQQwLwYJKoZIhvcNAQkEMSIEIAZrKdIvpe4etJdIpute
# bD7Bkgo2OLI6O5CjboEGMuXnMIGgBgsqhkiG9w0BCRACDDGBkDCBjTCBijCBhwQU
# rmsC2QsljAmRsRYSid62aVY5HW8wbzBfpF0wWzELMAkGA1UEBhMCQkUxGTAXBgNV
# BAoTEEdsb2JhbFNpZ24gbnYtc2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0
# YW1waW5nIENBIC0gU0hBMjU2IC0gRzICDDOQIHdhxCbdlFADDTANBgkqhkiG9w0B
# AQEFAASCAQCtspr11iTT8uoLlJY6Gmk9/dEzqYSh+ib0ml+qk5WNO2g0ggA42yp9
# lnUfnLFUdqTCTm1kP5QHYISnBRVq88TDVqPOlxMUr/pxaWGi95NgkMbYS0A9bEf1
# 0B1BjUsVHdEcRmW3RYU6bgmcoMKCNNvt2U0+r/e85MW358FMr5+Qwje5xKFhFKQi
# wZkY34+ycnFsyMBwDCYeMxIWEAJdFdp+BQ1NI4hE1+whqEoXxBFbHABzoK7CQfZt
# x38BWzvhRjGc4DFiTH25oqKHmzvvBrtIBhR1KGP0UxgJtLIkBu1lqqVCpD2DuOpu
# 6Q/wMh8Z+1DanPs+68ioAyOE0N4MaVz+
# HDAaoRiAFmh0dHA6Ly93d3cudm13YXJlLmNvbS8wLwYJKoZIhvcNAQkEMSIEIFE5
# XkE1aqldNZ9PdTmDM9o8F2go4eZy2Z0ldYxQDQjYMA0GCSqGSIb3DQEBAQUABIIB
# ABYojUSikybt+zBAYjJkVB+ZXSqf2DFW5I2FrzHL2kJXE8Z8sse8x5eBL/wTQydp
# I7Nt6E2Oa7l+AFI1QSmc1kdHGjrljiJV6rdIVMl2Qi1DEGYloLIkUuGpeMq09Bio
# pgRkWUQOax2L9X+Jabf5f9jK9OABnjPjU944/mw2hMNSlPFa1N3YhM9lS2Ua6sgi
# sUFE+iK4rNPQo+fT753hbzQLZvVKOkJ/Kt10ELa/nWzzZnm7O5kViagDpvQc7dYb
# WYjqm5mZviZQSZSkcj0BQPP1kpexl3c3jYz2l6EXYq4C8MXc7ZbktFqMnCe3eQno
# NRTi0u4owXw7W3Z4IwF66/Shgg7IMIIOxAYKKwYBBAGCNwMDATGCDrQwgg6wBgkq
# hkiG9w0BBwKggg6hMIIOnQIBAzEPMA0GCWCGSAFlAwQCAQUAMHcGCyqGSIb3DQEJ
# EAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglghkgBZQMEAgEFAAQg6TWzqpl5
# e7eFcT7LyWtAxkl3Xz0jBI5uSPTz509MPlgCEByTeiRukyNPugnHqHi5fDcYDzIw
# MjAxMDEyMTAxNzExWqCCC7swggaCMIIFaqADAgECAhAEzT+FaK52xhuw/nFgzKdt
# MA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2Vy
# dCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNVBAMTKERpZ2lD
# ZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0EwHhcNMTkxMDAxMDAw
# MDAwWhcNMzAxMDE3MDAwMDAwWjBMMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGln
# aUNlcnQsIEluYy4xJDAiBgNVBAMTG1RJTUVTVEFNUC1TSEEyNTYtMjAxOS0xMC0x
# NTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOlkNZz6qZhlZBvkF9y4
# KTbMZwlYhU0w4Mn/5Ts8EShQrwcx4l0JGML2iYxpCAQj4HctnRXluOihao7/1K7S
# ehbv+EG1HTl1wc8vp6xFfpRtrAMBmTxiPn56/UWXMbT6t9lCPqdVm99aT1gCqDJp
# IhO+i4Itxpira5u0yfJlEQx0DbLwCJZ0xOiySKKhFKX4+uGJcEQ7je/7pPTDub0U
# LOsMKCclgKsQSxYSYAtpIoxOzcbVsmVZIeB8LBKNcA6Pisrg09ezOXdQ0EIsLnrO
# nGd6OHdUQP9PlQQg1OvIzocUCP4dgN3Q5yt46r8fcMbuQhZTNkWbUxlJYp16ApuV
# FKMCAwEAAaOCAzgwggM0MA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMBYG
# A1UdJQEB/wQMMAoGCCsGAQUFBwMIMIIBvwYDVR0gBIIBtjCCAbIwggGhBglghkgB
# hv1sBwEwggGSMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2VydC5jb20v
# Q1BTMIIBZAYIKwYBBQUHAgIwggFWHoIBUgBBAG4AeQAgAHUAcwBlACAAbwBmACAA
# dABoAGkAcwAgAEMAZQByAHQAaQBmAGkAYwBhAHQAZQAgAGMAbwBuAHMAdABpAHQA
# dQB0AGUAcwAgAGEAYwBjAGUAcAB0AGEAbgBjAGUAIABvAGYAIAB0AGgAZQAgAEQA
# aQBnAGkAQwBlAHIAdAAgAEMAUAAvAEMAUABTACAAYQBuAGQAIAB0AGgAZQAgAFIA
# ZQBsAHkAaQBuAGcAIABQAGEAcgB0AHkAIABBAGcAcgBlAGUAbQBlAG4AdAAgAHcA
# aABpAGMAaAAgAGwAaQBtAGkAdAAgAGwAaQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQA
# IABhAHIAZQAgAGkAbgBjAG8AcgBwAG8AcgBhAHQAZQBkACAAaABlAHIAZQBpAG4A
# IABiAHkAIAByAGUAZgBlAHIAZQBuAGMAZQAuMAsGCWCGSAGG/WwDFTAfBgNVHSME
# GDAWgBT0tuEgHf4prtLkYaWyoiWyyBc1bjAdBgNVHQ4EFgQUVlMPwcYHp03X2G5X
# coBQTOTsnsEwcQYDVR0fBGowaDAyoDCgLoYsaHR0cDovL2NybDMuZGlnaWNlcnQu
# Y29tL3NoYTItYXNzdXJlZC10cy5jcmwwMqAwoC6GLGh0dHA6Ly9jcmw0LmRpZ2lj
# ZXJ0LmNvbS9zaGEyLWFzc3VyZWQtdHMuY3JsMIGFBggrBgEFBQcBAQR5MHcwJAYI
# KwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBPBggrBgEFBQcwAoZD
# aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0U0hBMkFzc3VyZWRJ
# RFRpbWVzdGFtcGluZ0NBLmNydDANBgkqhkiG9w0BAQsFAAOCAQEALoOhRAVKBOO5
# MlL62YHwGrv4CY0juT3YkqHmRhxKL256PGNuNxejGr9YI7JDnJSDTjkJsCzox+Hi
# zO3LeWvO3iMBR+2VVIHggHsSsa8Chqk6c2r++J/BjdEhjOQpgsOKC2AAAp0fR8Sf
# tApoU39aEKb4Iub4U5IxX9iCgy1tE0Kug8EQTqQk9Eec3g8icndcf0/pOZgrV5JE
# 1+9uk9lDxwQzY1E3Vp5HBBHDo1hUIdjijlbXST9X/AqfI1579JSN3Z0au996KqbS
# RaZVDI/2TIryls+JRtwxspGQo18zMGBV9fxrMKyh7eRHTjOeZ2ootU3C7VuXgvjL
# qQhsUwm09zCCBTEwggQZoAMCAQICEAqhJdbWMht+QeQF2jaXwhUwDQYJKoZIhvcN
# AQELBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG
# A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMbRGlnaUNlcnQgQXNzdXJl
# ZCBJRCBSb290IENBMB4XDTE2MDEwNzEyMDAwMFoXDTMxMDEwNzEyMDAwMFowcjEL
# MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3
# LmRpZ2ljZXJ0LmNvbTExMC8GA1UEAxMoRGlnaUNlcnQgU0hBMiBBc3N1cmVkIElE
# IFRpbWVzdGFtcGluZyBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
# AL3QMu5LzY9/3am6gpnFOVQoV7YjSsQOB0UzURB90Pl9TWh+57ag9I2ziOSXv2Mh
# kJi/E7xX08PhfgjWahQAOPcuHjvuzKb2Mln+X2U/4Jvr40ZHBhpVfgsnfsCi9aDg
# 3iI/Dv9+lfvzo7oiPhisEeTwmQNtO4V8CdPuXciaC1TjqAlxa+DPIhAPdc9xck4K
# rd9AOly3UeGheRTGTSQjMF287DxgaqwvB8z98OpH2YhQXv1mblZhJymJhFHmgudG
# UP2UKiyn5HU+upgPhH+fMRTWrdXyZMt7HgXQhBlyF/EXBu89zdZN7wZC/aJTKk+F
# HcQdPK/P2qwQ9d2srOlW/5MCAwEAAaOCAc4wggHKMB0GA1UdDgQWBBT0tuEgHf4p
# rtLkYaWyoiWyyBc1bjAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzAS
# BgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjATBgNVHSUEDDAKBggr
# BgEFBQcDCDB5BggrBgEFBQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3Nw
# LmRpZ2ljZXJ0LmNvbTBDBggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNl
# cnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElEUm9vdENBLmNydDCBgQYDVR0fBHoweDA6
# oDigNoY0aHR0cDovL2NybDQuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0QXNzdXJlZElE
# Um9vdENBLmNybDA6oDigNoY0aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lD
# ZXJ0QXNzdXJlZElEUm9vdENBLmNybDBQBgNVHSAESTBHMDgGCmCGSAGG/WwAAgQw
# KjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzALBglg
# hkgBhv1sBwEwDQYJKoZIhvcNAQELBQADggEBAHGVEulRh1Zpze/d2nyqY3qzeM8G
# N0CE70uEv8rPAwL9xafDDiBCLK938ysfDCFaKrcFNB1qrpn4J6JmvwmqYN92pDqT
# D/iy0dh8GWLoXoIlHsS6HHssIeLWWywUNUMEaLLbdQLgcseY1jxk5R9IEBhfiThh
# TWJGJIdjjJFSLK8pieV4H9YLFKWA1xJHcLN11ZOFk362kmf7U2GJqPVrlsD0WGkN
# fMgBsbkodbeZY4UijGHKeZR+WfyMD+NvtQEmtmyl7odRIeRYYJu6DC0rbaLEfrvE
# JStHAgh8Sa4TtuF8QkIoxhhWz0E0tmZdtnR79VYzIi8iNrJLokqV2PWmjlIxggJN
# MIICSQIBATCBhjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
# MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT
# SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBAhAEzT+FaK52xhuw/nFgzKdt
# MA0GCWCGSAFlAwQCAQUAoIGYMBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRABBDAc
# BgkqhkiG9w0BCQUxDxcNMjAxMDEyMTAxNzExWjArBgsqhkiG9w0BCRACDDEcMBow
# GDAWBBQDJb1QXtqWMC3CL0+gHkwovig0xTAvBgkqhkiG9w0BCQQxIgQgljiG33qR
# W3eFxG+8JqokoQ3h+0VUPjMr2ipJwjHjKyYwDQYJKoZIhvcNAQEBBQAEggEA0rMO
# e70hWy1hPDaGuhZm97/x9R9L+7u2D/gQ5VZi9hVNsUuspfPnPANRqNdwPZFqVhT0
# DtbXldlhx57QmM5/KAJJgI6LNurGHz2IkSEt2wx96RET33erziTdnxxcsUK90Jqd
# xiMbLtXWr3pIgP6PuuCoTf3CaBIcHncQG8h/YYoYUggRpUV6fl2LqQeRNgt6lsfy
# puD1ZvdskgUVTGKeCPP7UWyZSgGy6DAJBSw935BnXw5zxvDxIqtcX+5m/Dg/gvp7
# 9p6+zSiYQlo5BKhN3ehunVucmSH3ARPAo3uTlkMoYUleSVvSlM0IKZkNovha1IIx
# a7pYtiIIYFVJXnOUSw==
# SIG # End signature block

View File

@@ -30,50 +30,37 @@ $TrustAuthorityClusterSettingsFile =
Function Add-TrustAuthorityVMHost {
<#
.SYNOPSIS
This cmdlet adds a new host into the specific Trust Authority cluster.
There are some preconditions need to be met:
1. The newly added host is cleared of any previous Trust Authority configurations
2. The Trust Authority Cluster settings are all healthy
3. The connection user has the needed privileges. Please, check vSphere documentation.
4. The trust between Key Servers and TrustAuthorityKeyProvider uses the signed client certificate, user should provide its privateKey part
.DESCRIPTION
This cmdlet adds a new host into the specific Trust Authority cluster.
.PARAMETER TrustAuthorityCluster
Specifies the Trust Authority cluster you want to add the new host.
.PARAMETER VMHostAddress
Specifies the ip address of the new host you want to add to the specific Trust Authority cluster.
.PARAMETER Credential
Specifies the credential of the new host.
.PARAMETER DestDir
Specifies the location where you want to save the settings
.PARAMETER PrivateKey
Specifies the private key part of the ClientCertificate of the TrustAuthorityKeyProvider. It's a hashtable type with: the keyprovider.Name as the Key, and the File having the PrivateKey string for the ClientCertificate of the keyprovider as its Value.
.PARAMETER BaseImageFolder
Specifies the folder having all the baseImage files to re-create the TrustAuthorityVMHostBaseImage.
.EXAMPLE
PS C:\> $ts = Get-TrustAuthorityCluster "mycluster"
PS C:\> $pass = Read-Host "Please enter the host's password" -AsSecureString
PS C:\> $credential = New-Object System.Management.Automation.PSCredential -ArgumentList root,$pass
PS C:\> $privateKeyHash = @{"provider1"="c:\myprivatekey.txt";}
PS C:\> Add-TrustAuthorityVMHost -TrustAuthorityCluster $ts -VMHostAddress 1.1.1.1 -Credential $credential -DestDir c:\destDir\ -PrivateKey $privateKeyHash -BaseImageFolder "c:\baseImages\"
Add the host 1.1.1.1 with the $credential to Trust Authority cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\.
.EXAMPLE
PS C:\> $ts = Get-TrustAuthorityCluster "mycluster"
PS C:\> Add-TrustAuthorityVMHost -TrustAuthorityCluster $ts -VMHostAddress 1.1.1.1 -Credential root -DestDir c:\destDir\ -BaseImageFolder "c:\baseImages\"
Add the host 1.1.1.1 with the credential root (a window wizard will be prompted to let you input the password for the user root) to Trust Authority cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\.
.NOTES
Author : Carrie Yang
Author email : yangm@vmware.com
@@ -123,7 +110,7 @@ Function Add-TrustAuthorityVMHost {
Process {
Save-TrustAuthorityClusterSettings -TrustAuthorityCluster $TrustAuthorityCluster -DestinationFile $DestinationFile -ErrorAction Stop
Join-VMHost -ClusterName $TrustAuthorityCluster.Name -VMHostAddress $VMHostAddress -Credential $Credential -ErrorAction Stop
Join-VMHost -ClusterName $TrustAuthorityCluster.Name -VMHostAddress $VMHostAddress -Credential $Credential -Server $server -ErrorAction Stop
Apply-TrustAuthorityClusterSettings -TrustAuthorityCluster $TrustAuthorityCluster -SettingsFile $DestinationFile -BaseImageFolder $baseImageFolder -PrivateKey $privateKey -ErrorAction Stop
}
}
@@ -131,42 +118,32 @@ Function Add-TrustAuthorityVMHost {
Function Add-TrustedVMHost {
<#
.SYNOPSIS
This cmdlet adds a new host into the specific Trusted cluster.
This cmdlet adds a new host into the specific trusted cluster.
There are some preconditions need to be met:
1. No active workloads in the workload host as the cmdlet will interrup the workloads
2. The newly added host is cleared of any previous Trust Authority Configurations
3. Sufficient license
For vCenter Server 7.0.1 and above, use 'Set-TrustedCluster -Remediate' to remediate the trusted cluster after adding a new host directly.
.DESCRIPTION
This cmdlet adds a new host into the specific Trusted cluster.
.PARAMETER TrustedCluster
Specifies the Trusted cluster you want to add the new host.
.PARAMETER VMHostAddress
Specifies the ip address of the new host you want to add to the specific Trusted cluster.
.PARAMETER Credential
Specifies the credential of the new host.
.PARAMETER DestDir
Specifies the location where you want to save the settings
.EXAMPLE
PS C:\> $ts = Get-TrustedCluster "mycluster"
PS C:\> $pass = Read-Host "Please enter the host's password" -AsSecureString
PS C:\> $credential = New-Object System.Management.Automation.PSCredential -ArgumentList root,$pass
PS C:\> Add-TrustedVMHost -TrustedCluster $ts -VMHostAddress 1.1.1.1 -Credential $credential -DestDir c:\destDir\
Add the host 1.1.1.1 with the $credential to Trusted Cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\.
.EXAMPLE
PS C:\> $ts = Get-TrustedCluster "mycluster"
PS C:\> Add-TrustedVMHost -TrustedCluster $ts -VMHostAddress 1.1.1.1 -Credential root -DestDir c:\destDir\
Add the host 1.1.1.1 with the credential root (a window wizard will be prompted to let you input the password for the user root) to Trusted Cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\.
.NOTES
Author : Carrie Yang
Author email : yangm@vmware.com
@@ -202,7 +179,11 @@ Function Add-TrustedVMHost {
Write-Verbose "The server got is: $server"
ConfirmIsVCenter $server
Check-VMHostVersionAndLicense -VMHostName $VMHostAddress -Credential $Credential -CheckLicense:$true
if (Is70AboveServer -VIServer $server) {
Throw "Use 'Set-TrustedCluster -Remediate' cmdlet from VMware.VimAutomation.Security module."
}
Check-VMHostVersionAndLicense -VMHostName $VMHostAddress -Credential $Credential -CheckLicense:$true -Allow70Above $false
$DestinationFile = Join-Path $DestDir $TrustedClusterSettingsFile
Write-Verbose "The file to save settings is $DestinationFile"
}
@@ -211,7 +192,7 @@ Function Add-TrustedVMHost {
Check-TrustedClusterSettings -TrustedCluster $TrustedCluster -ErrorAction Stop
Save-TrustedClusterSettings -TrustedCluster $TrustedCluster -DestinationFile $DestinationFile -ErrorAction Stop
Remove-TrustedClusterSettings -TrustedCluster $TrustedCluster -ErrorAction Stop
Join-VMHost -ClusterName $TrustedCluster.Name -VMHostAddress $VMHostAddress -Credential $Credential -ErrorAction Stop
Join-VMHost -ClusterName $TrustedCluster.Name -VMHostAddress $VMHostAddress -Credential $Credential -Server $server -ErrorAction Stop
Apply-TrustedClusterSettings -TrustedCluster $TrustedCluster -SettingsFile $DestinationFile -ErrorAction Stop
}
}
@@ -220,21 +201,16 @@ Function Save-TrustedClusterSettings {
<#
.SYNOPSIS
This cmdlet saves the settings of the specific Trusted Cluster to the file $DestinationFile.
.DESCRIPTION
This cmdlet saves the settings of the specific Trusted Cluster to the file $DestinationFile.
.PARAMETER TrustedCluster
Specifies the Trusted Cluster you want to save the settings.
.PARAMETER DestinationFile
Specifies the file you want to save the settings to.
.EXAMPLE
PS C:\> $ts = Get-TrustedCluster "mycluster"
PS C:\> Save-TrustedClusterSettings -TrustedCluster $ts -DestinationFile "c:\myfile.json"
Saves the settings of Trusted Cluster "mycluster" to file c:\myfile.json.
.NOTES
Author : Carrie Yang
Author email : yangm@vmware.com
@@ -284,22 +260,16 @@ Function Save-TrustAuthorityClusterSettings {
<#
.SYNOPSIS
This cmdlet saves the settings of the specific Trust Authority Cluster to the file $DestinationFile.
.DESCRIPTION
This cmdlet saves the settings of the specific Trust Authority Cluster to the file $DestinationFile.
.PARAMETER TrustedCluster
Specifies the Trust Authority Cluster you want to save the settings.
.PARAMETER DestinationFile
Specifies the file you want to save the settings to.
.EXAMPLE
PS C:\> $ts = Get-TrustAuthorityCluster "mycluster"
PS C:\> Save-TrustAuthorityClusterSettings -TrustAuthorityCluster $ts -DestinationFile "c:\myfile.json"
Saves the settings of Trust Authority Cluster "mycluster" to file c:\myfile.json.
.NOTES
Author : Carrie Yang
Author email : yangm@vmware.com
@@ -343,13 +313,13 @@ Function Save-TrustAuthorityClusterSettings {
$i = 0
if ($kp -ne $null) {
$jsonObj.TrustAuthorityCluster.TrustAuthorityKeyProvider = $kp | Select-Object -Property Name, MasterKeyId, Description, ProxyAddress, ProxyPort, ConnectionTimeoutSeconds, KmipServerUsername
$jsonObj.TrustAuthorityCluster.TrustAuthorityKeyProvider = $kp | Select-Object -Property Name, PrimaryKeyId, Description, ProxyAddress, ProxyPort, ConnectionTimeoutSeconds, KmipServerUsername
$clientCert = @{}
$serverCert = @{}
$clientCSR = @{}
}
foreach ($_ in $kp) {
$kp | Foreach-Object {
$kps = Get-TrustAuthorityKeyProviderServer -KeyProvider $_ -Server $bluevc| Select-Object -Property Address, Port, Name
$clientCertTemp = Get-TrustAuthorityKeyProviderClientCertificate -KeyProvider $_ -Server $bluevc
$clientCertStr = [System.Convert]::ToBase64String($($clientCertTemp.GetRawCertData()))
@@ -390,7 +360,7 @@ Function Save-TrustAuthorityClusterSettings {
$jsonObj.TrustAuthorityCluster.TrustAuthorityTpm2CACertificate = $tpm2CA | Select-Object -Property Name
$i = 0
foreach ($_ in $tpm2CA) {
$tpm2CA | Foreach-Object {
$certStr = ConvertFrom-X509Chain -CertChain $_.CertificateChain
$jsonObj.TrustAuthorityCluster.TrustAuthorityTpm2CACertificate[$i] | Add-Member -Name "certRawData" -value $certStr -MemberType NoteProperty
@@ -411,28 +381,21 @@ Function Apply-TrustAuthorityClusterSettings {
Here are some limitations when applying the TrustAuthorityKeyProvider Settings:
- The CSR configuration will not be preserved, user needs to reset the CSR and get it signed by the Key Server, then retrieve the signed client certificate to set it back to TrustAuthorityKeyProvider
- If self signed certificates are used for trust setup, they need to be redone on new host.
.DESCRIPTION
This cmdlet applies the settings in the specific $SettingsFile to a Trust Authority Cluster
.PARAMETER TrustAuthorityCluster
Specifies the Trust Authority Cluster you want to apply the settings
.PARAMETER SettingsFile
Specifies the file having the settings you want to apply
.PARAMETER PrivateKey
Specifies the private key part of the ClientCertificate of the TrustAuthorityKeyProvider. It is a hashtable type with: the Key is the TrustAuthorityKeyProvider.Name, and the Value is the filePath for the TrustAuthorityKeyProvider's ClientCertificate PrivateKey part.
.PARAMETER BaseImageFolder
Specifies the folder having all the baseImage files to re-create the TrustAuthorityVMHostBaseImage. All the .tgz files under this folder and its sub-folders will be used to re-create TrustAuthorityVMHostBaseImage objects.
.EXAMPLE
PS C:\> $privateKeyHash = @{"provider1"="c:\myprivatekey.txt";}
PS C:\> $ts = Get-TrustAuthorityCluster "mycluster"
PS C:\> Apply-TrustAuthorityClusterSettings -TrustAuthorityCluster $ts -SettingsFile "c:\myfile.json" -PrivateKey $privateKeyHash -BaseImageFolder "c:\myimages\"
Applies the settings in file c:\myfile.json to Trust Authority Cluster "mycluster" with all the baseimage files under c:\myimages\ recursively, and cmdlet will prompt for inputting the password for each TrustAuthorityKeyProvider, also the PrivateKey info saved in c:\myprivatekey.txt will be used for the TrustAuthorityKeyProvider provider1.
.NOTES
Author : Carrie Yang
Author email : yangm@vmware.com
@@ -473,44 +436,45 @@ Function Apply-TrustAuthorityClusterSettings {
$baseImages = $jsonObj."TrustAuthorityCluster".TrustAuthorityVMHostBaseImage
if ($kp -ne $null) {
foreach ($_ in $kp) {
$kps = $_.KmipServers
$kp | Foreach-Object {
$provider = $_
$kps = $provider.KmipServers
$cmd = "New-TrustAuthorityKeyProvider"
$allArgs = @{
'TrustAuthorityCluster' = $TrustAuthorityCluster;
'Name' = $($_.Name);
'MasterKeyId' = $_.MasterKeyId;
'Name' = $provider.Name;
'PrimaryKeyId' = $provider.PrimaryKeyId;
'KmipServerName' = $kps[0].Name;
'KmipServerAddress' = $kps[0].Address;
'KmipServerPort' = $kps[0].Port;
'Server' = $blueserver;
}
if (![String]::IsNullOrWhiteSpace($_.Description)) {
$allArgs += @{'Description' = $_.Description;}
if (![String]::IsNullOrWhiteSpace($provider.Description)) {
$allArgs += @{'Description' = $provider.Description;}
}
if (![String]::IsNullOrWhiteSpace($_.ProxyAddress)) {
$allArgs += @{'ProxyAddress' = $_.ProxyAddress;}
if (![String]::IsNullOrWhiteSpace($provider.ProxyAddress)) {
$allArgs += @{'ProxyAddress' = $provider.ProxyAddress;}
}
if (![String]::IsNullOrWhiteSpace($_.ProxyPort)) {
$allArgs += @{'ProxyPort' = $_.ProxyPort;}
if (![String]::IsNullOrWhiteSpace($provider.ProxyPort)) {
$allArgs += @{'ProxyPort' = $provider.ProxyPort;}
}
if (![String]::IsNullOrWhiteSpace($_.ConnectionTimeOutSeconds)) {
$allArgs += @{'ConnectionTimeOutSeconds' = $_.ConnectionTimeOutSeconds;}
if (![String]::IsNullOrWhiteSpace($provider.ConnectionTimeOutSeconds)) {
$allArgs += @{'ConnectionTimeOutSeconds' = $provider.ConnectionTimeOutSeconds;}
}
if (![String]::IsNullOrWhiteSpace($_.KmipServerUsername)) {
$allArgs += @{'KmipServerUsername' = $_.KmipServerUsername;}
if (![String]::IsNullOrWhiteSpace($provider.KmipServerUsername)) {
$allArgs += @{'KmipServerUsername' = $provider.KmipServerUsername;}
}
$silent = & $cmd @allArgs
& $cmd @allArgs
if (($kps | Measure-Object).Count -gt 1) {
for ($i = 1; $i -gt ($kps | Measure-Object).Count; $i++) {
Add-TrustAuthorityKeyProviderServer -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Address $kps[$i].Address -Name $kps[$i].Name -Port $kps[$i].Port -Server $blueserver
LogAndRunCmdlet {Add-TrustAuthorityKeyProviderServer -KeyProvider $provider.Name -TrustAuthorityCluster $TrustAuthorityCluster -Address $kps[$i].Address -Name $kps[$i].Name -Port $kps[$i].Port -Server $blueserver -ErrorAction:Continue}
}
}
@@ -518,73 +482,92 @@ Function Apply-TrustAuthorityClusterSettings {
Write-Warning "CSR configuration won't be preserved, please manually establish the trust between kmip servers and trust authority keyprovider: $($_.Name)"
}
if ($_.ClientCertificate -ne $null) {
if ($privateKey -ne $null -and $privateKey.ContainsKey($($_.Name))) {
if ($provider.ClientCertificate -ne $null) {
if ($privateKey -ne $null -and $privateKey.ContainsKey($($provider.Name))) {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import([System.Text.Encoding]::Default.GetBytes($_.ClientCertificate))
$cert.Import([System.Text.Encoding]::Default.GetBytes($provider.ClientCertificate))
try {
$pkStr = [System.IO.File]::ReadAllText($privateKey.$($_.Name))
$pkStr = [System.IO.File]::ReadAllText($privateKey.$($provider.Name))
} catch {
Throw "Failed to read privateKey file: $($privateKey.$($_.Name))"
}
Set-TrustAuthorityKeyProviderClientCertificate -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Certificate $cert -PrivateKey $pkStr -Server $blueserver
$cmd = {Set-TrustAuthorityKeyProviderClientCertificate -KeyProvider $provider.Name -TrustAuthorityCluster $TrustAuthorityCluster -Certificate $cert -PrivateKey $privateKey.$($provider.Name) -Server $blueserver -ErrorAction:Continue}
LogAndRunCmdlet $cmd
} else {
New-TrustAuthorityKeyProviderClientCertificate -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Server $blueserver
LogAndRunCmdlet {New-TrustAuthorityKeyProviderClientCertificate -KeyProvider $provider.Name -TrustAuthorityCluster $TrustAuthorityCluster -Server $blueserver -ErrorAction:Continue}
}
}
if ($_.ServerCertificate -ne $null) {
$trustedcerts = [System.Collections.ArrayList]@()
foreach ($certStr in $_.ServerCertificate) {
$provider.ServerCertificate | Foreach-Object {
$certStr = $_
$tempStr = $certStr.CertificateRawData
if ($certStr.Trusted) {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import([System.Text.Encoding]::Default.GetBytes($tempStr))
$silent = $trustedcerts.Add($cert)
$trustedcerts.Add($cert) | Out-Null
}
}
Set-TrustAuthorityKeyProviderServerCertificate -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Certificate $trustedcerts -Server $blueserver
$cmd = {Set-TrustAuthorityKeyProviderServerCertificate -KeyProvider $provider.Name -TrustAuthorityCluster $TrustAuthorityCluster -Certificate $trustedcerts -Server $blueserver -ErrorAction:Continue}
LogAndRunCmdlet $cmd
}
$kmipPwd = Read-Host "Enter the password of Trust Authority Key Provider $($_.Name) (Return if none)" -AsSecureString
if ($kmipPwd.Length -gt 0) {
Set-TrustAuthorityKeyProvider -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -KmipServerPassword $kmipPwd -Server $blueserver
LogAndRunCmdlet {Set-TrustAuthorityKeyProvider -KeyProvider $provider.Name -TrustAuthorityCluster $TrustAuthorityCluster -KmipServerPassword $kmipPwd -Server $blueserver -ErrorAction:Continue}
}
}
}
if ($principals -ne $null) {
foreach ($_ in $principals) {
$chainList = [System.Collections.ArrayList]@()
foreach ($str in $_.certRawData) {
$chain = ConvertTo-X509Chain -certString $str
$silent = $chainList.Add($chain)
}
New-TrustAuthorityPrincipal -TrustAuthorityCluster $TrustAuthorityCluster -Name $_.Name -Domain $_.Domain -Issuer $_.Issuer -CertificateChain $chainList -Type $_.Type -Server $blueserver -Confirm:$false
}
}
if ($tpm2Setting -ne $null) {
Set-TrustAuthorityTpm2AttestationSettings -RequireCertificateValidation:$tpm2Setting.RequireCertificateValidation -RequireEndorsementKey:$tpm2Setting.RequireEndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Confirm:$false
$cmd = {Set-TrustAuthorityTpm2AttestationSettings -RequireCertificateValidation:$tpm2Setting.RequireCertificateValidation -RequireEndorsementKey:$tpm2Setting.RequireEndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Server $blueserver -Confirm:$false -ErrorAction:Continue}
LogAndRunCmdlet $cmd
}
if ($tpm2CA -ne $null) {
foreach ($_ in $tpm2CA) {
$chain = ConvertTo-X509Chain $_.certRawData
New-TrustAuthorityTpm2CACertificate -TrustAuthorityCluster $TrustAuthorityCluster -CertificateChain $chain -Name $_.Name -Server $blueserver -Confirm:$false
$tpm2CA | Foreach-Object {
$ca = $_
$chain = ConvertTo-X509Chain $ca.certRawData
$cmd = {New-TrustAuthorityTpm2CACertificate -TrustAuthorityCluster $TrustAuthorityCluster -CertificateChain $chain -Name $ca.Name -Server $blueserver -Confirm:$false -ErrorAction:Continue}
LogAndRunCmdlet $cmd
}
}
if ($tpm2Ek -ne $null) {
foreach ($_ in $tpm2Ek) {
New-TrustAuthorityTpm2EndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Name $_.Name -PublicKey $_.PublicKey -Server $blueserver -Confirm:$false
$tpm2Ek | Foreach-Object {
$ek = $_
$publicKey = $ek.PublicKey
$cmd = {New-TrustAuthorityTpm2EndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Name $ek.Name -PublicKey $publicKey -Server $blueserver -Confirm:$false -ErrorAction:Continue}
LogAndRunCmdlet $cmd
}
}
if ($baseImages -ne $null) {
New-TrustAuthorityVMHostBaseImage -TrustAuthorityCluster $TrustAuthorityCluster -FilePath $baseImageFolder -Server $blueserver -Confirm:$false
$cmd = {New-TrustAuthorityVMHostBaseImage -TrustAuthorityCluster $TrustAuthorityCluster -FilePath $baseImageFolder -Server $blueserver -Confirm:$false -ErrorAction:Continue}
LogAndRunCmdlet $cmd
}
if ($principals -ne $null) {
$errorBeforeExecution = $Global:error.Clone()
$Global:error.Clear()
$principals | Foreach-Object {
$p = $_
$chainList = [System.Collections.ArrayList]@()
$p.certRawData | Foreach-Object {
$str = $_
$chain = ConvertTo-X509Chain -certString $str
$chainList.Add($chain) | Out-Null
}
$cmd = {New-TrustAuthorityPrincipal -TrustAuthorityCluster $TrustAuthorityCluster -Name $p.Name -Domain $p.Domain -Issuer $p.Issuer -CertificateChain $chainList -Type $p.Type -Server $blueserver -Confirm:$false -ErrorAction:Continue}
$newPrincipal = LogAndRunCmdlet $cmd
CheckNewTrustAuthorityPrincipalResult -TAPrincipal $newPrincipal
}
$Global:error.AddRange($errorBeforeExecution)
}
}
}
@@ -594,21 +577,16 @@ Function Apply-TrustedClusterSettings {
<#
.SYNOPSIS
This cmdlet applies the settings in the specific $SettingsFile to a Trusted Cluster.
.DESCRIPTION
This cmdlet applies the settings in the specific $SettingsFile to a Trusted Cluster
.PARAMETER TrustedCluster
Specifies the Trusted Cluster you want to apply the settings.
.PARAMETER SettingsFile
Specifies the file having the settings you want to apply.
.EXAMPLE
PS C:\> $ts = Get-TrustedCluster "mycluster"
PS C:\> Apply-TrustedClusterSettings -TrustedCluster $ts -SettingsFile "c:\myfile.json"
Applies the settings in file c:\myfile.json to Trusted Cluster "mycluster".
.NOTES
Author : Carrie Yang
Author email : yangm@vmware.com
@@ -637,18 +615,59 @@ Function Apply-TrustedClusterSettings {
}
if ($jsonObj.TrustedCluster.AttestationServiceInfo -ne $null) {
$attests = Get-AttestationServiceInfo | where {$($_.Name) -in $($jsonObj.TrustedCluster.AttestationServiceInfo)}
Add-TrustedClusterAttestationServiceInfo -TrustedCluster $TrustedCluster -AttestationServiceInfo $attests -Confirm:$false -Server $greenvc
$attests = Get-AttestationServiceInfo -Server $greenvc | Where-Object {$($_.Name) -in $($jsonObj.TrustedCluster.AttestationServiceInfo)}
$cmd = {Add-TrustedClusterAttestationServiceInfo -TrustedCluster $TrustedCluster -AttestationServiceInfo $attests -Confirm:$false -Server $greenvc -ErrorAction:Continue}
LogAndRunCmdlet $cmd
}
if ($jsonObj.TrustedCluster.KeyProviderServiceInfo -ne $null) {
$kms = Get-KeyProviderServiceInfo | where {$($_.Name) -in $($jsonObj.TrustedCluster.KeyProviderServiceInfo)}
Add-TrustedClusterKeyProviderServiceInfo -TrustedCluster $TrustedCluster -KeyProviderServiceInfo $kms -Confirm:$false -Server $greenvc
$kms = Get-KeyProviderServiceInfo -Server $greenvc | Where-Object {$($_.Name) -in $($jsonObj.TrustedCluster.KeyProviderServiceInfo)}
$cmd = {Add-TrustedClusterKeyProviderServiceInfo -TrustedCluster $TrustedCluster -KeyProviderServiceInfo $kms -Confirm:$false -Server $greenvc -ErrorAction:Continue}
LogAndRunCmdlet $cmd
}
}
}
Function LogAndRunCmdlet {
[CmdLetBinding()]
Param (
[Parameter(Mandatory=$True)]
[ScriptBlock] $CmdBlock
)
Process {
Write-Host "Running cmdlet: $CmdBlock"
& $CmdBlock
}
}
Function CheckNewTrustAuthorityPrincipalResult {
[CmdLetBinding()]
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][AllowNull()]
[VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustAuthorityPrincipal] $TAPrincipal
)
Begin {
$expectedCmdName = "NewTrustAuthorityPrincipal"
$expectedError = "com.vmware.esx.authentication.trust.security_token_issuers.issuer_already_exists"
}
Process {
$err = $Global:Error[0]
if (($TAPrincipal -eq $null) -and ($($err.Exception.TargetSite.Name) -eq $expectedCmdName)) {
if ($($err.Exception.InnerException) -match $expectedError) {
Write-Error "Operation didn't complete successfully. This is a known issue. Refer to https://kb.vmware.com/s/article/77146 to recover the host, then rerun New-TrustAuthorityPrincipal cmdlet to create the TrustAuthorityPrincipal for the new host please."
}
} elseif ($TAPrincipal) {
$TAPrincipal
}
}
}
Function Join-VMHost {
Param (
@@ -660,12 +679,16 @@ Function Join-VMHost {
[Parameter(Mandatory=$True)]
[System.Management.Automation.Credential()]
$Credential
$Credential,
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[String] $Server
)
Process {
Write-Host "Adding new host $VMHostAddress to cluster $ClusterName..."
Add-VMHost -Name $VMHostAddress -Credential $Credential -Location $ClusterName -Force
Add-VMHost -Name $VMHostAddress -Credential $Credential -Location $ClusterName -Server $Server -Force
}
}
@@ -680,6 +703,7 @@ Function Remove-TrustedClusterSettings {
Begin {
$greenvc = GetViServer -clusterUid $TrustedCluster.Uid
Write-Host "Removing the settings of TrustedCluster $($TrustedCluster.Name)..."
$TrustedCluster = Get-TrustedCluster $TrustedCluster.Name -Server $greenvc
}
Process {
@@ -687,7 +711,7 @@ Function Remove-TrustedClusterSettings {
Set-TrustedCluster -TrustedCluster $TrustedCluster -State Disabled -Server $greenvc -Confirm:$false
} else {
if ($TrustedCluster.KeyProviderServiceInfo -ne $null) {
Remove-TrustedClusterKeyProviderServiceInfo -TrustedCluster $TrustedCluster -KeyProviderServiceInfo $TrustedCluster.KeyProviderServiceInfo -Server $greenvc
Remove-TrustedClusterKeyProviderServiceInfo -TrustedCluster $TrustedCluster -KeyProviderServiceInfo $TrustedCluster.KeyProviderServiceInfo -Server $greenvc -Confirm:$false
}
}
}
@@ -714,23 +738,50 @@ Function IsSelfSignedClientCertificate {
$privateKeyNotSet = $False
$kpNames = [System.Collections.ArrayList]@()
if ($kp -ne $null) {
foreach ($k in $kp) {
$kp | Foreach-Object {
$k = $_
$clientCert = Get-TrustAuthorityKeyProviderClientCertificate -KeyProvider $k -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc
if ($clientCert -ne $null -and !($privateKey -ne $null -and $privateKey.ContainsKey($($k.Name)))) {
$privateKeyNotSet = $True
$silent = $kpNames.Add($k.Name)
$kpNames.Add($k.Name) | Out-Null
}
}
}
if ($privateKeyNotSet) {
$kpnameStr = [System.String]::join(",", $($kpNames))
Write-Warning "For self-signed client certificate, the cmdlet could not be able to establish the trust between the kmip servers and the keyprovider: ($kpnameStr).
Please manually use these followed cmdlets to establish the trust: New-TrustAuthorityKeyProviderClientCertificate, and Get-TrustAuthorityKeyProviderClientCertificate, then make the certificate be signed in kmip servers." -WarningAction Inquire
Write-Warning "For self-signed client certificate, the cmdlet might not be able to establish the trust between the kmip servers and the keyprovider: ($kpnameStr). `nManually try to use followed cmdlets to establish the trust: `n 1. New-TrustAuthorityKeyProviderClientCertificate;`n 2. Get-TrustAuthorityKeyProviderClientCertificate; `n then make the certificate be signed in kmip servers." -WarningAction Inquire
}
}
}
Function Is70AboveServer {
Param (
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[String] $VIServer
)
Process {
if ([String]::IsNullOrWhiteSpace($VIServer)) {
Throw "Please provide a valid vCenter Server!"
}
$SI = Get-View Serviceinstance -Server $VIServer
$apiVersion = [System.Version]$($SI.Content.About.Version)
$MajorVersion = $apiVersion.Major
$MinorVersion = $apiVersion.Minor
$buildNum = $apiVersion.Build
if (($MajorVersion -lt 7) -or ($MajorVersion -eq 7 -And $MinorVersion -eq 0 -And $buildNum -eq 0)) {
return $false
}
return $true
}
}
Function Check-VMHostVersionAndLicense {
[CmdLetBinding()]
@@ -743,7 +794,9 @@ Function Check-VMHostVersionAndLicense {
$Credential,
[Parameter(Mandatory=$True)]
[bool]$CheckLicense
[bool]$CheckLicense,
[bool]$Allow70Above=$true
)
Begin {
@@ -759,10 +812,18 @@ Function Check-VMHostVersionAndLicense {
$MajorVersion = $apiVersion.Major
$MinorVersion = $apiVersion.Minor
$buildNum = $apiVersion.Build
if ($MajorVersion -lt 7 -And $MinorVersion -ne 0 -And $buildNum -ne 0) {
if (!$Allow70Above) {
if ($MajorVersion -ne 7 -or $MinorVersion -ne 0 -or $buildNum -ne 0) {
Disconnect-VIServer -Server $server -confirm:$false
Throw "VMHost of $apiVersion is not supported, only 7.0.0 is supported...`n"
}
} else {
if ($MajorVersion -lt 7) {
Disconnect-VIServer -Server $server -confirm:$false
Throw "VMHost of $apiVersion is not supported, only 7.0.0 and above are supported...`n"
}
}
# Check license
if ($CheckLicense) {
@@ -814,21 +875,22 @@ Function Check-TrustAuthorityClusterHealth {
# Check TrustAuthorityPrincipal's healthy
$principals = Get-TrustAuthorityPrincipal -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc
foreach ($p in $principals) {
if ($p.Health -ne 'Ok') {
$principals | Foreach-Object {
if ($_.Health -ne 'Ok') {
Throw "The TrustAuthorityPrincipal $($p.Name) is not healthy, please fix it first!"
}
}
# Check TrustAuthorityKeyProvider's healthy
$kp = Get-TrustAuthorityKeyProvider -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc
foreach ($k in $kp) {
$kp | Foreach-Object {
$k = $_
if ($k.Status.Health -ne 'Ok') {
Throw "TrustAuthorityKeyProvider $($k.Name) is not healthy, please fix it first!"
}
foreach ($status in $k.Status.ServerStatus) {
if ($status.Health -ne 'Ok') {
$k.Status.ServerStatus | Foreach-Object {
if ($_.Health -ne 'Ok') {
Throw "The ServerStatus $($status.Name) in TrustAuthorityKeyProvider $($k.Name) is not healthy, please fix it first!"
}
}
@@ -843,8 +905,8 @@ Function Check-TrustAuthorityClusterHealth {
# Check tpm2Ek healthy
$tpm2Eks = Get-TrustAuthorityTpm2EndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc
if ($tpm2Eks -ne $null) {
foreach ($ek in $tpm2Eks) {
if ($ek.Health -ne 'Ok') {
$tpm2Eks | Foreach-Object {
if ($_.Health -ne 'Ok') {
Throw "TrustAuthorityTpm2EndorsementKey $($ek.Name) is not healthy, please fix it first!"
}
}
@@ -853,8 +915,8 @@ Function Check-TrustAuthorityClusterHealth {
# Check tpm2CA healthy
$tpm2cas = Get-TrustAuthorityTpm2CACertificate -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc
if ($tpm2cas -ne $null) {
foreach ($ca in $tpm2cas) {
if ($ca.Health -ne 'Ok') {
$tpm2cas | Foreach-Object {
if ($_.Health -ne 'Ok') {
Throw "TrustAuthorityTpm2CACertificate $($ca.Name) is not healthy, please fix it first!"
}
}
@@ -863,8 +925,8 @@ Function Check-TrustAuthorityClusterHealth {
# Check BaseImage healthy
$baseImages = Get-TrustAuthorityVMHostBaseImage -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc
if ($baseImages -ne $null) {
foreach ($img in $baseImages) {
if ($img.Health -ne 'Ok') {
$baseImages | Foreach-Object {
if ($_.Health -ne 'Ok') {
Throw "TrustAuthorityVMHostBaseImage $($img.Name) is not healthy, please fix it first!"
}
}
@@ -907,7 +969,7 @@ Function GetViServer {
}
}
Function ConfirmIsVCenter{
Function ConfirmIsVCenter {
<#
.SYNOPSIS
This function confirms the connected VI server is vCenter Server.
@@ -946,11 +1008,11 @@ Function ConvertFrom-X509Chain {
Process {
$certStr = $null
foreach ($c in $($CertChain.ChainElements)) {
$($CertChain.ChainElements) | Foreach-Object {
if ($certStr -eq $null) {
$certStr = [System.Convert]::ToBase64String($($c.Certificate.GetRawCertData()))
$certStr = [System.Convert]::ToBase64String($($_.Certificate.GetRawCertData()))
} else {
$certStr = $certStr, [System.Convert]::ToBase64String($($c.Certificate.GetRawCertData()))
$certStr = $certStr, [System.Convert]::ToBase64String($($_.Certificate.GetRawCertData()))
}
}
@@ -965,18 +1027,18 @@ Function ConvertTo-X509Chain {
)
Process {
$chain = new-object System.Security.Cryptography.X509Certificates.X509Chain
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
if ($certString.Length -gt 0) {
for ($i = 0; $i -lt $certString.Length - 1; $i++ ) {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import([System.Text.Encoding]::Default.GetBytes($certString[$i].replace("\n", [Environment]::NewLine)))
$silent = $chain.ChainPolicy.ExtraStore.Add($cert)
$chain.ChainPolicy.ExtraStore.Add($cert) | Out-Null
}
}
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import([System.Text.Encoding]::Default.GetBytes($certString[-1].replace("\n", [Environment]::NewLine)))
$silent = $chain.Build($cert)
$chain.Build($cert) | Out-Null
return $chain
}
@@ -984,12 +1046,11 @@ Function ConvertTo-X509Chain {
Export-ModuleMember Add-TrustAuthorityVMHost, Add-TrustedVMHost
# SIG # Begin signature block
# MIIi9AYJKoZIhvcNAQcCoIIi5TCCIuECAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCCwMEx3Ndpn/K5N
# T9PigHlgbfEAXX20xwVouOnKKMD48KCCD8swggTMMIIDtKADAgECAhBdqtQcwalQ
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDicYU2iA+clsiG
# VfuCJGR5GCDk63j+8YRckQvxLcD5yKCCD8swggTMMIIDtKADAgECAhBdqtQcwalQ
# C13tonk09GI7MA0GCSqGSIb3DQEBCwUAMH8xCzAJBgNVBAYTAlVTMR0wGwYDVQQK
# ExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3Qg
# TmV0d29yazEwMC4GA1UEAxMnU3ltYW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBT
@@ -1079,18 +1140,18 @@ Export-ModuleMember Add-TrustAuthorityVMHost, Add-TrustedVMHost
# YW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBAhBdqtQcwalQC13t
# onk09GI7MA0GCWCGSAFlAwQCAQUAoIGWMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3
# AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCoGCisGAQQBgjcCAQwx
# HDAaoRiAFmh0dHA6Ly93d3cudm13YXJlLmNvbS8wLwYJKoZIhvcNAQkEMSIEIL6r
# SvvCSJpAoQz4YvtfQH11/WevM1ULBbGfNUE3j37RMA0GCSqGSIb3DQEBAQUABIIB
# AKUHXKwZcvP2g8/l7dqWyaG7h4q/yJDxaWpk9r1mnUSw1MBR+0AOCm1mquTlpFVH
# ZD1KMQWtu1rJDz5A7XAm8/n6LpyqCCHcgMm+hiEjA8r02oTA8vMFch3OR6Z1/aad
# tOBkeln18M9kVkQ//uociG89A2LkfE35UKAhnDVcOBNlU0g43n9vSgakNdOOc0ZI
# VC2FD/tn9QPJXtcZ0LAFrCPuiIya+gvQ1aQCALUYi+aLuARNN01KBMRFG9za/JwX
# L6rwInitQt/BRNDINiuuTI96xBEMq3JjzW9AE8jF1rVqr1ISBgf8ZZUHdnNHiE91
# HxLh4zvDq7SEh2ne6UhOJg6hghAjMIIQHwYKKwYBBAGCNwMDATGCEA8wghALBgkq
# HDAaoRiAFmh0dHA6Ly93d3cudm13YXJlLmNvbS8wLwYJKoZIhvcNAQkEMSIEIEIQ
# y4E7C63SmxSxEC+1DBchnh7DW24QhvnHyMjCEuJ+MA0GCSqGSIb3DQEBAQUABIIB
# ADwK/sQPu5Vv+Jink4WM/Bf3CvrNgyfZD13TPDsMlt+tSEjghyHQ5/Xz4asgQuKB
# CSUgh0bJDaDaz9FF1oY9VUHHsonuB4sVhMKevKbXsYVuvUU65tBZ0RN+74RP/3iS
# rQAADQdIGuKBX1pmOmyE65A6pLWmJ+j05XCagPFboiXdiEcVxfCqRctK8MSyvtzd
# HOa2miNTIPEPUTVvqo/9nZCUwFhNN8TwaaOwrkMZv0NOFGk9AaGyQJuHb/IP1y2r
# cgFGtWA+WgPKftWq1s9Evk7W3WXV/nlKu55zg8K/no2Ug6+7KE0jNGUJJHg/yp6b
# gO/kfYj4sIwd5RJvOkk45QChghAjMIIQHwYKKwYBBAGCNwMDATGCEA8wghALBgkq
# hkiG9w0BBwKggg/8MIIP+AIBAzEPMA0GCWCGSAFlAwQCAQUAMIHmBgsqhkiG9w0B
# CRABBKCB1gSB0zCB0AIBAQYJKwYBBAGgMgIDMDEwDQYJYIZIAWUDBAIBBQAEIII1
# T46qC5Scv1JNpvu1aNNVzRq4lB1M9EZlbgeSsNYJAg4BbKiJKXgAAAAAAKUUzBgT
# MjAyMDA0MDIxMDI5MTguNjc5WjADAgEBoGOkYTBfMQswCQYDVQQGEwJKUDEcMBoG
# CRABBKCB1gSB0zCB0AIBAQYJKwYBBAGgMgIDMDEwDQYJYIZIAWUDBAIBBQAEIMSa
# 32tGkSO0MHzDIAL+rOzowJzdf7nOyZAYmKBTXDbnAg4BbKiJKXgAAAAAAjyk+xgT
# MjAyMDEwMTIxMDE3MTEuOTY0WjADAgEBoGOkYTBfMQswCQYDVQQGEwJKUDEcMBoG
# A1UEChMTR01PIEdsb2JhbFNpZ24gSy5LLjEyMDAGA1UEAxMpR2xvYmFsU2lnbiBU
# U0EgZm9yIEFkdmFuY2VkIC0gRzMgLSAwMDMtMDGgggxqMIIE6jCCA9KgAwIBAgIM
# M5Agd2HEJt2UUAMNMA0GCSqGSIb3DQEBCwUAMFsxCzAJBgNVBAYTAkJFMRkwFwYD
@@ -1162,15 +1223,15 @@ Export-ModuleMember Add-TrustAuthorityVMHost, Add-TrustedVMHost
# ggKFAgEBMGswWzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt
# c2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gU0hBMjU2
# IC0gRzICDDOQIHdhxCbdlFADDTANBglghkgBZQMEAgEFAKCB8DAaBgkqhkiG9w0B
# CQMxDQYLKoZIhvcNAQkQAQQwLwYJKoZIhvcNAQkEMSIEIA4jXM836yg3wGdHIpch
# UiliyMiFAI2ifPJZqDcXgJ1ZMIGgBgsqhkiG9w0BCRACDDGBkDCBjTCBijCBhwQU
# CQMxDQYLKoZIhvcNAQkQAQQwLwYJKoZIhvcNAQkEMSIEIJ1Mp8MoZoM8GN+RvFGW
# kxLQOL4htvdgNS1G5j3jevwAMIGgBgsqhkiG9w0BCRACDDGBkDCBjTCBijCBhwQU
# rmsC2QsljAmRsRYSid62aVY5HW8wbzBfpF0wWzELMAkGA1UEBhMCQkUxGTAXBgNV
# BAoTEEdsb2JhbFNpZ24gbnYtc2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0
# YW1waW5nIENBIC0gU0hBMjU2IC0gRzICDDOQIHdhxCbdlFADDTANBgkqhkiG9w0B
# AQEFAASCAQB89B/P9T38HdPsMvwHePaxCuxvcVOb0tWYORy4h/6961Hr8+uJi3g8
# oPQl5tMvsUObcO+hMG8YyXfRpQRr5YrHeWpUGdQzMMHb+gC540P+r3jm6iWoKtpR
# 1WGSnQQUqKaB7a4wZtQoizzSm9a7hB4JEcDtb2Qh2jmSr4yhMx7XmFMLo7NVlEnW
# lS6kTYR9kE4qTagRIOZW5iIUjcAaVn/uhNAOZUjatErU8c/a8vJ7TxtPj4YSaK0J
# IeC+HeUYNRrjwtSgmnU+j/xg1Jo9zUoCGJHBIEJ9iwzgCeRLJuqHKUZiAGBZm09F
# EzycbyZmxfS5ui4MX5wSMdO1ETnvkbRc
# AQEFAASCAQCw0o79lMBljtr86gcDxeF2/v1wLaLJaxTvwLJ3bYLabHR5wZUv42aO
# 3KEMzeIvLN9/mMSn7rq6vcWGZSAZVvWecDntZE9OYU7i4cQdRucXctFGpoTN6MKF
# yeX3vMbe7YfBPGJkNB6HfYp4qWy6CkWWlWXgK1MOKo+HQFORkZtDqqpoUa3soqVl
# IeCMCcJjJIrSd3LA8NFYtOUfPXRmdhcn10xke3vTBO4T7pTLdymcm3x909UN+0cE
# xIe2wMG3D3XxSN+Rx5+iz9thPISgVdOgJLP4FxQ5fU1ci56k35wXQeDnHQFyQTO+
# uF+EWBmAiBQ6cGTiYvDOZSG2Ody3NSPn
# SIG # End signature block

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'VMware.VMC.NSXT'
#

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Connect-NSXTProxy {
<#
.NOTES
@@ -83,13 +87,14 @@ Function Get-NSXTSegment {
If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else {
$method = "GET"
$segmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/segments"
$segmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/segments?page_size=100"
if($Troubleshoot) {
Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$segmentsURL`n"
}
try {
Write-Host "Retrieving NSX-T Segments ..."
if($PSVersionTable.PSEdition -eq "Core") {
$requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck
} else {
@@ -107,14 +112,53 @@ Function Get-NSXTSegment {
}
if($requests.StatusCode -eq 200) {
$baseSegmentsURL = $segmentsURL
$totalSegmentCount = ($requests.Content | ConvertFrom-Json).result_count
if($Troubleshoot) {
Write-Host -ForegroundColor cyan "`n[DEBUG] totalSegmentCount = $totalSegmentCount"
}
$totalSegments = ($requests.Content | ConvertFrom-Json).results
$seenSegments = $totalSegments.count
if($Troubleshoot) {
Write-Host -ForegroundColor cyan "`n[DEBUG] $segmentsURL (currentCount = $seenSegments)"
}
while ( $seenSegments -lt $totalSegmentCount) {
$segmentsURL = $baseSegmentsURL + "&cursor=$(($requests.Content | ConvertFrom-Json).cursor)"
try {
if($PSVersionTable.PSEdition -eq "Core") {
$requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck
} else {
$requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers
}
} catch {
if($_.Exception.Response.StatusCode -eq "Unauthorized") {
Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n"
break
} else {
Write-Error "Error in retrieving NSX-T Segments"
Write-Error "`n($_.Exception.Message)`n"
break
}
}
$segments = ($requests.Content | ConvertFrom-Json).results
$totalSegments += $segments
$seenSegments += $segments.count
if($Troubleshoot) {
Write-Host -ForegroundColor cyan "`n[DEBUG] $segmentsURL (currentCount = $seenSegments)"
}
}
if ($PSBoundParameters.ContainsKey("Name")){
$segments = $segments | where {$_.display_name -eq $Name}
$totalSegments = $totalSegments | where {$_.display_name -eq $Name}
}
$results = @()
foreach ($segment in $segments) {
foreach ($segment in $totalSegments) {
$subnets = $segment.subnets
$network = $subnets.network
@@ -877,7 +921,7 @@ Function New-NSXTGroup {
[Parameter(Mandatory=$true, ParameterSetName='IPAddress')][String[]]$IPAddress,
[Parameter(Mandatory=$true, ParameterSetName='Tag')][String]$Tag,
[Parameter(Mandatory=$true, ParameterSetName='VmName')][String]$VmName,
[Parameter(Mandatory=$true, ParameterSetName='VmName')][ValidateSet('CONTAINS','STARTSWITH')][String]$Operator,
[Parameter(Mandatory=$true, ParameterSetName='VmName')][ValidateSet('CONTAINS','STARTSWITH','EQUALS')][String]$Operator,
[Switch]$Troubleshoot
)

Binary file not shown.

View File

@@ -1,3 +1,7 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Get-VMCCommand {
<#
.NOTES

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'VMware.VMEncryption'
#

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# Script Module : VMware.VMEncryption
# Version : 1.2
@@ -1264,7 +1269,7 @@ Function Get-EntityByCryptoKey {
$VMList += $VMs|Where {$_.EncryptionKeyId|MatchKeys -KeyId $keyId -KMSClusterId $KMSClusterId}
$VMList += $VMDiskList.Parent
$VMList = $VMList|sort|Get-Unique
$VMList = $VMList|sort-object|Get-Unique
$Entities.VMList = $VMList
}

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
# Script Module : VMware.VsanEncryption
# Version : 1.0
# Author : Jase McCarty, VMware Storage & Availability Business Unit

View File

@@ -0,0 +1,95 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'VMware.WorkloadManagement'
#
# Generated by: wlam@vmware.com
#
# Generated on: 05/19/20
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'VMware.WorkloadManagement.psm1'
# Version number of this module.
ModuleVersion = '1.0.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'VMware.WorkloadManagement'
# Author of this module
Author = 'William Lam'
# Company or vendor of this module
CompanyName = 'VMware'
# Copyright statement for this module
Copyright = '(c) 2020 VMware. All rights reserved.'
# Description of the functionality provided by this module
Description = 'PowerShell Module for vSphere with Kubernetes Workload Management'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '6.0'
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'New-WorkloadManagement','Get-WorkloadManagement','Remove-WorkloadManagement'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}

View File

@@ -0,0 +1,360 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function New-WorkloadManagement {
<#
.NOTES
===========================================================================
Created by: William Lam
Date: 05/19/2020
Organization: VMware
Blog: http://www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
Enable Workload Management on vSphere 7 Cluster
.DESCRIPTION
Enable Workload Management on vSphere 7 Cluster
.PARAMETER ClusterName
Name of vSphere Cluster to enable Workload Management
.PARAMETER ControlPlaneSize
Size of Control Plane VMs (TINY, SMALL, MEDIUM, LARGE)
.PARAMETER MgmtNetwork
Management Network for Control Plane VMs
.PARAMETER MgmtNetworkStartIP
Starting IP Address for Control Plane VMs (5 consecutive free addresses)
.PARAMETER MgmtNetworkSubnet
Netmask for Management Network
.PARAMETER MgmtNetworkGateway
Gateway for Management Network
.PARAMETER MgmtNetworkDNS
DNS Server(s) to use for Management Network
.PARAMETER MgmtNetworkDNSDomain
DNS Domain(s)
.PARAMETER MgmtNetworkNTP
NTP Server(s)
.PARAMETER WorkloadNetworkVDS
Name of vSphere 7 Distributed Virtual Switch (VDS) configured with NSX-T
.PARAMETER WorkloadNetworkEdgeCluster
Name of NSX-T Edge Cluster
.PARAMETER WorkloadNetworkDNS
DNS Server(s) to use for Workloads
.PARAMETER WorkloadNetworkPodCIDR
K8s POD CIDR (default: 10.244.0.0/21)
.PARAMETER WorkloadNetworkServiceCIDR
K8S Service CIDR (default: 10.96.0.0/24)
.PARAMETER WorkloadNetworkIngressCIDR
CIDR for Workload Ingress (recommend /27 or larger)
.PARAMETER WorkloadNetworkEgressCIDR
CIDR for Workload Egress (recommend /27 or larger)
.PARAMETER ControlPlaneStoragePolicy
Name of VM Storage Policy to use for Control Plane VMs
.PARAMETER EphemeralDiskStoragePolicy
Name of VM Storage Policy to use for Ephemeral Disk
.PARAMETER ImageCacheStoragePolicy
Name of VM Storage Policy to use for Image Cache
.PARAMETER LoginBanner
Login message to show during kubectl login
.EXAMPLE
New-WorkloadManagement `
-ClusterName "Workload-Cluster" `
-ControlPlaneSize TINY `
-MgmtNetwork "DVPG-Management Network" `
-MgmtNetworkStartIP "172.17.36.51" `
-MgmtNetworkSubnet "255.255.255.0" `
-MgmtNetworkGateway "172.17.36.253" `
-MgmtNetworkDNS "172.17.31.5" `
-MgmtNetworkDNSDomain "cpub.corp" `
-MgmtNetworkNTP "5.199.135.170" `
-WorkloadNetworkVDS "Pacific-VDS" `
-WorkloadNetworkEdgeCluster "Edge-Cluster-01" `
-WorkloadNetworkDNS "172.17.31.5" `
-WorkloadNetworkIngressCIDR "172.17.36.64/27" `
-WorkloadNetworkEgressCIDR "172.17.36.96/27" `
-ControlPlaneStoragePolicy "pacific-gold-storage-policy" `
-EphemeralDiskStoragePolicy "pacific-gold-storage-policy" `
-ImageCacheStoragePolicy "pacific-gold-storage-policy"
#>
Param (
[Parameter(Mandatory=$True)]$ClusterName,
[Parameter(Mandatory=$True)][ValidateSet("TINY","SMALL","MEDIUM","LARGE")][string]$ControlPlaneSize,
[Parameter(Mandatory=$True)]$MgmtNetwork,
[Parameter(Mandatory=$True)]$MgmtNetworkStartIP,
[Parameter(Mandatory=$True)]$MgmtNetworkSubnet,
[Parameter(Mandatory=$True)]$MgmtNetworkGateway,
[Parameter(Mandatory=$True)][string[]]$MgmtNetworkDNS,
[Parameter(Mandatory=$True)][string[]]$MgmtNetworkDNSDomain,
[Parameter(Mandatory=$True)][string[]]$MgmtNetworkNTP,
[Parameter(Mandatory=$True)]$WorkloadNetworkVDS,
[Parameter(Mandatory=$True)]$WorkloadNetworkEdgeCluster,
[Parameter(Mandatory=$True)][string[]]$WorkloadNetworkDNS,
[Parameter(Mandatory=$False)]$WorkloadNetworkPodCIDR="10.244.0.0/21",
[Parameter(Mandatory=$False)]$WorkloadNetworkServiceCIDR="10.96.0.0/24",
[Parameter(Mandatory=$True)]$WorkloadNetworkIngressCIDR,
[Parameter(Mandatory=$True)]$WorkloadNetworkEgressCIDR,
[Parameter(Mandatory=$True)]$ControlPlaneStoragePolicy,
[Parameter(Mandatory=$True)]$EphemeralDiskStoragePolicy,
[Parameter(Mandatory=$True)]$ImageCacheStoragePolicy,
[Parameter(Mandatory=$False)]$LoginBanner
)
If (-Not $global:DefaultCisServers) { Write-error "No CiS Connection found, please use Connect-CisServer`n" } Else {
# Management Network Moref
$networkService = Get-CisService "com.vmware.vcenter.network"
$networkFilterSpec = $networkService.help.list.filter.Create()
$networkFilterSpec.names = @("$MgmtNetwork")
$mgmtNetworkMoRef = $networkService.list($networkFilterSpec).network.Value
if ($mgmtNetworkMoRef -eq $NULL) {
Write-Host -ForegroundColor Red "Unable to find vSphere Cluster ${MgmtNetwork}"
break
}
# Cluster Moref
$clusterService = Get-CisService "com.vmware.vcenter.cluster"
$clusterFilterSpec = $clusterService.help.list.filter.Create()
$clusterFilterSpec.names = @("$ClusterName")
$clusterMoRef = $clusterService.list($clusterFilterSpec).cluster.Value
if ($clusterMoRef -eq $NULL) {
Write-Host -ForegroundColor Red "Unable to find vSphere Cluster ${ClusterName}"
break
}
# VDS MoRef
$vdsCompatService = Get-CisService "com.vmware.vcenter.namespace_management.distributed_switch_compatibility"
$vdsMoRef = ($vdsCompatService.list($clusterMoref)).distributed_switch.Value
if ($vdsMoRef -eq $NULL) {
Write-Host -ForegroundColor Red "Unable to find VDS ${WorkloadNetworkVDS}"
break
}
# NSX-T Edge Cluster
$edgeClusterService = Get-CisService "com.vmware.vcenter.namespace_management.edge_cluster_compatibility"
$edgeClusterMoRef = ($edgeClusterService.list($clusterMoref,$vdsMoRef)).edge_cluster.Value
if ($edgeClusterMoRef -eq $NULL) {
Write-Host -ForegroundColor Red "Unable to find NSX-T Edge Cluster ${WorkloadNetworkEdgeCluster}"
break
}
# VM Storage Policy MoRef
$storagePolicyService = Get-CisService "com.vmware.vcenter.storage.policies"
$sps= $storagePolicyService.list()
$cpSP = ($sps | where {$_.name -eq $ControlPlaneStoragePolicy}).Policy.Value
$edSP = ($sps | where {$_.name -eq $EphemeralDiskStoragePolicy}).Policy.Value
$icSP = ($sps | where {$_.name -eq $ImageCacheStoragePolicy}).Policy.Value
if ($cpSP -eq $NULL) {
Write-Host -ForegroundColor Red "Unable to find VM Storage Policy ${ControlPlaneStoragePolicy}"
break
}
if ($edSP -eq $NULL) {
Write-Host -ForegroundColor Red "Unable to find VM Storage Policy ${EphemeralDiskStoragePolicy}"
break
}
if ($icSP -eq $NULL) {
Write-Host -ForegroundColor Red "Unable to find VM Storage Policy ${ImageCacheStoragePolicy}"
break
}
$nsmClusterService = Get-CisService "com.vmware.vcenter.namespace_management.clusters"
$spec = $nsmClusterService.help.enable.spec.Create()
$spec.size_hint = $ControlPlaneSize
$spec.network_provider = "NSXT_CONTAINER_PLUGIN"
$mgmtNetworkSpec = $nsmClusterService.help.enable.spec.master_management_network.Create()
$mgmtNetworkSpec.mode = "STATICRANGE"
$mgmtNetworkSpec.network = $mgmtNetworkMoRef
$mgmtNetworkSpec.address_range.starting_address = $MgmtNetworkStartIP
$mgmtNetworkSpec.address_range.address_count = 5
$mgmtNetworkSpec.address_range.subnet_mask = $MgmtNetworkSubnet
$mgmtNetworkSpec.address_range.gateway = $MgmtNetworkGateway
$spec.master_management_network = $mgmtNetworkSpec
$spec.master_DNS = $MgmtNetworkDNS
$spec.master_DNS_search_domains = $MgmtNetworkDNSDomain
$spec.master_NTP_servers = $MgmtNetworkNTP
$spec.ncp_cluster_network_spec.cluster_distributed_switch = $vdsMoRef
$spec.ncp_cluster_network_spec.nsx_edge_cluster = $edgeClusterMoRef
$spec.worker_DNS = $WorkloadNetworkDNS
$serviceCidrSpec = $nsmClusterService.help.enable.spec.service_cidr.Create()
$serviceAddress,$servicePrefix = $WorkloadNetworkServiceCIDR.split("/")
$serviceCidrSpec.address = $serviceAddress
$serviceCidrSpec.prefix = $servicePrefix
$spec.service_cidr = $serviceCidrSpec
$podCidrSpec = $nsmClusterService.help.enable.spec.ncp_cluster_network_spec.pod_cidrs.Element.Create()
$podAddress,$podPrefix = $WorkloadNetworkPodCIDR.split("/")
$podCidrSpec.address = $podAddress
$podCidrSpec.prefix = $podPrefix
$spec.ncp_cluster_network_spec.pod_cidrs = @($podCidrSpec)
$egressCidrSpec = $nsmClusterService.help.enable.spec.ncp_cluster_network_spec.egress_cidrs.Element.Create()
$egressAddress,$egressPrefix = $WorkloadNetworkEgressCIDR.split("/")
$egressCidrSpec.address = $egressAddress
$egressCidrSpec.prefix = $egressPrefix
$spec.ncp_cluster_network_spec.egress_cidrs = @($egressCidrSpec)
$ingressCidrSpec = $nsmClusterService.help.enable.spec.ncp_cluster_network_spec.ingress_cidrs.Element.Create()
$ingressAddress,$ingressPrefix = $WorkloadNetworkIngressCIDR.split("/")
$ingressCidrSpec.address = $ingressAddress
$ingressCidrSpec.prefix = $ingressPrefix
$spec.ncp_cluster_network_spec.ingress_cidrs = @($ingressCidrSpec)
$spec.master_storage_policy = $cpSP
$spec.ephemeral_storage_policy = $edSP
$imagePolicySpec = $nsmClusterService.help.enable.spec.image_storage.Create()
$imagePolicySpec.storage_policy = $icSP
$spec.image_storage = $imagePolicySpec
if($LoginBanner -eq $NULL) {
$LoginBanner = "
" + [char]::ConvertFromUtf32(0x1F973) + "vSphere with Kubernetes Cluster enabled by virtuallyGhetto " + [char]::ConvertFromUtf32(0x1F973) + "
"
}
$spec.login_banner = $LoginBanner
try {
Write-Host -Foreground Green "`nEnabling Workload Management on vSphere Cluster ${ClusterName} ..."
$nsmClusterService.enable($clusterMoRef,$spec)
} catch {
Write-Error "Error in attempting to enable Workload Management on vSphere Cluster ${ClusterName}"
Write-Error "`n($_.Exception.Message)`n"
break
}
Write-Host -Foreground Green "Please refer to the Workload Management UI in vCenter Server to monitor the progress of this operation"
}
}
Function Get-WorkloadManagement {
<#
.NOTES
===========================================================================
Created by: William Lam
Date: 05/19/2020
Organization: VMware
Blog: http://www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
Retrieve all Workload Management Clusters
.DESCRIPTION
Retrieve all Workload Management Clusters
.PARAMETER Stats
Output additional stats pertaining to CPU, Memory and Storage
.EXAMPLE
Get-WorkloadManagement
.EXAMPLE
Get-WorkloadManagement -Stats
#>
Param (
[Switch]$Stats
)
If (-Not $global:DefaultCisServers) { Write-error "No CiS Connection found, please use Connect-CisServer`n" } Else {
If (-Not $global:DefaultVIServers) { Write-error "No VI Connection found, please use Connect-VIServer`n" } Else {
$nssClusterService = Get-CisService "com.vmware.vcenter.namespace_management.software.clusters"
$nsInstanceService = Get-CisService "com.vmware.vcenter.namespaces.instances"
$nsmClusterService = Get-CisService "com.vmware.vcenter.namespace_management.clusters"
$wlClusters = $nsmClusterService.list()
$results = @()
foreach ($wlCluster in $wlClusters) {
$workloadClusterId = $wlCluster.cluster
$vSphereCluster = Get-Cluster | where {$_.id -eq "ClusterComputeResource-${workloadClusterId}"}
$workloadCluster = $nsmClusterService.get($workloadClusterId)
$nsCount = ($nsInstanceService.list() | where {$_.cluster -eq $workloadClusterId}).count
$hostCount = ($vSphereCluster.ExtensionData.Host).count
if($workloadCluster.kubernetes_status -ne "ERROR") {
$k8sVersion = $nssClusterService.get($workloadClusterId).current_version
} else { $k8sVersion = "UNKNOWN" }
$tmp = [pscustomobject] @{
NAME = $vSphereCluster.name;
NAMESPACES = $nsCount;
HOSTS = $hostCount;
CONTROL_PLANE_IP = $workloadCluster.api_server_cluster_endpoint;
CLUSTER_STATUS = $workloadCluster.config_status;
K8S_STATUS = $workloadCluster.kubernetes_status;
VERSION = $k8sVersion;
}
if($Stats) {
$tmp | Add-Member -NotePropertyName CPU_CAPACITY -NotePropertyValue $workloadCluster.stat_summary.cpu_capacity
$tmp | Add-Member -NotePropertyName MEM_CAPACITY -NotePropertyValue $workloadCluster.stat_summary.memory_capacity
$tmp | Add-Member -NotePropertyName STORAGE_CAPACITY -NotePropertyValue $workloadCluster.stat_summary.storage_capacity
$tmp | Add-Member -NotePropertyName CPU_USED -NotePropertyValue $workloadCluster.stat_summary.cpu_used
$tmp | Add-Member -NotePropertyName MEM_USED -NotePropertyValue $workloadCluster.stat_summary.memory_used
$tmp | Add-Member -NotePropertyName STORAGE_USED -NotePropertyValue $workloadCluster.stat_summary.storage_used
}
$results+=$tmp
}
$results
}
}
}
Function Remove-WorkloadManagement {
<#
.NOTES
===========================================================================
Created by: William Lam
Date: 05/19/2020
Organization: VMware
Blog: http://www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
Disable Workload Management on vSphere Cluster
.DESCRIPTION
Disable Workload Management on vSphere Cluster
.PARAMETER ClusterName
Name of vSphere Cluster to disable Workload Management
.EXAMPLE
Remove-WorkloadManagement -ClusterName "Workload-Cluster"
#>
Param (
[Parameter(Mandatory=$True)]$ClusterName
)
If (-Not $global:DefaultCisServers) { Write-error "No CiS Connection found, please use Connect-CisServer`n" } Else {
$vSphereCluster = Get-Cluster | where {$_.Name -eq $ClusterName}
if($vSphereCluster -eq $null) {
Write-Host -ForegroundColor Red "Unable to find vSphere Cluster ${ClusterName}"
break
}
$vSphereClusterID = ($vSphereCluster.id).replace("ClusterComputeResource-","")
$nsmClusterService = Get-CisService "com.vmware.vcenter.namespace_management.clusters"
$workloadClusterID = ($nsmClusterService.list() | where {$_.cluster -eq $vSphereClusterID}).cluster.Value
if($workloadClusterID -eq $null) {
Write-Host -ForegroundColor Red "Unable to find Workload Management Cluster ${ClusterName}"
break
}
try {
Write-Host -Foreground Green "`nDisabling Workload Management on vSphere Cluster ${ClusterName} ..."
$nsmClusterService.disable($workloadClusterID)
} catch {
Write-Error "Error in attempting to disable Workload Management on vSphere Cluster ${ClusterName}"
Write-Error "`n($_.Exception.Message)`n"
break
}
Write-Host -Foreground Green "Please refer to the Workload Management UI in vCenter Server to monitor the progress of this operation"
}
}

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Module manifest for module 'VMware.HCX'
#

View File

@@ -1,3 +1,8 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
Function Connect-WorkspaceOneAccess {
<#
.NOTES

View File

@@ -0,0 +1,329 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Get-SsoAuthenticationPolicy {
<#
.NOTES
===========================================================================
Created on: 7/28/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Gets Authentication Policy
.DESCRIPTION
Gets Authentication Policy.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-SsoAuthenticationPolicy
Gets the Authentication Policy for the connected servers
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($null -ne $Server) {
$serversToProcess = $Server
}
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
# Output is the result of 'GetAuthenticationPolicy'
try {
$connection.Client.GetAuthenticationPolicy()
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
}
function Set-SsoAuthenticationPolicy {
<#
.NOTES
===========================================================================
Created on: 7/28/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Updates Authentication Policy
.DESCRIPTION
Updates Authentication Policy settings
.PARAMETER AuthenticationPolicy
An AuthenticationPolicy to update retrieved from Set-SsoAuthenticationPolicy cmdlet
.PARAMETER PasswordAuthnEnabled
Enables or disables Password Authentication
.PARAMETER WindowsAuthnEnabled
Enables or disables Windows Authentication
.PARAMETER SmartCardAuthnEnabled
Enables or disables Smart Card Authentication
.PARAMETER CRLCacheSize
Specifies CRL Cache size
.PARAMETER CRLUrl
Specifies CRL Url
.PARAMETER OCSPEnabled
Enables or disables OCSP
.PARAMETER OCSPResponderSigningCert
OCSP Responder Signing Certificate
.PARAMETER OCSPUrl
.PARAMETER OIDs
.PARAMETER SendOCSPNonce
.PARAMETER TrustedCAs
.PARAMETER UseCRLAsFailOver,
.PARAMETER UseInCertCRL
.EXAMPLE
$myServer = Connect-SsoAdminServer -Server MyServer -User myUser -Password myPassword
Get-SsoAuthenticationPolicy -Server $myServer | Set-SsoAuthenticationPolicy -SmartCardAuthnEnabled $true
Enables SmartCard Authnetication on server $myServer
#>
[CmdletBinding(ConfirmImpact = 'Medium')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'AuthenticationPolicy object to update')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.AuthenticationPolicy]
$AuthenticationPolicy,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Enables or disables Password Authentication')]
[bool]
$PasswordAuthnEnabled,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Enables or disables Windows Authentication')]
[bool]
$WindowsAuthnEnabled,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Enables or disables Smart Card Authentication')]
[bool]
$SmartCardAuthnEnabled,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'CRL Cache size')]
[int]
$CRLCacheSize,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'CRL Url')]
[string]
$CRLUrl,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Enables or disables OCSP')]
[bool]
$OCSPEnabled,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'OCSP Responder Signing Certificate')]
[System.Security.Cryptography.X509Certificates.X509Certificate2]
$OCSPResponderSigningCert,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'OCSP Url')]
[string]
$OCSPUrl,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'OIDs')]
[string[]]
$OIDs,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Enables or disables seinding OCSP Nonce')]
[bool]
$SendOCSPNonce,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'List of trusted CAs')]
[string[]]
$TrustedCAs,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Specifies whether to use CRL fail over')]
[bool]
$UseCRLAsFailOver,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Specifiеs whether to use CRL from certificate')]
[bool]
$UseInCertCRL)
Process {
try {
foreach ($a in $AuthenticationPolicy) {
$ssoAdminClient = $a.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$a' is from disconnected server"
continue
}
if (-not $PSBoundParameters.ContainsKey('PasswordAuthnEnabled')) {
$PasswordAuthnEnabled = $a.PasswordAuthnEnabled
}
if (-not $PSBoundParameters.ContainsKey('WindowsAuthnEnabled')) {
$WindowsAuthnEnabled = $a.WindowsAuthnEnabled
}
if (-not $PSBoundParameters.ContainsKey('SmartCardAuthnEnabled')) {
$SmartCardAuthnEnabled = $a.SmartCardAuthnEnabled
}
if (-not $PSBoundParameters.ContainsKey('CRLCacheSize')) {
$CRLCacheSize = $a.CRLCacheSize
}
if (-not $PSBoundParameters.ContainsKey('CRLUrl')) {
$CRLUrl = $a.CRLUrl
}
if (-not $PSBoundParameters.ContainsKey('OCSPEnabled')) {
$OCSPEnabled = $a.OCSPEnabled
}
if (-not $PSBoundParameters.ContainsKey('OCSPResponderSigningCert')) {
$OCSPResponderSigningCert = $a.OCSPResponderSigningCert
}
if (-not $PSBoundParameters.ContainsKey('OCSPUrl')) {
$OCSPUrl = $a.OCSPUrl
}
if (-not $PSBoundParameters.ContainsKey('OIDs')) {
$OIDs = $a.OIDs
}
if (-not $PSBoundParameters.ContainsKey('SendOCSPNonce')) {
$SendOCSPNonce = $a.SendOCSPNonce
}
if (-not $PSBoundParameters.ContainsKey('TrustedCAs')) {
$TrustedCAs = $a.TrustedCAs
}
if (-not $PSBoundParameters.ContainsKey('UseCRLAsFailOver')) {
$UseCRLAsFailOver = $a.UseCRLAsFailOver
}
if (-not $PSBoundParameters.ContainsKey('UseInCertCRL')) {
$UseInCertCRL = $a.UseInCertCRL
}
$ssoAdminClient.SetAuthenticationPolicy(
$PasswordAuthnEnabled,
$WindowsAuthnEnabled,
$SmartCardAuthnEnabled,
$CRLCacheSize,
$CRLUrl,
$OCSPEnabled,
$OCSPResponderSigningCert,
$OCSPUrl,
$OIDs,
$SendOCSPNonce,
$TrustedCAs,
$UseCRLAsFailOver,
$UseInCertCRL
)
# Output updated policy
Write-Output ($ssoAdminClient.GetAuthenticationPolicy())
}
} catch {
Write-Error (FormatError $_.Exception)
}
}
}

View File

@@ -0,0 +1,187 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Connect-SsoAdminServer {
<#
.NOTES
===========================================================================
Created on: 9/29/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function establishes a connection to a vSphere SSO Admin server.
.PARAMETER Server
Specifies the IP address or the DNS name of the vSphere server to which you want to connect.
.PARAMETER User
Specifies the user name you want to use for authenticating with the server.
.PARAMETER Password
Specifies the password you want to use for authenticating with the server.
.PARAMETER Credential
Specifies a PSCredential object to for authenticating with the server.
.PARAMETER SkipCertificateCheck
Specifies whether server Tls certificate validation will be skipped
.EXAMPLE
Connect-SsoAdminServer -Server my.vc.server -User myAdmin@vsphere.local -Password MyStrongPa$$w0rd
Connects 'myAdmin@vsphere.local' user to Sso Admin server 'my.vc.server'
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'IP address or the DNS name of the vSphere server')]
[string]
$Server,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'User name you want to use for authenticating with the server',
ParameterSetName = 'UserPass')]
[string]
$User,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Password you want to use for authenticating with the server',
ParameterSetName = 'UserPass')]
[VMware.vSphere.SsoAdmin.Utils.StringToSecureStringArgumentTransformationAttribute()]
[SecureString]
$Password,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'PSCredential object to use for authenticating with the server',
ParameterSetName = 'Credential')]
[PSCredential]
$Credential,
[Parameter(
Mandatory = $false,
HelpMessage = 'Skips server Tls certificate validation')]
[switch]
$SkipCertificateCheck)
Process {
$certificateValidator = $null
if ($SkipCertificateCheck) {
$certificateValidator = New-Object 'VMware.vSphere.SsoAdmin.Utils.AcceptAllX509CertificateValidator'
}
$ssoAdminServer = $null
try {
if ($PSBoundParameters.ContainsKey('Credential')) {
$ssoAdminServer = New-Object `
'VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer' `
-ArgumentList @(
$Server,
$Credential.UserName,
$Credential.Password,
$certificateValidator)
} else {
$ssoAdminServer = New-Object `
'VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer' `
-ArgumentList @(
$Server,
$User,
$Password,
$certificateValidator)
}
}
catch {
Write-Error (FormatError $_.Exception)
}
if ($ssoAdminServer -ne $null) {
$existingConnectionIndex = $global:DefaultSsoAdminServers.IndexOf($ssoAdminServer)
if ($existingConnectionIndex -ge 0) {
$global:DefaultSsoAdminServers[$existingConnectionIndex].RefCount++
$ssoAdminServer = $global:DefaultSsoAdminServers[$existingConnectionIndex]
}
else {
# Update $global:DefaultSsoAdminServers varaible
$global:DefaultSsoAdminServers.Add($ssoAdminServer) | Out-Null
}
# Function Output
Write-Output $ssoAdminServer
}
}
}
function Disconnect-SsoAdminServer {
<#
.NOTES
===========================================================================
Created on: 9/29/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function closes the connection to a vSphere SSO Admin server.
.PARAMETER Server
Specifies the vSphere SSO Admin systems you want to disconnect from
.EXAMPLE
$mySsoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd'
Disconnect-SsoAdminServer -Server $mySsoAdminConnection
Disconnect a SSO Admin connection stored in 'mySsoAdminConnection' varaible
#>
[CmdletBinding()]
param(
[Parameter(
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdmin.Utils.StringToSsoAdminServerArgumentTransformationAttribute()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer[]]
$Server
)
Process {
if (-not $PSBoundParameters['Server']) {
switch (@($global:DefaultSsoAdminServers).count) {
{ $_ -eq 1 } { $server = ($global:DefaultSsoAdminServers).ToArray()[0] ; break }
{ $_ -gt 1 } {
Throw 'Connected to more than 1 SSO server, please specify a SSO server via -Server parameter'
break
}
Default {
Throw 'Not connected to SSO server.'
}
}
}
foreach ($requestedServer in $Server) {
if ($requestedServer.IsConnected) {
$requestedServer.Disconnect()
}
if ($global:DefaultSsoAdminServers.Contains($requestedServer) -and $requestedServer.RefCount -eq 0) {
$global:DefaultSsoAdminServers.Remove($requestedServer) | Out-Null
}
}
}
}

View File

@@ -0,0 +1,652 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function New-SsoGroup {
<#
.NOTES
===========================================================================
Created on: 5/25/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Creates Local Sso Group
.DESCRIPTION
Creates Local Sso Group
.PARAMETER Name
Specifies the name of the group.
.PARAMETER Description
Specifies an optional description of the group.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
New-SsoGroup -Name 'myGroup' -Description 'My Group Description'
Creates a local group with name 'myGroup' and description 'My Group Description'
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Specifies the name of the group')]
[string]
$Name,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Specifies the description of the group')]
[string]
$Description,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
# Output is the result of 'CreateLocalGroup'
try {
$connection.Client.CreateLocalGroup(
$Name,
$Description
)
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
}
function Get-SsoGroup {
<#
.NOTES
===========================================================================
Created on: 9/29/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function gets domain groups.
.PARAMETER Name
Specifies Name to filter on when searching for groups.
.PARAMETER Domain
Specifies the Domain in which search will be applied, default is 'localos'.
.PARAMETER Group
Specifies the group in which search for person user members will be applied.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-SsoGroup -Name administrators -Domain vsphere.local
Gets 'adminsitrators' group in 'vsphere.local' domain
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Name filter to be applied when searching for group')]
[string]
$Name,
[Parameter(
ParameterSetName = 'ByNameAndDomain',
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain name to search in, default is "localos"')]
[string]
$Domain = 'localos',
[Parameter(
ParameterSetName = 'ByGroup',
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Searches group members of the specified group')]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$Group,
[Parameter(
ParameterSetName = 'ByNameAndDomain',
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($null -ne $Server) {
$serversToProcess = $Server
}
if ($null -eq $Name) {
$Name = [string]::Empty
}
try {
if ($null -ne $Group) {
foreach ($g in $Group) {
$ssoAdminClient = $g.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$g' is from disconnected server"
continue
}
foreach ($resultGroup in $ssoAdminClient.GetGroupsInGroup(
(RemoveWildcardSymbols $Name),
$Group)) {
if ([string]::IsNullOrEmpty($Name) ) {
Write-Output $resultGroup
}
else {
# Apply Name filtering
if ((HasWildcardSymbols $Name) -and `
$resultGroup.Name -like $Name) {
Write-Output $resultGroup
}
elseif ($resultGroup.Name -eq $Name) {
# Exactly equal
Write-Output $resultGroup
}
}
}
}
} else {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
foreach ($resultGroup in $connection.Client.GetGroups(
(RemoveWildcardSymbols $Name),
$Domain)) {
if ([string]::IsNullOrEmpty($Name) ) {
Write-Output $resultGroup
}
else {
# Apply Name filtering
if ((HasWildcardSymbols $Name) -and `
$resultGroup.Name -like $Name) {
Write-Output $resultGroup
}
elseif ($resultGroup.Name -eq $Name) {
# Exactly equal
Write-Output $resultGroup
}
}
}
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Set-SsoGroup {
<#
.NOTES
===========================================================================
Created on: 5/25/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Updates Local Sso Group
.DESCRIPTION
Updates Local Sso Group details
.PARAMETER Group
Specifies the group instace to update.
.PARAMETER Description
Specifies a description of the group.
.EXAMPLE
$myGroup = New-SsoGroup -Name 'myGroup'
$myGroup | Set-SsoGroup -Description 'My Group Description'
Updates local group $myGroup with description 'My Group Description'
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Group instance you want to update')]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$Group,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Specifies the description of the group')]
[string]
$Description)
Process {
try {
foreach ($g in $Group) {
$ssoAdminClient = $g.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$g' is from disconnected server"
continue
}
$ssoAdminClient.UpdateLocalGroup($g, $Description)
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Remove-SsoGroup {
<#
.NOTES
===========================================================================
Created on: 5/25/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function removes existing local group.
.PARAMETER Group
Specifies the Group instance to remove.
.EXAMPLE
$ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd'
$myNewGroup = New-SsoGroup -Server $ssoAdminConnection -Name 'myGroup'
Remove-SsoGroup -Group $myNewGroup
Remove plocal group with name 'myGroup'
#>
[CmdletBinding(ConfirmImpact = 'High')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Group instance you want to remove')]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$Group)
Process {
try {
foreach ($g in $Group) {
$ssoAdminClient = $g.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$g' is from disconnected server"
continue
}
$ssoAdminClient.RemoveLocalGroup($g)
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Add-GroupToSsoGroup {
<#
.NOTES
===========================================================================
Created on: 5/26/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Adds a group to another group
.DESCRIPTION
Adds the specified group on $Group parameter to target group specified on $TargetGroup parameter
.PARAMETER Group
A Group instance to be added to the $TargetGroup
.PARAMETER TargetGroup
A target group to which the $Group will be added.
.EXAMPLE
$administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local'
Get-SsoGroup -Name 'TestGroup' -Domain 'MyDomain' | Add-GroupToSsoGroup -TargetGroup $administratosGroup
Adds 'TestGroup' from 'MyDomain' domain to vsphere.local Administrators group.
#>
[CmdletBinding(ConfirmImpact = 'Medium')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'SsoGroup instance you want to add to the target group')]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$Group,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Target SsoGroup instance where the $Group wtill be added')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$TargetGroup)
Process {
try {
foreach ($g in $Group) {
$ssoAdminClient = $g.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$g' is from disconnected server"
continue
}
if ($g.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) {
Write-Error "Group '$g' is not from the same server as the target group"
continue
}
$result = $ssoAdminClient.AddGroupToGroup($g, $TargetGroup)
if (-not $result) {
Write-Error "Group '$g' was not added to the target group. The Server operation result doesn't indicate success"
continue
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Remove-GroupFromSsoGroup {
<#
.NOTES
===========================================================================
Created on: 5/26/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Removes a group to another group
.DESCRIPTION
Removes the specified group on $Group parameter from target group specified on $TargetGroup parameter
.PARAMETER Group
A Group instance to be removed from the $TargetGroup
.PARAMETER TargetGroup
A target group from which the $Group will be removed.
.EXAMPLE
$administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local'
Get-SsoGroup -Name 'TestGroup' -Domain 'MyDomain' | Remove-GroupFromSsoGroup -TargetGroup $administratosGroup
Removes 'TestGroup' from 'MyDomain' domain from vsphere.local Administrators group.
#>
[CmdletBinding(ConfirmImpact = 'Medium')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'SsoGroup instance you want to remove from the target group')]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$Group,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Target SsoGroup instance from which the $Group wtill be removed')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$TargetGroup)
Process {
try {
foreach ($g in $Group) {
$ssoAdminClient = $g.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$g' is from disconnected server"
continue
}
if ($g.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) {
Write-Error "Group '$g' is not from the same server as the target group"
continue
}
$result = $ssoAdminClient.RemoveGroupFromGroup($g, $TargetGroup)
if (-not $result) {
Write-Error "Group '$g' was not removed to the target group. The Server operation result doesn't indicate success"
continue
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Add-UserToSsoGroup {
<#
.NOTES
===========================================================================
Created on: 5/26/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Adds an user to a group
.DESCRIPTION
Adds the user on $User parameter to target group specified on $TargetGroup parameter
.PARAMETER User
A PersonUser instance to be added to the $TargetGroup
.PARAMETER TargetGroup
A target group to which the $User will be added.
.EXAMPLE
$administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local'
Get-SsoPersonUser -Name 'TestUser' -Domain 'MyDomain' | Add-UserToSsoGroup -TargetGroup $administratosGroup
Adds 'TestUser' from 'MyDomain' domain to vsphere.local Administrators group.
#>
[CmdletBinding(ConfirmImpact = 'Medium')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'PersonUser instance you want to add to the target group')]
[VMware.vSphere.SsoAdminClient.DataTypes.PersonUser]
$User,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Target SsoGroup instance where the $Group wtill be added')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$TargetGroup)
Process {
try {
foreach ($u in $User) {
$ssoAdminClient = $u.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$u' is from disconnected server"
continue
}
if ($u.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) {
Write-Error "User '$u' is not from the same server as the target group"
continue
}
$result = $ssoAdminClient.AddPersonUserToGroup($u, $TargetGroup)
if (-not $result) {
Write-Error "User '$u' was not added to the target group. The Server operation result doesn't indicate success"
continue
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Remove-UserFromSsoGroup {
<#
.NOTES
===========================================================================
Created on: 5/26/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.SYNOPSIS
Removes a person user from group
.DESCRIPTION
Removes the specified person user on $User parameter from target group specified on $TargetGroup parameter
.PARAMETER User
A PersonUser instance to be removed from the $TargetGroup
.PARAMETER TargetGroup
A target group from which the $User will be removed.
.EXAMPLE
$administratosGroup = Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local'
Get-SsoPersonUser -Name 'TestUser' -Domain 'MyDomain' | Remove-UserFromSsoGroup -TargetGroup $administratosGroup
Removes 'TestUser' from 'MyDomain' domain from vsphere.local Administrators group.
#>
[CmdletBinding(ConfirmImpact = 'Medium')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'PersonUser instance you want to remove from the target group')]
[VMware.vSphere.SsoAdminClient.DataTypes.PersonUser]
$User,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Target SsoGroup instance from which the $User wtill be removed')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$TargetGroup)
Process {
try {
foreach ($u in $User) {
$ssoAdminClient = $u.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$u' is from disconnected server"
continue
}
if ($u.GetClient().ServiceUri -ne $TargetGroup.GetClient().ServiceUri) {
Write-Error "User '$u' is not from the same server as the target group"
continue
}
$result = $ssoAdminClient.RemovePersonUserFromGroup($u, $TargetGroup)
if (-not $result) {
Write-Error "User '$u' was not removed to the target group. The Server operation result doesn't indicate success"
continue
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}

View File

@@ -0,0 +1,872 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Add-ExternalDomainIdentitySource {
<#
.NOTES
===========================================================================
Created on: 2/11/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function adds Identity Source of ActiveDirectory, OpenLDAP or NIS type.
.PARAMETER Name
Name of the identity source
.PARAMETER DomainName
Domain name
.PARAMETER DomainAlias
Domain alias
.PARAMETER PrimaryUrl
Primary Server URL
.PARAMETER BaseDNUsers
Base distinguished name for users
.PARAMETER BaseDNGroups
Base distinguished name for groups
.PARAMETER Username
Domain authentication user name
.PARAMETER Passowrd
Domain authentication password
.PARAMETER DomainServerType
Type of the ExternalDomain, one of 'ActiveDirectory','OpenLdap','NIS'
.PARAMETER Default
Sets the Identity Source as the defualt for the SSO
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Add-ExternalDomainIdentitySource `
-Name 'sof-powercli' `
-DomainName 'sof-powercli.vmware.com' `
-DomainAlias 'sof-powercli' `
-PrimaryUrl 'ldap://sof-powercli.vmware.com:389' `
-BaseDNUsers 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' `
-BaseDNGroups 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' `
-Username 'sofPowercliAdmin' `
-Password '$up3R$Tr0Pa$$w0rD'
Adds External Identity Source
#>
[CmdletBinding()]
[Alias("Add-ActiveDirectoryIdentitySource")]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Friendly name of the identity source')]
[ValidateNotNull()]
[string]
$Name,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[ValidateNotNull()]
[string]
$DomainName,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[string]
$DomainAlias,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[ValidateNotNull()]
[string]
$PrimaryUrl,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Base distinguished name for users')]
[ValidateNotNull()]
[string]
$BaseDNUsers,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Base distinguished name for groups')]
[ValidateNotNull()]
[string]
$BaseDNGroups,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain authentication user name')]
[ValidateNotNull()]
[string]
$Username,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain authentication password')]
[ValidateNotNull()]
[string]
$Password,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'External domain server type')]
[ValidateSet('ActiveDirectory')]
[string]
$DomainServerType = 'ActiveDirectory',
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Sets the Identity Source as default')]
[Switch]
$Default,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$connection.Client.AddActiveDirectoryExternalDomain(
$DomainName,
$DomainAlias,
$Name,
$PrimaryUrl,
$BaseDNUsers,
$BaseDNGroups,
$Username,
$Password,
$DomainServerType);
if ($Default) {
$connection.Client.SetDefaultIdentitySource($Name)
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
function Add-LDAPIdentitySource {
<#
.NOTES
===========================================================================
Created on: 2/11/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function adds LDAP Identity Source of ActiveDirectory, OpenLDAP or NIS type.
.PARAMETER Name
Friendly name of the identity source
.PARAMETER DomainName
Domain name
.PARAMETER DomainAlias
Domain alias
.PARAMETER PrimaryUrl
Primary Server URL
.PARAMETER SecondaryUrl
Secondary Server URL
.PARAMETER BaseDNUsers
Base distinguished name for users
.PARAMETER BaseDNGroups
Base distinguished name for groups
.PARAMETER Username
Domain authentication user name
.PARAMETER Passowrd
Domain authentication password
.PARAMETER Credential
Domain authentication credential
.PARAMETER ServerType
Type of the ExternalDomain, one of 'ActiveDirectory','OpenLdap','NIS'
.PARAMETER Certificates
List of X509Certicate2 LDAP certificates
.PARAMETER Default
Sets the Identity Source as the defualt for the SSO
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
Adds LDAP Identity Source
.EXAMPLE
Add-LDAPIdentitySource `
-Name 'sof-powercli' `
-DomainName 'sof-powercli.vmware.com' `
-DomainAlias 'sof-powercli' `
-PrimaryUrl 'ldap://sof-powercli.vmware.com:389' `
-BaseDNUsers 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' `
-BaseDNGroups 'CN=Users,DC=sof-powercli,DC=vmware,DC=com' `
-Username 'sofPowercliAdmin@sof-powercli.vmware.com' `
-Password '$up3R$Tr0Pa$$w0rD' `
-Certificates 'C:\Temp\test.cer'
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Friendly name of the identity source')]
[ValidateNotNull()]
[string]
$Name,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[ValidateNotNull()]
[string]
$DomainName,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[string]
$DomainAlias,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[string]
$SecondaryUrl,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[ValidateNotNull()]
[string]
$PrimaryUrl,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Base distinguished name for users')]
[ValidateNotNull()]
[string]
$BaseDNUsers,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Base distinguished name for groups')]
[ValidateNotNull()]
[string]
$BaseDNGroups,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain authentication user name',
ParameterSetName = 'DomainAuthenticationPassword')]
[ValidateNotNull()]
[string]
$Username,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain authentication password',
ParameterSetName = 'DomainAuthenticationPassword')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdmin.Utils.StringToSecureStringArgumentTransformationAttribute()]
[SecureString]
$Password,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'PSCredential object to use for authenticating with the LDAP',
ParameterSetName = 'DomainAuthenticationCredential')]
[PSCredential]
$Credential,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Ldap Certificates')]
[System.Security.Cryptography.X509Certificates.X509Certificate2[]]
$Certificates,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Ldap Server type')]
[ValidateSet('ActiveDirectory', 'OpenLdap')]
[string]
$ServerType = 'ActiveDirectory',
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Sets the Identity Source as default')]
[Switch]
$Default,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$authenticationUserName = ""
$authenticationPassword = ""
if ($PSBoundParameters.ContainsKey('Credential')) {
$authenticationUserName = $Credential.UserName
$authenticationPassword = $Credential.Password
} else {
$authenticationUserName = $Username
$authenticationPassword = $Password
}
$connection.Client.AddLdapIdentitySource(
$DomainName,
$DomainAlias,
$Name,
$PrimaryUrl,
$SecondaryUrl,
$BaseDNUsers,
$BaseDNGroups,
$authenticationUserName,
$authenticationPassword,
$ServerType,
$Certificates);
if ($Default) {
$connection.Client.SetDefaultIdentitySource($Name)
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
function Set-LDAPIdentitySource {
<#
.NOTES
===========================================================================
Created on: 2/17/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function adds LDAP Identity Source of ActiveDirectory, OpenLDAP or NIS type.
.PARAMETER IdentitySource
Identity Source to update
.PARAMETER Certificates
List of X509Certicate2 LDAP certificates
.PARAMETER Username
Domain authentication user name
.PARAMETER Passowrd
Domain authentication password
.PARAMETER Credential
Domain authentication credential
.PARAMETER Default
Sets the Identity Source as the defualt for the SSO
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
Updates LDAP Identity Source
.EXAMPLE
Updates certificate of a LDAP identity source
Get-IdentitySource -External | `
Set-LDAPIdentitySource `
-Certificates 'C:\Temp\test.cer'
.EXAMPLE
Updates certificate of a LDAP identity source authentication password
Get-IdentitySource -External | `
Set-LDAPIdentitySource `
-Username 'sofPowercliAdmin@sof-powercli.vmware.com' `
-Password '$up3R$Tr0Pa$$w0rD'
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Identity source to update')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.ActiveDirectoryIdentitySource]
$IdentitySource,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Ldap Certificates',
ParameterSetName = 'UpdateCertificates')]
[System.Security.Cryptography.X509Certificates.X509Certificate2[]]
$Certificates,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain authentication user name',
ParameterSetName = 'DomainAuthenticationPassword')]
[ValidateNotNull()]
[string]
$Username,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain authentication password',
ParameterSetName = 'DomainAuthenticationPassword')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdmin.Utils.StringToSecureStringArgumentTransformationAttribute()]
[SecureString]
$Password,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'PSCredential object to use for authenticating with the LDAP',
ParameterSetName = 'DomainAuthenticationCredential')]
[PSCredential]
$Credential,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
ParameterSetName = 'SetAsDefault',
HelpMessage = 'Sets the Identity Source as default')]
[Switch]
$Default,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($null -ne $Server) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
if ($PSBoundParameters.ContainsKey('Certificates')) {
$connection.Client.UpdateLdapIdentitySource(
$IdentitySource.Name,
$IdentitySource.FriendlyName,
$IdentitySource.PrimaryUrl,
$IdentitySource.FailoverUrl,
$IdentitySource.UserBaseDN,
$IdentitySource.GroupBaseDN,
$Certificates);
}
$authenticationUserName = $null
$authenticationPassword = $null
if ($PSBoundParameters.ContainsKey('Credential')) {
$authenticationUserName = $Credential.UserName
$authenticationPassword = $Credential.Password
}
if ($PSBoundParameters.ContainsKey('Password')) {
$authenticationUserName = $Username
$authenticationPassword = $Password
}
if ($null -ne $authenticationPassword) {
$connection.Client.UpdateLdapIdentitySourceAuthentication(
$IdentitySource.Name,
$authenticationUserName,
$authenticationPassword);
}
if ($Default) {
$connection.Client.SetDefaultIdentitySource($IdentitySource.Name)
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Set-IdentitySource {
<#
.NOTES
===========================================================================
Created on: 2/25/2022
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
Updates IDentitySource
.PARAMETER IdentitySource
Identity Source to update
.PARAMETER Default
Sets the Identity Source as the defualt for the SSO
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
Updates LDAP Identity Source
.EXAMPLE
Updates certificate of a LDAP identity source
Get-IdentitySource -External | Set-IdentitySource -Default
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Identity source to update')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.IdentitySource]
$IdentitySource,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Sets the Identity Source as default')]
[Switch]
$Default,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($null -ne $Server) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
if ($Default) {
$connection.Client.SetDefaultIdentitySource($IdentitySource.Name)
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Get-IdentitySource {
<#
.NOTES
===========================================================================
Created on: 11/26/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function gets Identity Source.
.PARAMETER Localos
Filter parameter to return only the localos domain identity source
.PARAMETER System
Filter parameter to return only the system domain identity source
.PARAMETER External
Filter parameter to return only the external domain identity sources
.PARAMETER Default
Filter parameter to return only the default domain identity sources
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-IdentitySource -External
Gets all external domain identity source
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Returns only the localos domain identity source')]
[Switch]
$Localos,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Returns only the system domain identity source')]
[Switch]
$System,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Returns only the external domain identity sources')]
[Switch]
$External,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Returns only the default domain identity sources')]
[Switch]
$Default,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$resultIdentitySources = @()
$allIdentitySources = $connection.Client.GetDomains()
if (-not $Localos -and -not $System -and -not $External) {
$resultIdentitySources = $allIdentitySources
}
if ($Localos) {
$resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.LocalOSIdentitySource] }
}
if ($System) {
$resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.SystemIdentitySource] }
}
if ($External) {
$resultIdentitySources += $allIdentitySources | Where-Object { $_ -is [VMware.vSphere.SsoAdminClient.DataTypes.ActiveDirectoryIdentitySource] }
}
if ($Default) {
$resultIdentitySources = @()
$defaultDomainName = $connection.Client.GetDefaultIdentitySourceDomainName()
$resultIdentitySources = $allIdentitySources | Where-Object { $_.Name -eq $defaultDomainName }
}
#Return result
$resultIdentitySources
}
}
function Remove-IdentitySource {
<#
.NOTES
===========================================================================
Created on: 03/19/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function removes Identity Source.
.PARAMETER IdentitySource
The identity source to remove
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-IdentitySource -External | Remove-IdentitySource
Removes all external domain identity source
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Identity source to remove')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.IdentitySource]
$IdentitySource,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$connection.Client.DeleteDomain($IdentitySource.Name)
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}

View File

@@ -0,0 +1,164 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Get-SsoLockoutPolicy {
<#
.NOTES
===========================================================================
Created on: 9/30/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function gets lockout policy.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-SsoLockoutPolicy
Gets lockout policy for the server connections available in $global:defaultSsoAdminServers
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$connection.Client.GetLockoutPolicy();
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Set-SsoLockoutPolicy {
<#
.NOTES
===========================================================================
Created on: 9/30/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function updates lockout policy settings.
.PARAMETER LockoutPolicy
Specifies the LockoutPolicy instance which will be used as original policy. If some properties are not specified they will be updated with the properties from this object.
.PARAMETER Description
.PARAMETER AutoUnlockIntervalSec
.PARAMETER FailedAttemptIntervalSec
.PARAMETER MaxFailedAttempts
.EXAMPLE
Get-SsoLockoutPolicy | Set-SsoLockoutPolicy -AutoUnlockIntervalSec 15 -MaxFailedAttempts 4
Updates lockout policy auto unlock interval seconds and maximum failed attempts
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'LockoutPolicy instance you want to update')]
[VMware.vSphere.SsoAdminClient.DataTypes.LockoutPolicy]
$LockoutPolicy,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'LockoutPolicy description')]
[string]
$Description,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int64]]
$AutoUnlockIntervalSec,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int64]]
$FailedAttemptIntervalSec,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MaxFailedAttempts)
Process {
try {
foreach ($lp in $LockoutPolicy) {
$ssoAdminClient = $lp.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$lp' is from disconnected server"
continue
}
if ([string]::IsNullOrEmpty($Description)) {
$Description = $lp.Description
}
if ($AutoUnlockIntervalSec -eq $null) {
$AutoUnlockIntervalSec = $lp.AutoUnlockIntervalSec
}
if ($FailedAttemptIntervalSec -eq $null) {
$FailedAttemptIntervalSec = $lp.FailedAttemptIntervalSec
}
if ($MaxFailedAttempts -eq $null) {
$MaxFailedAttempts = $lp.MaxFailedAttempts
}
$ssoAdminClient.SetLockoutPolicy(
$Description,
$AutoUnlockIntervalSec,
$FailedAttemptIntervalSec,
$MaxFailedAttempts);
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}

View File

@@ -0,0 +1,262 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Get-SsoPasswordPolicy {
<#
.NOTES
===========================================================================
Created on: 9/30/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function gets password policy.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-SsoPasswordPolicy
Gets password policy for the server connections available in $global:defaultSsoAdminServers
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$connection.Client.GetPasswordPolicy();
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Set-SsoPasswordPolicy {
<#
.NOTES
===========================================================================
Created on: 9/30/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function updates password policy settings.
.PARAMETER PasswordPolicy
Specifies the PasswordPolicy instance which will be used as original policy. If some properties are not specified they will be updated with the properties from this object.
.PARAMETER Description
.PARAMETER ProhibitedPreviousPasswordsCount
.PARAMETER MinLength
.PARAMETER MaxLength
.PARAMETER MaxIdenticalAdjacentCharacters
.PARAMETER MinNumericCount
.PARAMETER MinSpecialCharCount
.PARAMETER MinAlphabeticCount
.PARAMETER MinUppercaseCount
.PARAMETER MinLowercaseCount
.PARAMETER PasswordLifetimeDays
.EXAMPLE
Get-SsoPasswordPolicy | Set-SsoPasswordPolicy -MinLength 10 -PasswordLifetimeDays 45
Updates password policy setting minimum password length to 10 symbols and password lifetime to 45 days
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'PasswordPolicy instance you want to update')]
[VMware.vSphere.SsoAdminClient.DataTypes.PasswordPolicy]
$PasswordPolicy,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'PasswordPolicy description')]
[string]
$Description,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$ProhibitedPreviousPasswordsCount,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MinLength,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MaxLength,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MaxIdenticalAdjacentCharacters,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MinNumericCount,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MinSpecialCharCount,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MinAlphabeticCount,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MinUppercaseCount,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$MinLowercaseCount,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int32]]
$PasswordLifetimeDays)
Process {
try {
foreach ($pp in $PasswordPolicy) {
$ssoAdminClient = $pp.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$pp' is from disconnected server"
continue
}
if ([string]::IsNullOrEmpty($Description)) {
$Description = $pp.Description
}
if ($ProhibitedPreviousPasswordsCount -eq $null) {
$ProhibitedPreviousPasswordsCount = $pp.ProhibitedPreviousPasswordsCount
}
if ($MinLength -eq $null) {
$MinLength = $pp.MinLength
}
if ($MaxLength -eq $null) {
$MaxLength = $pp.MaxLength
}
if ($MaxIdenticalAdjacentCharacters -eq $null) {
$MaxIdenticalAdjacentCharacters = $pp.MaxIdenticalAdjacentCharacters
}
if ($MinNumericCount -eq $null) {
$MinNumericCount = $pp.MinNumericCount
}
if ($MinSpecialCharCount -eq $null) {
$MinSpecialCharCount = $pp.MinSpecialCharCount
}
if ($MinAlphabeticCount -eq $null) {
$MinAlphabeticCount = $pp.MinAlphabeticCount
}
if ($MinUppercaseCount -eq $null) {
$MinUppercaseCount = $pp.MinUppercaseCount
}
if ($MinLowercaseCount -eq $null) {
$MinLowercaseCount = $pp.MinLowercaseCount
}
if ($PasswordLifetimeDays -eq $null) {
$PasswordLifetimeDays = $pp.PasswordLifetimeDays
}
$ssoAdminClient.SetPasswordPolicy(
$Description,
$ProhibitedPreviousPasswordsCount,
$MinLength,
$MaxLength,
$MaxIdenticalAdjacentCharacters,
$MinNumericCount,
$MinSpecialCharCount,
$MinAlphabeticCount,
$MinUppercaseCount,
$MinLowercaseCount,
$PasswordLifetimeDays);
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}

View File

@@ -0,0 +1,551 @@
<#
Copyright 2020-2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function New-SsoPersonUser {
<#
.NOTES
===========================================================================
Created on: 9/29/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function creates new person user account.
.PARAMETER UserName
Specifies the UserName of the requested person user account.
.PARAMETER Password
Specifies the Password of the requested person user account.
.PARAMETER Description
Specifies the Description of the requested person user account.
.PARAMETER EmailAddress
Specifies the EmailAddress of the requested person user account.
.PARAMETER FirstName
Specifies the FirstName of the requested person user account.
.PARAMETER LastName
Specifies the FirstName of the requested person user account.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
$ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd'
New-SsoPersonUser -Server $ssoAdminConnection -User myAdmin -Password 'MyStrongPa$$w0rd'
Creates person user account with user name 'myAdmin' and password 'MyStrongPa$$w0rd'
.EXAMPLE
New-SsoPersonUser -User myAdmin -Password 'MyStrongPa$$w0rd' -EmailAddress 'myAdmin@mydomain.com' -FirstName 'My' -LastName 'Admin'
Creates person user account with user name 'myAdmin', password 'MyStrongPa$$w0rd', and details against connections available in 'DefaultSsoAdminServers'
#>
[CmdletBinding(ConfirmImpact = 'Low')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'User name of the new person user account')]
[string]
$UserName,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Password of the new person user account')]
[string]
$Password,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Description of the new person user account')]
[string]
$Description,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'EmailAddress of the new person user account')]
[string]
$EmailAddress,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'FirstName of the new person user account')]
[string]
$FirstName,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'LastName of the new person user account')]
[string]
$LastName,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
# Output is the result of 'CreateLocalUser'
try {
$connection.Client.CreateLocalUser(
$UserName,
$Password,
$Description,
$EmailAddress,
$FirstName,
$LastName
)
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
}
function Get-SsoPersonUser {
<#
.NOTES
===========================================================================
Created on: 9/29/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function gets person user account.
.PARAMETER Name
Specifies Name to filter on when searching for person user accounts.
.PARAMETER Domain
Specifies the Domain in which search will be applied, default is 'localos'.
.PARAMETER Group
Specifies the group in which search for person user members will be applied.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-SsoPersonUser -Name admin -Domain vsphere.local
Gets person user accounts which contain name 'admin' in 'vsphere.local' domain
.EXAMPLE
Get-SsoGroup -Name 'Administrators' -Domain 'vsphere.local' | Get-SsoPersonUser
Gets person user accounts members of 'Administrators' group
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Name filter to be applied when searching for person user accounts')]
[string]
$Name,
[Parameter(
ParameterSetName = 'ByNameAndDomain',
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Domain name to search in, default is "localos"')]
[string]
$Domain = 'localos',
[Parameter(
ParameterSetName = 'ByGroup',
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Searches members of the specified group')]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$Group,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
if ($Name -eq $null) {
$Name = [string]::Empty
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$personUsers = $null
if ($Group -ne $null) {
$personUsers = $connection.Client.GetPersonUsersInGroup(
(RemoveWildcardSymbols $Name),
$Group)
}
else {
$personUsers = $connection.Client.GetLocalUsers(
(RemoveWildcardSymbols $Name),
$Domain)
}
if ($personUsers -ne $null) {
foreach ($personUser in $personUsers) {
if ([string]::IsNullOrEmpty($Name) ) {
Write-Output $personUser
}
else {
# Apply Name filtering
if ((HasWildcardSymbols $Name) -and `
$personUser.Name -like $Name) {
Write-Output $personUser
}
elseif ($personUser.Name -eq $Name) {
# Exactly equal
Write-Output $personUser
}
}
}
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Set-SsoPersonUser {
<#
.NOTES
===========================================================================
Created on: 9/29/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
Updates person user account.
.PARAMETER User
Specifies the PersonUser instance to update.
.PARAMETER Group
Specifies the Group you want to add or remove PwersonUser from.
.PARAMETER Add
Specifies user will be added to the spcified group.
.PARAMETER Remove
Specifies user will be removed from the spcified group.
.PARAMETER Unlock
Specifies user will be unlocked.
.PARAMETER NewPassword
Specifies new password for the specified user.
.PARAMETER Enable
Specifies user to be enabled or disabled.
.EXAMPLE
Set-SsoPersonUser -User $myPersonUser -Group $myExampleGroup -Add -Server $ssoAdminConnection
Adds $myPersonUser to $myExampleGroup
.EXAMPLE
Set-SsoPersonUser -User $myPersonUser -Group $myExampleGroup -Remove -Server $ssoAdminConnection
Removes $myPersonUser from $myExampleGroup
.EXAMPLE
Set-SsoPersonUser -User $myPersonUser -Unlock -Server $ssoAdminConnection
Unlocks $myPersonUser
.EXAMPLE
Set-SsoPersonUser -User $myPersonUser -Enable $false -Server $ssoAdminConnection
Disable user account
.EXAMPLE
Set-SsoPersonUser -User $myPersonUser -NewPassword 'MyBrandNewPa$$W0RD' -Server $ssoAdminConnection
Resets $myPersonUser password
#>
[CmdletBinding(ConfirmImpact = 'Medium')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Person User instance you want to update')]
[VMware.vSphere.SsoAdminClient.DataTypes.PersonUser]
$User,
[Parameter(
ParameterSetName = 'AddToGroup',
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Group instance you want user to be added to or removed from')]
[Parameter(
ParameterSetName = 'RemoveFromGroup',
Mandatory = $true,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Group instance you want user to be added to or removed from')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.Group]
$Group,
[Parameter(
ParameterSetName = 'AddToGroup',
Mandatory = $true)]
[switch]
$Add,
[Parameter(
ParameterSetName = 'RemoveFromGroup',
Mandatory = $true)]
[switch]
$Remove,
[Parameter(
ParameterSetName = 'ResetPassword',
Mandatory = $true,
HelpMessage = 'New password for the specified user.')]
[ValidateNotNull()]
[string]
$NewPassword,
[Parameter(
ParameterSetName = 'UnlockUser',
Mandatory = $true,
HelpMessage = 'Specifies to unlock user account.')]
[switch]
$Unlock,
[Parameter(
ParameterSetName = 'EnableDisableUserAccount',
Mandatory = $true,
HelpMessage = 'Specifies to enable or disable user account.')]
[bool]
$Enable)
Process {
try {
foreach ($u in $User) {
$ssoAdminClient = $u.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$u' is from disconnected server"
continue
}
if ($Add) {
$result = $ssoAdminClient.AddPersonUserToGroup($u, $Group)
if ($result) {
Write-Output $u
}
}
if ($Remove) {
$result = $ssoAdminClient.RemovePersonUserFromGroup($u, $Group)
if ($result) {
Write-Output $u
}
}
if ($Unlock) {
$result = $ssoAdminClient.UnlockPersonUser($u)
if ($result) {
Write-Output $u
}
}
if ($NewPassword) {
$ssoAdminClient.ResetPersonUserPassword($u, $NewPassword)
Write-Output $u
}
if ($PSBoundParameters.ContainsKey('Enable')) {
$result = $false
if ($Enable) {
$result = $ssoAdminClient.EnablePersonUser($u)
} else {
$result = $ssoAdminClient.DisablePersonUser($u)
}
if ($result) {
# Return update person user
Write-Output ($ssoAdminClient.GetLocalUsers($u.Name, $u.Domain))
}
}
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Set-SsoSelfPersonUserPassword {
<#
.NOTES
===========================================================================
Created on: 2/19/2021
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
Resets connected person user password.
.PARAMETER NewPassword
Specifies new password for the connected person user.
.EXAMPLE
Set-SsoSelfPersonUserPassword -Password 'MyBrandNewPa$$W0RD' -Server $ssoAdminConnection
Resets password
#>
[CmdletBinding(ConfirmImpact = 'High')]
param(
[Parameter(
Mandatory = $true,
HelpMessage = 'New password for the connected user.')]
[ValidateNotNull()]
[SecureString]
$Password,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
try {
$connection.Client.ResetSelfPersonUserPassword($Password)
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
}
function Remove-SsoPersonUser {
<#
.NOTES
===========================================================================
Created on: 9/29/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function removes existing person user account.
.PARAMETER User
Specifies the PersonUser instance to remove.
.EXAMPLE
$ssoAdminConnection = Connect-SsoAdminServer -Server my.vc.server -User ssoAdmin@vsphere.local -Password 'ssoAdminStrongPa$$w0rd'
$myNewPersonUser = New-SsoPersonUser -Server $ssoAdminConnection -User myAdmin -Password 'MyStrongPa$$w0rd'
Remove-SsoPersonUser -User $myNewPersonUser
Remove person user account with user name 'myAdmin'
#>
[CmdletBinding(ConfirmImpact = 'High')]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Person User instance you want to remove')]
[VMware.vSphere.SsoAdminClient.DataTypes.PersonUser]
$User)
Process {
try {
foreach ($u in $User) {
$ssoAdminClient = $u.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$u' is from disconnected server"
continue
}
$ssoAdminClient.DeleteLocalUser($u)
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}

View File

@@ -0,0 +1,30 @@
# PowerCLI Example module for managing vSphere SSO Admin
This module is combination of .NET binary libraries for accessing vSphere SSO Admin API and PowerShell advanced functions exposing cmdlet-like interface to the SSO Admin features.<br/>
<br/>
The module supports PowerShell 5.1 and PowerShell 7.0 and above.<br/>
## Install Module from PowerShell Gallery
```
Install-Module VMware.vSphere.SsoAdmin
```
# Using the source code
## '/src' directory
This directory contains the .NET binaries sources code and Pester integration tests that cover both the binaries and the module advanced functions functionality.<br/>
## Required build tools
- PowerShell 7.0<br/>
- dotnet sdk<br/>
## Required test tools
- PowerShell 7.0
- PowerCLI 12.0<br/>
- Pester 5.0.0<br/>
## '/src/build.ps1' script
The script builds the binaries and publishes them to the 'net45' and 'netcoreapp3.1' directories of the module.<br/>
It has also the option to run module Pester tests. The optional parameters for VC server and credentials has to be specified in order the script to run the tests. Tests run in separate PowreShell process because PowerShell has to load the module binaries which are build output.<br/>
## '/src/test/RunTests.ps1' script
This script can be used to run the tests<br/>

View File

@@ -0,0 +1,128 @@
<#
Copyright 2020-2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
function Get-SsoTokenLifetime {
<#
.NOTES
===========================================================================
Created on: 9/30/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function gets HoK and Bearer Token lifetime settings.
.PARAMETER Server
Specifies the vSphere Sso Admin Server on which you want to run the cmdlet.
If not specified the servers available in $global:DefaultSsoAdminServers variable will be used.
.EXAMPLE
Get-SsoTokenLifetime
Gets HoK and Bearer Token lifetime settings for the server connections available in $global:defaultSsoAdminServers
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'Connected SsoAdminServer object')]
[ValidateNotNull()]
[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
$Server)
Process {
$serversToProcess = $global:DefaultSsoAdminServers.ToArray()
if ($Server -ne $null) {
$serversToProcess = $Server
}
try {
foreach ($connection in $serversToProcess) {
if (-not $connection.IsConnected) {
Write-Error "Server $connection is disconnected"
continue
}
$connection.Client.GetTokenLifetime();
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}
function Set-SsoTokenLifetime {
<#
.NOTES
===========================================================================
Created on: 9/30/2020
Created by: Dimitar Milov
Twitter: @dimitar_milov
Github: https://github.com/dmilov
===========================================================================
.DESCRIPTION
This function updates HoK or Bearer token lifetime settings.
.PARAMETER TokenLifetime
Specifies the TokenLifetime instance to update.
.PARAMETER MaxHoKTokenLifetime
.PARAMETER MaxBearerTokenLifetime
.EXAMPLE
Get-SsoTokenLifetime | Set-SsoTokenLifetime -MaxHoKTokenLifetime 60
Updates HoK token lifetime setting
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $false,
HelpMessage = 'TokenLifetime instance you want to update')]
[VMware.vSphere.SsoAdminClient.DataTypes.TokenLifetime]
$TokenLifetime,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int64]]
$MaxHoKTokenLifetime,
[Parameter(
Mandatory = $false,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $false)]
[Nullable[System.Int64]]
$MaxBearerTokenLifetime)
Process {
try {
foreach ($tl in $TokenLifetime) {
$ssoAdminClient = $tl.GetClient()
if ((-not $ssoAdminClient)) {
Write-Error "Object '$tl' is from disconnected server"
continue
}
$ssoAdminClient.SetTokenLifetime(
$MaxHoKTokenLifetime,
$MaxBearerTokenLifetime
);
}
}
catch {
Write-Error (FormatError $_.Exception)
}
}
}

View File

@@ -0,0 +1,143 @@
#
# Module manifest for module 'VMware.vSphere.SsoAdmin'
#
# Generated by: Dimitar Milov
#
# Generated on: 7/28/2021
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'VMware.vSphere.SsoAdmin.psm1'
# Version number of this module.
ModuleVersion = '1.3.9'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'b3e25326-e809-4d68-a252-ca5fcaf1eb8b'
# Author of this module
Author = 'Dimitar Milov'
# Company or vendor of this module
CompanyName = 'VMware, Inc.'
# Copyright statement for this module
Copyright = 'Copyright (c) VMware, Inc. All rights reserved.'
# Description of the functionality provided by this module
Description = 'PowerShell Module for Managing VMware vSphere SSO Admin functionality.'
# Minimum version of the PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @(@{ModuleName = 'VMware.VimAutomation.Common'; ModuleVersion = '12.0.0.15939652'; })
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Connect-SsoAdminServer', 'Disconnect-SsoAdminServer',
'New-SsoPersonUser', 'Get-SsoPersonUser', 'Set-SsoPersonUser',
'Remove-SsoPersonUser', 'Set-SsoSelfPersonUserPassword',
'New-SsoGroup', 'Get-SsoGroup', 'Set-SsoGroup', 'Remove-SsoGroup',
'Add-GroupToSsoGroup', 'Remove-GroupFromSsoGroup',
'Add-UserToSsoGroup', 'Remove-UserFromSsoGroup',
'Get-SsoPasswordPolicy', 'Set-SsoPasswordPolicy',
'Get-SsoLockoutPolicy', 'Set-SsoLockoutPolicy',
'Get-SsoTokenLifetime', 'Set-SsoTokenLifetime', 'Get-IdentitySource', 'Set-IdentitySource',
'Remove-IdentitySource', 'Add-ActiveDirectoryIdentitySource',
'Add-LDAPIdentitySource', 'Set-LDAPIdentitySource',
'Get-SsoAuthenticationPolicy', 'Set-SsoAuthenticationPolicy'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
# VariablesToExport = @()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = 'Add-ActiveDirectoryIdentitySource'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
IconUri = 'https://raw.githubusercontent.com/vmware/PowerCLI-Example-Scripts/master/Modules/VMware.vSphere.SsoAdmin/src/resources/powercli.png'
# ReleaseNotes of this module
# ReleaseNotes = ''
# Prerelease string of this module
# Prerelease = ''
# Flag to indicate whether the module requires explicit user acceptance for install/update/save
# RequireLicenseAcceptance = $false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}

View File

@@ -0,0 +1,88 @@
<#
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
#>
#
# Script module for module 'VMware.vSphere.SsoAdmin'
#
Set-StrictMode -Version Latest
$moduleFileName = 'VMware.vSphere.SsoAdmin.psd1'
# Set up some helper variables to make it easier to work with the module
$PSModule = $ExecutionContext.SessionState.Module
$PSModuleRoot = $PSModule.ModuleBase
# Import the appropriate nested binary module based on the current PowerShell version
$subModuleRoot = $PSModuleRoot
if (($PSVersionTable.Keys -contains "PSEdition") -and ($PSVersionTable.PSEdition -ne 'Desktop')) {
$subModuleRoot = Join-Path -Path $PSModuleRoot -ChildPath 'netcoreapp3.1'
}
else {
$subModuleRoot = Join-Path -Path $PSModuleRoot -ChildPath 'net45'
}
$subModulePath = Join-Path -Path $subModuleRoot -ChildPath $moduleFileName
$subModule = Import-Module -Name $subModulePath -PassThru
# When the module is unloaded, remove the nested binary module that was loaded with it
$PSModule.OnRemove = {
Remove-Module -ModuleInfo $subModule
}
# Internal helper functions
function HasWildcardSymbols {
param(
[string]
$stringToVerify
)
(-not [string]::IsNullOrEmpty($stringToVerify) -and `
($stringToVerify -match '\*' -or `
$stringToVerify -match '\?'))
}
function RemoveWildcardSymbols {
param(
[string]
$stringToProcess
)
if (-not [string]::IsNullOrEmpty($stringToProcess)) {
$stringToProcess.Replace('*', '').Replace('?', '')
}
else {
[string]::Empty
}
}
function FormatError {
param(
[System.Exception]
$exception
)
if ($exception -ne $null) {
if ($exception.InnerException -ne $null) {
$exception = $exception.InnerException
}
# result
$exception.Message
}
}
# Global variables
$global:DefaultSsoAdminServers = New-Object System.Collections.Generic.List[VMware.vSphere.SsoAdminClient.DataTypes.SsoAdminServer]
# Import Module Advanced Functions Implementation
Get-ChildItem -Path $PSScriptRoot -Filter '*.ps1' | ForEach-Object {
Write-Debug "Importing file: $($_.BaseName)"
try {
. $_.FullName
}
catch {
Write-Error -Message "Failed to import functions from $($_.Fullname): $_"
}
}

View File

@@ -0,0 +1,86 @@
#
# Module manifest for module 'VMware.vSphere.SsoAdmin'
#
# Generated by: dmilov@vmware.com
#
# Generated on: 9/25/20
@{
# Version number of this module.
ModuleVersion = '1.0.0'
# ID used to uniquely identify this module
GUID = 'dd2b1928-e8ee-4c3a-a364-1caec6d3bd58'
# Author of this module
Author = 'Dimitar Milov'
# Company or vendor of this module
CompanyName = 'VMware, Inc.'
# Copyright statement for this module
Copyright = 'Copyright (c) VMware, Inc. All rights reserved.'
# Description of the functionality provided by this module
Description = 'PowerShell Module for Managing VMware vSphere SSO Admin functionality.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.1'
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
DotNetFrameworkVersion = '4.5'
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion = '4.0'
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = ''
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @(
'VMware.vSphere.SsoAdmin.Utils.dll',
'VMware.vSphere.SsoAdminClient.dll',
'VMware.vSphere.LsClient.dll'
)
# Script files (.ps1) that are run in the caller's environment prior to importing this module
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
#FormatsToProcess = 'VMware.vSphere.SsoAdmin.Format.ps1xml'
# Modules to import as nested modules of the module specified in ModuleToProcess
#NestedModules= @()
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = ''
# Private data to pass to the module specified in ModuleToProcess
PrivateData = ''
}

View File

@@ -0,0 +1,83 @@
#
# Module manifest for module 'VMware.vSphere.SsoAdmin'
#
# Generated by: dmilov@vmware.com
#
# Generated on: 9/25/20
@{
# Version number of this module.
ModuleVersion = '1.0.0'
# ID used to uniquely identify this module
GUID = '29f1ed8b-311a-4ea1-80a6-0f3ec56e8259'
# Author of this module
Author = 'Dimitar Milov'
# Company or vendor of this module
CompanyName = 'VMware, Inc.'
# Copyright statement for this module
Copyright = 'Copyright (c) VMware, Inc. All rights reserved.'
# Description of the functionality provided by this module
Description = 'PowerShell Module for Managing VMware vSphere SSO Admin functionality.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '6.0.1'
# Specifies the compatible PSEditions of the module.
CompatiblePSEditions = @('Core')
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = ''
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @(
'VMware.vSphere.SsoAdmin.Utils.dll',
'VMware.vSphere.SsoAdminClient.dll',
'VMware.vSphere.LsClient.dll'
)
# Script files (.ps1) that are run in the caller's environment prior to importing this module
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
#FormatsToProcess = 'VMware.vSphere.SsoAdmin.Format.ps1xml'
# Modules to import as nested modules of the module specified in ModuleToProcess
#NestedModules= @()
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = ''
# Private data to pass to the module specified in ModuleToProcess
PrivateData = ''
}

View File

@@ -0,0 +1,3 @@
**/.vs
**/bin
**/obj

View File

@@ -0,0 +1,5 @@
<configuration>
<packageSources>
<add key="LocalPackages" value="packages" />
</packageSources>
</configuration>

View File

@@ -0,0 +1,24 @@
{
"ProviderId": "Microsoft.VisualStudio.ConnectedService.Wcf",
"Version": "15.0.20628.921",
"ExtendedData": {
"Uri": "https://10.23.80.205/lookupservice/wsdl/lookup.wsdl",
"Namespace": "LookupServiceReference",
"SelectedAccessLevelForGeneratedClass": "Public",
"GenerateMessageContract": false,
"ReuseTypesinReferencedAssemblies": true,
"ReuseTypesinAllReferencedAssemblies": true,
"CollectionTypeReference": {
"Item1": "System.Array",
"Item2": "System.Runtime.dll"
},
"DictionaryCollectionTypeReference": {
"Item1": "System.Collections.Generic.Dictionary`2",
"Item2": "System.Collections.dll"
},
"CheckedReferencedAssemblies": [],
"InstanceId": null,
"Name": "LookupServiceReference",
"Metadata": {}
}
}

View File

@@ -0,0 +1,136 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Linq;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Text;
using LookupServiceReference;
namespace VMware.vSphere.LsClient
{
public class LookupServiceClient {
private const int WEB_OPERATION_TIMEOUT_SECONDS = 30;
private LsPortTypeClient _lsClient;
private static readonly ManagedObjectReference RootMoRef = new ManagedObjectReference
{
type = "LookupServiceInstance",
Value = "ServiceInstance"
};
public LookupServiceClient(string hostname, X509CertificateValidator serverCertificateValidator) {
var lsUri = $"https://{hostname}/lookupservice/sdk";
_lsClient = new LsPortTypeClient(GetBinding(), new EndpointAddress(new Uri(lsUri)));
var serverAuthentication = GetServerAuthentication(serverCertificateValidator);
if (serverAuthentication != null)
{
_lsClient
.ChannelFactory
.Credentials
.ServiceCertificate
.SslCertificateAuthentication = serverAuthentication;
}
}
#region Private Helpers
private X509ServiceCertificateAuthentication GetServerAuthentication(X509CertificateValidator serverCertificateValidator)
{
if (serverCertificateValidator != null) {
return new X509ServiceCertificateAuthentication {
CertificateValidationMode = X509CertificateValidationMode.Custom,
CustomCertificateValidator = serverCertificateValidator
};
}
// Default .NET behavior for TLS certificate validation
return null;
}
private static MessageEncodingBindingElement GetWcfEncoding()
{
return new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);
}
private static HttpsTransportBindingElement GetWcfTransport(bool useSystemProxy)
{
HttpsTransportBindingElement transport = new HttpsTransportBindingElement
{
RequireClientCertificate = false
};
transport.UseDefaultWebProxy = useSystemProxy;
transport.MaxBufferSize = 2147483647;
transport.MaxReceivedMessageSize = 2147483647;
return transport;
}
private static Binding GetBinding() {
var binding = new CustomBinding(GetWcfEncoding(), GetWcfTransport(true));
var timeout = TimeSpan.FromSeconds(WEB_OPERATION_TIMEOUT_SECONDS);
binding.CloseTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
binding.SendTimeout = timeout;
return binding;
}
#endregion
public Uri GetSsoAdminEndpointUri() {
var product = "com.vmware.cis";
var endpointType = "com.vmware.cis.cs.identity.admin";
var type = "sso:admin";
return FindServiceEndpoint(product, type, endpointType);
}
public Uri GetStsEndpointUri() {
var product = "com.vmware.cis";
var type = "cs.identity";
var endpointType = "com.vmware.cis.cs.identity.sso";
return FindServiceEndpoint(product, type, endpointType);
}
private Uri FindServiceEndpoint(string product, string type, string endpointType) {
Uri result = null;
var svcContent = _lsClient.RetrieveServiceContentAsync(RootMoRef).Result;
var filterCriteria = new LookupServiceRegistrationFilter() {
serviceType = new LookupServiceRegistrationServiceType {
product = product,
type = type
}
};
var lsRegInfo = _lsClient.
ListAsync(svcContent.serviceRegistration, filterCriteria)
.Result?
.returnval?
.FirstOrDefault();
if (lsRegInfo != null) {
var registrationEndpooint = lsRegInfo.
serviceEndpoints?.
Where(a => a.endpointType.type == endpointType)?.
FirstOrDefault<LookupServiceRegistrationEndpoint>();
if (registrationEndpooint != null) {
result = new Uri(registrationEndpooint.url);
}
}
return result;
}
}
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>VMware.vSphere.LsClient</RootNamespace>
<AssemblyName>VMware.vSphere.LsClient</AssemblyName>
<Description>vSphere Lookup Service API client.</Description>
<TargetFrameworks>net45;netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net45'">
<Reference Include="System.IdentityModel" />
<Reference Include="System.ServiceModel" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="VMware.System.Private.ServiceModel" Version="4.4.4" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,43 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30503.244
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VMware.vSphere.SsoAdminClient", "VMware.vSphere.SsoAdminClient\VMware.vSphere.SsoAdminClient.csproj", "{BD48E0DD-4048-48FD-B0BE-560E2417A2CC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VMware.vSphere.LsClient", "VMware.vSphere.LsClient\VMware.vSphere.LsClient.csproj", "{EEC4C335-3E6C-4FA5-84CD-CBADCD720F35}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VMware.vSphere.SsoAdmin.Utils", "VMware.vSphere.SsoAdmin.Utils\VMware.vSphere.SsoAdmin.Utils.csproj", "{1523743E-C01E-4D37-845F-0BB8DAF9EE7E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VMware.vSphere.SsoAdminClient.Tests", "VMware.vSphere.SsoAdminClient.Tests\VMware.vSphere.SsoAdminClient.Tests.csproj", "{90E6C4A6-FDB4-43FC-B156-ADBCF2B85CCE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BD48E0DD-4048-48FD-B0BE-560E2417A2CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BD48E0DD-4048-48FD-B0BE-560E2417A2CC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BD48E0DD-4048-48FD-B0BE-560E2417A2CC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BD48E0DD-4048-48FD-B0BE-560E2417A2CC}.Release|Any CPU.Build.0 = Release|Any CPU
{EEC4C335-3E6C-4FA5-84CD-CBADCD720F35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EEC4C335-3E6C-4FA5-84CD-CBADCD720F35}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEC4C335-3E6C-4FA5-84CD-CBADCD720F35}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEC4C335-3E6C-4FA5-84CD-CBADCD720F35}.Release|Any CPU.Build.0 = Release|Any CPU
{1523743E-C01E-4D37-845F-0BB8DAF9EE7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1523743E-C01E-4D37-845F-0BB8DAF9EE7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1523743E-C01E-4D37-845F-0BB8DAF9EE7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1523743E-C01E-4D37-845F-0BB8DAF9EE7E}.Release|Any CPU.Build.0 = Release|Any CPU
{90E6C4A6-FDB4-43FC-B156-ADBCF2B85CCE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{90E6C4A6-FDB4-43FC-B156-ADBCF2B85CCE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{90E6C4A6-FDB4-43FC-B156-ADBCF2B85CCE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{90E6C4A6-FDB4-43FC-B156-ADBCF2B85CCE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9A376526-4487-43FF-A527-E34AD4764F12}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,21 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.IdentityModel.Selectors;
using System.Security.Cryptography.X509Certificates;
namespace VMware.vSphere.SsoAdmin.Utils
{
public class AcceptAllX509CertificateValidator : X509CertificateValidator
{
public override void Validate(X509Certificate2 certificate) {
// Check that there is a certificate.
if (certificate == null) {
throw new ArgumentNullException(nameof(certificate));
}
}
}
}

View File

@@ -0,0 +1,39 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace VMware.vSphere.SsoAdmin.Utils
{
public class StringToSecureStringArgumentTransformationAttribute : ArgumentTransformationAttribute
{
private static class SecureStringConverter
{
public static SecureString ToSecureString(string value) {
var result = new SecureString();
foreach (var c in value.ToCharArray()) {
result.AppendChar(c);
}
return result;
}
}
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) {
object result = inputData;
if (inputData is string s) {
result = SecureStringConverter.ToSecureString(s);
}
return result;
}
}
}

View File

@@ -0,0 +1,55 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VMware.vSphere.SsoAdminClient.DataTypes;
namespace VMware.vSphere.SsoAdmin.Utils
{
public class StringToSsoAdminServerArgumentTransformationAttribute : ArgumentTransformationAttribute
{
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) {
object result = inputData;
if (inputData is string obnValue &&
!string.IsNullOrEmpty(obnValue)) {
// Adopt PowerShell regex chars
var csharpObnValue = obnValue.Replace("*", ".*").Replace("?", ".?");
result = null;
var obnMatchingServers = new List<SsoAdminServer>();
var ssoAdminServerVariable = engineIntrinsics.SessionState.PSVariable.GetValue("DefaultSsoAdminServers");
if (ssoAdminServerVariable is PSObject ssoAdminServersPsObj &&
ssoAdminServersPsObj.BaseObject is List<SsoAdminServer> connectedServers) {
foreach (var server in connectedServers) {
if (!string.IsNullOrEmpty(Regex.Match(server.ToString(), csharpObnValue)?.Value)) {
obnMatchingServers.Add(server);
}
}
}
if (obnMatchingServers.Count > 0) {
result = obnMatchingServers.ToArray();
} else {
// Non-terminating error for not matching value
engineIntrinsics.Host.UI.WriteErrorLine($"'{obnValue}' doesn't match any objects in $global:DefaultSsoAdminServers variable");
}
}
return result;
}
}
}

View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>VMware.vSphere.SsoAdmin.Utils</RootNamespace>
<AssemblyName>VMware.vSphere.SsoAdmin.Utils</AssemblyName>
<Description>vSphere Lookup SsoAdmin utility types.</Description>
<TargetFrameworks>net45;netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net45'">
<Reference Include="System.IdentityModel" />
<Reference Include="System.ServiceModel" />
<PackageReference Include="Microsoft.PowerShell.5.ReferenceAssemblies" Version="1.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Microsoft.WSMan.Runtime" Version="6.1.0" />
<PackageReference Include="VMware.System.Private.ServiceModel" Version="4.4.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VMware.vSphere.SsoAdminClient\VMware.vSphere.SsoAdminClient.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,299 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using NUnit.Framework;
using System.Linq;
using System.Security;
using VMware.vSphere.SsoAdmin.Utils;
using VMware.vSphere.SsoAdminClient.DataTypes;
namespace VMware.vSphere.SsoAdminClient.Tests
{
public class Tests
{
private string _vc = "<vc>";
private string _user = "<user>";
private string _rawPassword = "<password>";
private SecureString _password;
[SetUp]
public void Setup() {
_password = new SecureString();
foreach (char c in _rawPassword) {
_password.AppendChar(c);
}
}
[Test]
public void AddRemoveLocalUser() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
var expectedUserName = "test-user2";
var expectedPassword = "te$tPa$sW0rd";
var expectedDescription = "test-description";
var expectedEmail = "testuse@testdomain.loc";
var expectedFirstName = "Test";
var expectedLastName = "User";
// Act Create User
var actual = ssoAdminClient.CreateLocalUser(
expectedUserName,
expectedPassword,
expectedDescription,
expectedEmail,
expectedFirstName,
expectedLastName);
// Assert Created User
Assert.AreEqual(expectedUserName, actual.Name);
Assert.AreEqual(expectedDescription, actual.Description);
Assert.AreEqual(expectedEmail, actual.EmailAddress);
Assert.AreEqual(expectedFirstName, actual.FirstName);
Assert.AreEqual(expectedLastName, actual.LastName);
// Act Delete User
ssoAdminClient.DeleteLocalUser(
actual);
}
[Test]
public void GetAllLocalOsUsers() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
// Act
var actual = ssoAdminClient.GetLocalUsers("", "localos").ToArray();
// Assert
Assert.NotNull(actual);
Assert.Greater(actual.Length, 0);
}
[Test]
public void GetRootLocalOsUsers() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
// Act
var actual = ssoAdminClient.GetLocalUsers("root", "localos").ToArray();
// Assert
Assert.NotNull(actual);
Assert.AreEqual(1, actual.Length);
Assert.AreEqual("root", actual[0].Name);
Assert.AreEqual("localos", actual[0].Domain);
}
[Test]
public void GetRootLocalOsGroups() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
// Act
var actual = ssoAdminClient.GetGroups("", "localos").ToArray();
// Assert
Assert.NotNull(actual);
Assert.Greater(actual.Length, 1);
Assert.AreEqual("localos", actual[0].Domain);
}
[Test]
public void GetPersonUsersInGroup() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
// Act
var actual = ssoAdminClient.GetPersonUsersInGroup("", new Group(ssoAdminClient) {
Name = "Administrators",
Domain = "vsphere.local"
}).ToArray();
// Assert
Assert.NotNull(actual);
Assert.GreaterOrEqual(actual.Length, 1);
Assert.AreEqual("vsphere.local", actual[0].Domain);
}
[Test]
public void AddRemoveUserFromGroup() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
var expectedUserName = "test-user5";
var expectedPassword = "te$tPa$sW0rd";
var newUser = ssoAdminClient.CreateLocalUser(
expectedUserName,
expectedPassword);
var group = ssoAdminClient.GetGroups("administrators", newUser.Domain).FirstOrDefault<Group>();
// Act
var addActual = ssoAdminClient.AddPersonUserToGroup(newUser, group);
var removeActual = ssoAdminClient.RemovePersonUserFromGroup(newUser, group);
// Assert
Assert.IsTrue(addActual);
Assert.IsTrue(removeActual);
// Cleanup
ssoAdminClient.DeleteLocalUser(
newUser);
}
[Test]
public void ResetUserPassword() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
var expectedUserName = "test-user6";
var expectedPassword = "te$tPa$sW0rd";
var updatePassword = "TE$tPa$sW0rd";
var newUser = ssoAdminClient.CreateLocalUser(
expectedUserName,
expectedPassword);
// Act
// Assert
Assert.DoesNotThrow(() => {
ssoAdminClient.ResetPersonUserPassword(newUser, updatePassword);
});
// Cleanup
ssoAdminClient.DeleteLocalUser(
newUser);
}
[Test]
public void GetPasswordPolicy() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
// Act
var actual = ssoAdminClient.GetPasswordPolicy();
// Assert
Assert.NotNull(actual);
}
[Test]
public void SetPasswordPolicy() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
var originalPasswordPolicy = ssoAdminClient.GetPasswordPolicy();
var expectedDescription = "TestDescription";
var expectedProhibitedPreviousPasswordsCount = originalPasswordPolicy.ProhibitedPreviousPasswordsCount + 1;
var expectedMinLength = originalPasswordPolicy.MinLength + 1;
var expectedMaxLength = originalPasswordPolicy.MaxLength + 1;
var exptectedMaxIdenticalAdjacentCharacters = originalPasswordPolicy.MaxIdenticalAdjacentCharacters + 1;
var expectedMinNumericCount = originalPasswordPolicy.MinNumericCount + 1;
var expectedMinSpecialCharCount = originalPasswordPolicy.MinSpecialCharCount + 1;
var expectedMinAlphabeticCount = originalPasswordPolicy.MinAlphabeticCount + 2;
var expectedMinUppercaseCount = 0;
var expectedMinLowercaseCount = originalPasswordPolicy.MinLowercaseCount + 2;
var expectedPasswordLifetimeDays = originalPasswordPolicy.PasswordLifetimeDays - 2;
// Act
var actual = ssoAdminClient.SetPasswordPolicy(
description: expectedDescription,
prohibitedPreviousPasswordsCount: expectedProhibitedPreviousPasswordsCount,
minLength: expectedMinLength,
maxLength: expectedMaxLength,
maxIdenticalAdjacentCharacters: exptectedMaxIdenticalAdjacentCharacters,
minNumericCount: expectedMinNumericCount,
minSpecialCharCount: expectedMinSpecialCharCount,
minAlphabeticCount: expectedMinAlphabeticCount,
minUppercaseCount: expectedMinUppercaseCount,
minLowercaseCount: expectedMinLowercaseCount,
passwordLifetimeDays: expectedPasswordLifetimeDays);
// Assert
Assert.NotNull(actual);
Assert.AreEqual(expectedDescription, actual.Description);
Assert.AreEqual(expectedProhibitedPreviousPasswordsCount, actual.ProhibitedPreviousPasswordsCount);
Assert.AreEqual(expectedMinLength, actual.MinLength);
Assert.AreEqual(expectedMaxLength, actual.MaxLength);
Assert.AreEqual(exptectedMaxIdenticalAdjacentCharacters, actual.MaxIdenticalAdjacentCharacters);
Assert.AreEqual(expectedMinNumericCount, actual.MinNumericCount);
Assert.AreEqual(expectedMinAlphabeticCount, actual.MinAlphabeticCount);
Assert.AreEqual(expectedMinUppercaseCount, actual.MinUppercaseCount);
Assert.AreEqual(expectedMinLowercaseCount, actual.MinLowercaseCount);
Assert.AreEqual(expectedPasswordLifetimeDays, actual.PasswordLifetimeDays);
// Cleanup
ssoAdminClient.SetPasswordPolicy(
description: originalPasswordPolicy.Description,
prohibitedPreviousPasswordsCount: originalPasswordPolicy.ProhibitedPreviousPasswordsCount,
minLength: originalPasswordPolicy.MinLength,
maxLength: originalPasswordPolicy.MaxLength,
maxIdenticalAdjacentCharacters: originalPasswordPolicy.MaxIdenticalAdjacentCharacters,
minNumericCount: originalPasswordPolicy.MinNumericCount,
minSpecialCharCount: originalPasswordPolicy.MinSpecialCharCount,
minAlphabeticCount: originalPasswordPolicy.MinAlphabeticCount,
minUppercaseCount: originalPasswordPolicy.MinUppercaseCount,
minLowercaseCount: originalPasswordPolicy.MinLowercaseCount,
passwordLifetimeDays: originalPasswordPolicy.PasswordLifetimeDays);
}
[Test]
public void GetLockoutPolicy() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
// Act
var actual = ssoAdminClient.GetLockoutPolicy();
// Assert
Assert.NotNull(actual);
}
[Test]
public void SetLockoutPolicy() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
var originalLockoutPolicy = ssoAdminClient.GetLockoutPolicy();
var expectedDescription = "TestDescription";
var expectedAutoUnlockIntervalSec = 20;
var expectedFailedAttemptIntervalSec = 30;
var expectedMaxFailedAttempts = 5;
// Act
var actual = ssoAdminClient.SetLockoutPolicy(
expectedDescription,
expectedAutoUnlockIntervalSec,
expectedFailedAttemptIntervalSec,
expectedMaxFailedAttempts);
// Assert
Assert.NotNull(actual);
Assert.AreEqual(expectedDescription, actual.Description);
Assert.AreEqual(expectedAutoUnlockIntervalSec, actual.AutoUnlockIntervalSec);
Assert.AreEqual(expectedFailedAttemptIntervalSec, actual.FailedAttemptIntervalSec);
Assert.AreEqual(expectedMaxFailedAttempts, actual.MaxFailedAttempts);
// Cleanup
ssoAdminClient.SetLockoutPolicy(
originalLockoutPolicy.Description,
originalLockoutPolicy.AutoUnlockIntervalSec,
originalLockoutPolicy.FailedAttemptIntervalSec,
originalLockoutPolicy.MaxFailedAttempts
);
}
[Test]
public void GetDomains() {
// Arrange
var ssoAdminClient = new SsoAdminClient(_vc, _user, _password, new AcceptAllX509CertificateValidator());
// Act
var actual = ssoAdminClient.GetDomains().ToArray<IdentitySource>();
// Assert
Assert.NotNull(actual);
Assert.IsTrue(actual.Length >= 2);
}
}
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="nunit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.15.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VMware.vSphere.SsoAdmin.Utils\VMware.vSphere.SsoAdmin.Utils.csproj" />
<ProjectReference Include="..\VMware.vSphere.SsoAdminClient\VMware.vSphere.SsoAdminClient.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,30 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VMware.vSphere.SsoAdminClient.DataTypes
{
public class ActiveDirectoryIdentitySource : IdentitySource
{
public string Type { get; set; }
public string Alias { get; set; }
public string AuthenticationType { get; set; }
public string AuthenticationUsername { get; set; }
public string FriendlyName { get; set; }
public string PrimaryUrl { get; set; }
public string FailoverUrl { get; set; }
public string UserBaseDN { get; set; }
public string GroupBaseDN { get; set; }
public System.Security.Cryptography.X509Certificates.X509Certificate2[] Certificates {get ;set;}
}
}

View File

@@ -0,0 +1,36 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System.Security.Cryptography.X509Certificates;
namespace VMware.vSphere.SsoAdminClient.DataTypes
{
public class AuthenticationPolicy
{
SsoAdminClient _client;
public AuthenticationPolicy(SsoAdminClient client) {
_client = client;
}
public SsoAdminClient GetClient() {
return _client;
}
public bool PasswordAuthnEnabled { get; internal set; }
public bool WindowsAuthnEnabled { get; internal set; }
public bool SmartCardAuthnEnabled { get; internal set; }
public bool OCSPEnabled { get; internal set; }
public bool UseCRLAsFailOver { get; internal set; }
public bool SendOCSPNonce { get; internal set; }
public string OCSPUrl { get; internal set; }
public X509Certificate2 OCSPResponderSigningCert { get; internal set; }
public bool UseInCertCRL { get; internal set; }
public string CRLUrl { get; internal set; }
public int CRLCacheSize { get; internal set; }
public string[] Oids { get; internal set; }
public string[] TrustedCAs { get; internal set; }
}
}

View File

@@ -0,0 +1,35 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VMware.vSphere.SsoAdminClient.DataTypes
{
public class Group
{
SsoAdminClient _client;
public Group(SsoAdminClient client)
{
_client = client;
}
public string Name { get; set; }
public string Domain { get; set; }
public string Description { get; set; }
public SsoAdminClient GetClient()
{
return _client;
}
public override string ToString()
{
return $"{Name}@{Domain}";
}
}
}

View File

@@ -0,0 +1,18 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VMware.vSphere.SsoAdminClient.DataTypes
{
public class IdentitySource
{
public string Name { get; set; }
}
}

View File

@@ -0,0 +1,16 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VMware.vSphere.SsoAdminClient.DataTypes
{
public class LocalOSIdentitySource : IdentitySource
{
}
}

View File

@@ -0,0 +1,31 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Security;
using System.Text;
using System.Threading.Tasks;
namespace VMware.vSphere.SsoAdminClient.DataTypes
{
public class LockoutPolicy
{
SsoAdminClient _client;
public LockoutPolicy(SsoAdminClient client) {
_client = client;
}
public SsoAdminClient GetClient() {
return _client;
}
public string Description { get; set; }
public long AutoUnlockIntervalSec { get; set; }
public long FailedAttemptIntervalSec { get; set; }
public int MaxFailedAttempts { get; set; }
}
}

View File

@@ -0,0 +1,37 @@
/*
Copyright 2021 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VMware.vSphere.SsoAdminClient.DataTypes
{
public class PasswordPolicy
{
SsoAdminClient _client;
public PasswordPolicy(SsoAdminClient client) {
_client = client;
}
public string Description { get; set; }
public int ProhibitedPreviousPasswordsCount { get; set; }
public int MinLength { get; set; }
public int MaxLength { get; set; }
public int MinNumericCount { get; set; }
public int MinSpecialCharCount { get; set; }
public int MaxIdenticalAdjacentCharacters { get; set; }
public int MinAlphabeticCount { get; set; }
public int MinUppercaseCount { get; set; }
public int MinLowercaseCount { get; set; }
public int PasswordLifetimeDays { get; set; }
public SsoAdminClient GetClient() {
return _client;
}
}
}

Some files were not shown because too many files have changed in this diff Show More