This commit is contained in:
Zack Meier
2026-04-15 15:45:50 -05:00
commit 1d304511b8
613 changed files with 140998 additions and 0 deletions
@@ -0,0 +1,140 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Approve-ITDVMNewBuild {
[CmdletBinding()]
param (
[Parameter(Mandatory = $True)]
[string]
$SCTaskNum,
[switch]
$CloseTask,
[switch]
$NoTaskUpdates
)
begin {
}
process {
# get current user, SCTask, Ritm
$assignTo = Get-ServiceNowRecord -Table 'User' -Filter @('email', '-eq', ($env:username + "@nd.gov"))
$SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
$RitmNum = $SCTask.request_item.display_value
$Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable
$ComputerName = ($Ritm.CustomVariable | Where-Object Name -EQ host_name).Value
$OperatingSystem = ($Ritm.CustomVariable | Where-Object Name -EQ operating_system).Value
switch (($Ritm.CustomVariable | Where-Object Name -EQ target_platform).Value) {
'azure' { $target_platform = "Azure" }
'vmware' { $target_platform = "VMware" }
}
# update short description
If ($NoTaskUpdates -eq $false) {
$shortdescription = "$target_platform $OperatingSystem VM Build for $ComputerName"
If ( ($RITM.CustomVariable | Where-Object Name -EQ dr_protection).Value -ne 'No DR') {
$shortdescription += ", with SRM protection"
}
Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = $shortdescription; assigned_to = $assignTo.name }
}
# search for VM
switch (($Ritm.CustomVariable | Where-Object Name -EQ "target_platform").Value) {
'azure' {
# update task close notes, task customer notes, and ritm customer notes
$CommentsToAdd = "Azure VM " + $ComputerName + " build completed. `n" + $CommentsForWorkNotes
}
'vmware' {
$VM = Get-VM -Name $ComputerName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
switch (@($VM).count) {
{ 0 -or $null } {
# no matches
Write-Error -Message "Zero VM matches found, ending script" -ErrorAction Stop
}
{ $_ -ne 1 } {
# more than one match
Write-Error -Message " VM matches found, ending script" -ErrorAction Stop
}
{ 1 } {
# add missing tags
switch (($Ritm.CustomVariable | Where-Object Name -EQ environment).Value){
'Development' {
$DtapString = 'Test'
}
'Test' {
$DtapString = 'Test'
}
'Production' {
$DtapString = 'Production'
}
}
$SetITDVMwareTagsParams = @{
ComputerName = $ComputerName;
#AppName = ($Ritm.CustomVariable | Where-Object Name -EQ application_name).Value;
Dtap = $DtapString;
#OperatingSystem = switch ( ($Ritm.CustomVariable | Where-Object Name -EQ target_os_version_windows).Value) {
# 'Windows Server 2019 Datacenter' { "Windows Server 2019 Standard (64-Bit)" }
# 'Windows Server 2022 Datacenter' { "Windows Server 2022 Standard (64-Bit)" }
#}
StartupPriority = ($Ritm.CustomVariable | Where-Object Name -EQ startup_priority).Value;
LicensingRestrictions = ($Ritm.CustomVariable | Where-Object Name -EQ licensing_restrictions).Value;
}
Set-ITDVMwareVMTag @SetITDVMwareTagsParams
$AppNameTag = Get-TagAssignment -Entity $VM -Category AppName -ErrorAction SilentlyContinue
If ($AppNameTag) {
# move VM to VM folder that matches AppName tag
Write-Verbose -Message ("AppName tag " + $AppNameTag.Tag.Name + " found, attempting to move to AppName folder")
Move-ITDVMwareVMToAppNameFolder -Name $ComputerName
$CommentsForWorkNotes += "VM $ComputerName moved to AppName folder. "
}
Else {
Write-Warning "Review AppName tag for $ComputerName, required for backups"
}
If (($Ritm.CustomVariable | Where-Object Name -EQ "dr_protection").value -ne 'No DR') {
Write-Warning "SCTask is not Closed. Review SRM Protection values manually"
$AutoCloseTask = $false
}
Else {
$AutoCloseTask = $true
}
# update task close notes, task customer notes, and ritm customer notes
$CommentsToAdd = "VMware VM " + $ComputerName + " build completed. " + $CommentsForWorkNotes
}
}
}
}
If ($NoTaskUpdates -eq $false) {
Update-ServiceNowRecord -ID $SCTask.number -Values @{work_notes = $CommentsToAdd; close_notes = $CommentsToAdd; } # enter comments into sctask
Update-ServiceNowRecord -ID $RitmNum -Values @{comments = $CommentsToAdd }
If ($CloseTask -eq $True -or $AutoCloseTask -eq $True) {
Update-ServiceNowRecord -ID $SCTask.number -Values @{state = "Closed Complete" }
}
}
}
end {
}
}
@@ -0,0 +1,137 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Compare-ITDVMwareVMTagFromCmdb {
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ParameterSetName = 'VMName'
)]
[string[]]
$VMName
)
begin {
#$Result = [System.Collections.ArrayList]@()
}
process {
ForEach ($vname in $VMName) {
$HostName = $vname.split('.')[0]
Write-Verbose -Message "Looking up Cmdb Object named $HostName"
$Cmdb = Get-ITDServiceNowRecord -Table cmdb_ci_server -Filter "name=$HostName"
If ($null -eq $Cmdb) {
Write-Warning -Message "No Cmdb Object found for $HostName"
Continue
}
$VM = Get-VM -Name $vname | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
$OldTags = Get-TagAssignment -Entity $VM
$VMCompare = [PSCustomObject]@{
VMName = $vname;
DTAP = $null;
AppName = $null;
LicensingRestrictions = $null;
DRProtection = $null;
SRMRecoveryType = $null;
}
# DTAP
#If ($Cmdb.environment.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'DTAP' }).Tag.Name
If ($Cmdb.environment.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vname DTAP Tag to " + $Cmdb.environment.display_value)
#Set-ITDVMwareVMTag -ComputerName $vname -Dtap $Cmdb.environment.display_value
$VMCompare.DTAP = $false
}
Else {
$VMCompare.DTAP = $true
}
#}
# AppName
#If ($Cmdb.u_nd_application_svc.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'AppName' }).Tag.Name
If ($Cmdb.u_nd_application_svc.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vname AppName Tag to " + $Cmdb.u_nd_application_svc.display_value)
#Set-ITDVMwareVMTag -ComputerName $vname -AppName $Cmdb.u_nd_application_svc.display_value
$VMCompare.AppName = $false
}
Else {
$VMCompare.AppName = $true
}
#}
# Licensing Restrictions
#If ($Cmdb.u_nd_licensing_restrictions.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'LicensingRestrictions' }).Tag.Name
If ($Cmdb.u_nd_licensing_restrictions.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vname Licensing Restrictions Tag to " + $Cmdb.u_nd_licensing_restrictions.display_value)
#Set-ITDVMwareVMTag -ComputerName $vname -LicensingRestrictions $Cmdb.u_nd_licensing_restrictions.display_value
$VMCompare.LicensingRestrictions = $false
}
Else {
$VMCompare.LicensingRestrictions = $true
}
#}
# startup priority TBD
# startup priority is not in Cmdb
# SRM Recovery Type
#If ($Cmdb.u_srm_recovery_type.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'SRM Recovery Type' }).Tag.Name
If ($Cmdb.u_srm_recovery_type.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vname SRM Recovery Type Tag to " + $Cmdb.u_srm_recovery_type.display_value)
#Set-ITDVMwareVMTag -ComputerName $vname -SRMRecoveryType $Cmdb.u_srm_recovery_type.display_value
$VMCompare.SRMRecoveryType = $false
}
Else {
$VMCompare.SRMRecoveryType = $true
}
#} Else {
#$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'SRM Recovery Type' }).Tag.Name
#If ($null -ne $TagAssignmentValue) {
#Write-Verbose -Message ("Setting $vname SRM Recovery Type Tag to " + $null)
#$VMCompare.SRMRecoveryType = $false
#}
#Else {
#$VMCompare.SRMRecoveryType = $true
#}
#}
#
# DR Protection
#If ( ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO") ) {
#-replace "VMware: " -replace "RPO", "VR RPO"
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'DR Protection' }).Tag.Name
If ( ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO") -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vname DR Protection Tag to " + ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: ") )
#Set-ITDVMwareVMTag -ComputerName $vname -DRProtection ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO")
$VMCompare.DRProtection = $false
}
Else {
$VMCompare.DRProtection = $true
}
#}
Write-Output $VMCompare
}
}
end {
}
}
@@ -0,0 +1,32 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Get-ITDVMwareVMAppNameTag {
[CmdletBinding()]
param (
)
begin {
$ViServer = $global:defaultviservers | sort-object Name | select -first 1
}
process {
$AppNameTags = Get-Tag -Category AppName -Server $ViServer.Name
}
end {
$AppNameTags
}
}
@@ -0,0 +1,63 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Get-ITDVMwareVMHardening {
[CmdletBinding()]
param(
[string]
$Name
)
Begin {
}
Process {
$SettingName = @(
"tools.setInfo.sizeLimit",
"isolation.device.edit.disable",
"isolation.device.connectable.disable",
"isolation.tools.copy.disable",
"isolation.tools.dnd.disable",
"isolation.tools.setGUIOptions.enable",
"isolation.tools.paste.disable",
"isolation.tools.diskShrink.disable",
"isolation.tools.diskWiper.disable",
"log.keepOld",
"log.rotateSize"
)
$Result = [System.Collections.ArrayList]@()
ForEach ($n in $Name) {
$VM = Get-VM -Name $n | Where-Object { $_.ExtensionData.Summary.Config.ManagedBy.Type -ne "placeholderVm" }
$GetAdvSetting = Get-AdvancedSetting -Entity $VM -Name $SettingName | select Entity, Name, Value
$obj = [PSCustomObject]@{
'Entity' = $VM.Name
'Uid' = $VM.Uid.split('@')[1].split(':')[0]
"tools.setInfo.sizeLimit" = ($GetAdvSetting | Where-Object Name -EQ 'tools.setInfo.sizeLimit').Value
"isolation.device.edit.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.device.edit.disable').Value
"isolation.device.connectable.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.device.connectable.disable').Value
"isolation.tools.copy.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.copy.disable').Value
"isolation.tools.dnd.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.dnd.disable').Value
"isolation.tools.setGUIOptions.enable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.setGUIOptions.enable').Value
"isolation.tools.paste.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.paste.disable').Value
"isolation.tools.diskShrink.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.diskShrink.disable').Value
"isolation.tools.diskWiper.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.diskWiper.disable').Value
"log.keepOld" = ($GetAdvSetting | Where-Object Name -EQ 'log.keepOld').Value
"log.rotateSize" = ($GetAdvSetting | Where-Object Name -EQ 'log.rotateSize').Value
}
$Result.Add($obj)
}
}
End {
Write-Output $Result
}
}
@@ -0,0 +1,40 @@
<#
.Synopsis
Retreives list of all VMs, and lists their corresponding vSphere Replication RPO settings, if applicable.
.DESCRIPTION
Long description
.EXAMPLE
Get-ITDVMwareRPO
#>
function Get-ITDVMwareVMRPO {
[CmdletBinding()]
Param
(
)
Begin {
}
Process {
$VMs = Get-VM -Name itddohslimsp2.nd.gov | Where-Object PowerState -EQ PoweredOn
$result = @()
ForEach ($VM in $VMs) {
Write-Verbose $VM.Name
$RPOMinutes = ($VM.ExtensionData.Config.extraconfig | Where-Object key -EQ hbr_filter.rpo).Value
$DatastoreTag = ($VM | Get-TagAssignment -Category "VR Datastores").Tag.Name
$Cluster = ($VM | Get-Cluster).Name
$obj = [PSCustomObject]@{
'Name' = $VM.Name;
'Cluster' = $Cluster;
'Datastore' = $DatastoreTag;
'RPO' = $RPOMinutes;
}
Write-Warning $obj
$result += $obj
}
}
End {
Write-Output $result
}
}
@@ -0,0 +1,122 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Get-ITDVMwareVMTagReport {
[CmdletBinding()]
param (
[Parameter(
ValueFromPipeline = $true,
ParameterSetName = 'VMName'
)]
[string]
$VMName
)
begin {
#$Result = [System.Collections.ArrayList]@()
}
process {
If ($PSBoundParameters.ContainsKey('VMName')) {
# do nothing
}
Else {
$VMName = Get-VM | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
ForEach ($vn in $VMName) {
$HostName = $vn.split('.')[0]
Write-Verbose -Message "Looking up Cmdb Object named $HostName"
$Cmdb = Get-ITDServiceNowRecord -Table cmdb_ci_server -Filter "name=$HostName"
$VM = Get-VM -Name $vn | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
$OldTags = Get-TagAssignment -Entity $VM
$obj = [PSCustomObject]@{
VMName = $vn;
DTAP = $null;
AppName = $null;
LicensingRestrictions = $null;
DRProtection = $null;
SRMRecoveryType = $null;
}
# DTAP
If ($Cmdb.environment.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'DTAP' }).Tag.Name
If ($Cmdb.environment.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vn DTAP Tag to " + $Cmdb.environment.display_value)
$obj.DTAP = $false
}
Else {
$obj.DTAP = $true
}
}
# AppName
If ($Cmdb.u_nd_application_svc.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'AppName' }).Tag.Name
If ($Cmdb.u_nd_application_svc.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vn AppName Tag to " + $Cmdb.u_nd_application_svc.display_value)
$obj.AppName = $false
}
Else {
$obj.AppName = $true
}
}
# Licensing Restrictions
If ($Cmdb.u_nd_licensing_restrictions.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'LicensingRestrictions' }).Tag.Name
If ($Cmdb.u_nd_licensing_restrictions.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vn Licensing Restrictions Tag to " + $Cmdb.u_nd_licensing_restrictions.display_value)
$obj.LicensingRestrictions = $false
}
Else {
$obj.LicensingRestrictions = $true
}
}
# startup priority TBD
# startup priority is not in Cmdb
# SRM Recovery Type
If ($Cmdb.u_srm_recovery_type.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'SRM Recovery Type' }).Tag.Name
If ($Cmdb.u_srm_recovery_type.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vn SRM Recovery Type Tag to " + $Cmdb.u_srm_recovery_type.display_value)
$obj.SRMRecoveryType = $false
}
Else {
$obj.SRMRecoveryType = $true
}
}
#
# DR Protection
If ( ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO") ) {
#-replace "VMware: " -replace "RPO", "VR RPO"
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'DR Protection' }).Tag.Name
If ( ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO") -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $vn DR Protection Tag to " + ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: ") )
$obj.DRProtection = $false
}
Else {
$obj.DRProtection = $true
}
}
}
}
end {
Write-Output $obj
}
}
@@ -0,0 +1,71 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Get-ITDVMwareVMToolsReport {
[CmdletBinding()]
param (
[string[]]
$VMName,
[ValidateSet("Windows", "RHEL", "Other")]
[string]
$GuestOS
)
begin {
}
process {
If ($PSBoundParameters.ContainsKey('VMName')) {
$AllVMs = Get-VM -Name $VMName | Where-Object { $_.ExtensionData.Summary.Config.ManagedBy.Type -ne "placeholderVm" -and $_.Name -notlike "vCLS*" }
}
else {
$AllVMs = Get-VM | Where-Object { $_.ExtensionData.Summary.Config.ManagedBy.Type -ne "placeholderVm" -and $_.Name -notlike "vCLS*" }
}
If ($PSBoundParameters.ContainsKey('GuestOS') ) {
switch ($GuestOS) {
"Windows" {
$AllVMs = $AllVMs | Where-Object { $_.ExtensionData.Guest.GuestId -like "*windows*" }
}
"RHEL" {
$AllVMs = $AllVMs | Where-Object { $_.ExtensionData.Guest.GuestId -like "*rhel*" }
}
"Other" {
$AllVMs = $AllVMs | Where-Object { $_.ExtensionData.Guest.GuestId -notlike "*rhel*" -and $_.ExtensionData.Guest.GuestId -notlike "*windows*" }
}
Default {
Write-Error "Invalid GuestOS specified. Use 'Windows' or 'RHEL'."
return
}
}
}
ForEach ($VM in $AllVMs) {
$obj = [PSCustomObject]@{
Name = $VM.Name;
PowerState = $VM.PowerState;
GuestOS = $VM.ExtensionData.Guest.GuestId;
ToolsVersion = $VM.ExtensionData.Config.Tools.ToolsVersion;
ToolsUpgradePolicy = $VM.ExtensionData.Config.Tools.ToolsUpgradePolicy
}
Write-Output $obj
}
}
end {
}
}
@@ -0,0 +1,59 @@
<#
.SYNOPSIS
Move Virtual Machines to the correct folder based on the AppName tag
.DESCRIPTION
Move Virtual Machines to the correct folder based on the AppName tag
.NOTES
.LINK
.EXAMPLE
Move-ITDVMwareVMToAppNameFolder -VMName itdservername.nd.gov
#>
function Move-ITDVMwareVMToAppNameFolder {
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string[]]
$VMName
)
begin {
}
process {
Write-Verbose -Message "Gathering Virtual Machine information"
$VMs = Get-VM -Name $VMName | Select-Object Name, PowerState, Folder, @{n = 'VIServer'; e = { $_.Uid.split('@')[1].split(':')[0] } }, @{n = 'AppName'; e = { (Get-TagAssignment -Category AppName -Entity $_).Tag.Name } }, @{n = 'Datacenter'; e = { ($_ | Get-Datacenter).Name } } | Sort-Object Name
ForEach ($VM in $VMs) {
Write-Verbose -Message ("Start " + $VM.Name)
$NewFolder = $null
$Owner = $VM.AppName.split('-')[0]
Write-Verbose ($VM.Name + ": current folder is " + $VM.Folder.Name)
Write-Verbose ($VM.Name + ": current appname is " + $VM.AppName)
If ($VM.Folder.Name -ne $VM.AppName) {
If ($VM.AppName) {
Write-Verbose ($VM.Name + ": Folder and AppName are different!!! moving VM to folder " + $VM.AppName)
If (!(Get-Datacenter $VM.Datacenter | Get-Folder -Name $VM.AppName -Server $VM.VIServer -ErrorAction SilentlyContinue)) {
New-Folder -Name $VM.AppName -Location (Get-Datacenter $VM.Datacenter | Get-Folder -Type VM -Name $Owner -Server $VM.VIServer)
}
$NewFolder = Get-Datacenter $VM.Datacenter | Get-Folder $VM.AppName -Server $VM.VIServer
Move-VM -VM $VM.Name -InventoryLocation $NewFolder -Destination (Get-VM $VM.Name -Server $VM.VIServer).VMHost
}
Else {
}
}
}
}
end {
}
}
@@ -0,0 +1,282 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
$NewITDVMSNowRitmParams = @{
RequestType = "New";
ComputerName = "itdzmtest100.nd.gov";
SysadminEmail = "zmeier@nd.gov";
CustomerRitm = "RITM0145886";
Environment = "Test";
AppName = "Infra-VMware";
Comments = "New VM for VMware sandbox, see RITM0145886 for details";
OperatingSystem = "Windows";
TargetOSVersion = "Windows Server 2022 Datacenter";
TargetPlatform = "VMware";
NumCpu = 1;
MemoryGB = 4;
Disk1GB = 50;
Disk2GB = 5;
CIDR = '10.11.12.0/23';
Datacenter = 'Bismarck';
LicensingRestrictions = 'No Licensing Restrictions';
AgencyPrefix = 'ITD';
SupportHours = 'All Day Every Day';
DRProtection = 'No DR';
StartupPriority = 5;
}
New-ITDVMSNowRitm @NewITDVMSNowRitmParams
.EXAMPLE
New-ITDVMSNowRitm -ImportCsv "C:\temp\NewITDVMSnowRitm.csv"
#>
function New-ITDVMSNowRitm {
[CmdletBinding()]
param (
[Parameter(ParameterSetName = 'Csv')]
[string]
$ImportCsv,
[Parameter(ParameterSetName = 'Single', Mandatory = $true)]
[ValidateSet('New', 'Upgrade/Code Deployment', 'Removal', 'Other')]
[string]
$RequestType,
[Parameter(ParameterSetName = 'Single', Mandatory = $true)]
[string]
$ComputerName,
[Parameter(ParameterSetName = 'Single', Mandatory = $true)]
[string]
$SysadminEmail,
[Parameter(ParameterSetName = 'Single', Mandatory = $true)]
[string]
$Comments,
[Parameter(ParameterSetName = 'Single', Mandatory = $true)]
[ValidateSet('Production', 'Test')]
[string]
$Environment,
[Parameter(ParameterSetName = 'Single', Mandatory = $true)]
[string]
$AppName,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet('Linux', 'Windows')]
[string]
$OperatingSystem,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet(
'Windows Server 2019 Datacenter',
'Windows Server 2022 Datacenter'
)]
[string]
$TargetOSVersion,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet('VMware', 'Azure')]
$TargetPlatform,
[Parameter(ParameterSetName = 'Single')]
[int]
$NumCpu,
[Parameter(ParameterSetName = 'Single')]
[int]
$MemoryGB,
[Parameter(ParameterSetName = 'Single')]
[int]
$Disk1GB,
[Parameter(ParameterSetName = 'Single')]
[int]
$Disk2GB,
[Parameter(ParameterSetName = 'Single')]
[string]
$CIDR,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet('Bismarck', 'Mandan')]
[string]
$Datacenter,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet(
'No Licensing Restrictions',
'Microsoft SharePoint Server',
'Microsoft SharePoint Server (Academic)',
'Microsoft SQL Developer',
'Microsoft SQL MSDN',
'Microsoft SQL Standard',
'Microsoft SQL Standard (Academic)',
'Microsoft SQL Standard (Vendor Provided)',
'Microsoft SQL Enterprise',
'Microsoft SQL Enterprise (Academic)',
'IBM Websphere',
'IBM ODM',
'Oracle Standard Edition',
'Oracle Standard Edition One',
'Powerschool'
)]
[string]
$LicensingRestrictions,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet('ITD', 'DHS', 'DOT')]
[string]
$AgencyPrefix,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet('All Day Every Day', 'All Week 500 to 2300', 'Weekdays 700 1800')]
[string]
$SupportHours,
[Parameter(ParameterSetName = 'Single')]
[ValidateSet(
'No DR',
'VMWare: ABR',
'VMWARE: RPO 0:15',
'VMWARE: RPO 0:30',
'VMWARE: RPO 1:00',
'VMWARE: RPO 2:00',
'VMWARE: RPO 4:00',
'VMWARE: RPO 8:00')]
[string]
$DRProtection,
[Parameter(ParameterSetName = 'Single')]
[ValidateRange(1, 5)]
[int]
$StartupPriority
)
begin {
}
process {
switch ($PSCmdlet.ParameterSetName) {
'Csv' {
$Csv = Import-Csv $ImportCsv
ForEach ($item in $csv) {
$NewITDVMSNowRitmParams = @{
RequestType = $item.RequestType
ComputerName = $item.ComputerName
SysadminEmail = $item.SysadminEmail
Environment = $item.Environment
AppName = $item.AppName
Comments = $item.Comments
OperatingSystem = $item.OperatingSystem
TargetOSVersion = $item.TargetOSVersion
TargetPlatform = $item.TargetPlatform
NumCpu = $item.NumCpu
MemoryGB = $item.MemoryGB
Disk1GB = $item.Disk1GB
Disk2GB = $item.Disk2GB
CIDR = $item.CIDR
Datacenter = $item.Datacenter
LicensingRestrictions = $item.LicensingRestrictions
AgencyPrefix = $item.AgencyPrefix
SupportHours = $item.SupportHours
DRProtection = $item.DRProtection
StartupPriority = $item.StartupPriority
}
New-ITDVMSNowRitm @NewITDVMSNowRitmParams
}
}
'Single' {
Write-Verbose -Message ("Start " + $ComputerName)
# determine lookup fields
switch ($PSBoundParameters.Keys) {
CIDR {
$cidr_block = Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -Filter "name=$CIDR"
If ($null -eq $cidr_block) { Write-Error -Message "CIDR is invalid" -ErrorAction Stop }
}
AgencyPrefix {
switch ($AgencyPrefix) {
'DHS' { $AgencyNum = '325.0' }
'DOT' { $AgencyNum = '801.0' }
'ITD' { $AgencyNum = '112.0' }
}
$Agency = Get-ITDServiceNowRecord -Table 'cmn_department' -Filter "id=$AgencyNum"
}
AppName {
$application_info = Get-ITDServiceNowRecord -Table cmdb_ci_service -Filter ("name=$AppName")
}
# send ints as strings
NumCpu {
[string]$NumCpuStr = $NumCpu.ToString()
}
MemoryGB {
[string]$MemoryGBStr = $MemoryGB.ToString()
}
Disk1GB {
[string]$Disk1GBStr = $Disk1GB.ToString()
}
Disk2GB{
[string]$Disk2GBStr = $Disk2GB.ToString()
}
}
$team_lead_sysid = (Get-ITDServiceNowUser -Email $RequestedForEmail).manager.value
$NewITDServiceNowServiceCatalogRequestParams = @{ # review and update all of these too
CategoryItemName = "Application Server";
RequestedForEmail = $SysadminEmail;
Values = @{
request_type = $RequestType;
application_name = $AppName;
environment = $Environment;
require_hosting_quote = 'No';
server_name = $ComputerName;
add_change_disaster_recovery = 'No';
additional_comments = $Comments;
####
vm_work_needed = 'Yes';
host_name = $ComputerName;
server_type = 'Virtual';
operating_system = $OperatingSystem;
target_os_version_windows = $TargetOSVersion;
target_platform = $TargetPlatform;
processors = $NumCpuStr;
memory_gb = $MemoryGBStr;
disk_1_os = $Disk1GBStr;
disk_2_swap_disk = $Disk2GBStr;
data_center = $Datacenter;
licensing_restrictions = $LicensingRestrictions;
support_hours = $SupportHours;
dr_protection = $DRProtection;
startup_priority = $StartupPriority;
# lookups
cidr_block = $cidr_block.sys_id;
agency_name = $agency.sys_id;
team_lead = $team_lead.sys_id;
application_info = $application_info.sys_id;
};
}
New-ITDServiceNowServiceCatalogRequest @NewITDServiceNowServiceCatalogRequestParams
#$NewITDServiceNowServiceCatalogRequestParams
Write-Verbose -Message ("End " + $ComputerName)
}
}
}
end {
}
}
@@ -0,0 +1,193 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
$params = @{
HostName = "itdzmtest999.nd.gov";
LicensingRestrictions = "No Licensing Restrictions";
DataCenter = 'Bismarck';
Environment = 'Test';
StartupPriority = '5';
OperatingSystem = 'Windows Server 2022 Datacenter (64-Bit)'
DR_Protection = 'None';
CPU = 1;
MemoryGB = 4;
Disk1 = 50;
Disk2 = 2;
Disk3 = 3;
}
New-ITDVMwareSharePointVMRecord @params
#>
function New-ITDVMwareSharePointVMRecord {
[CmdletBinding()]
param (
[string]
$HostName,
[string]
$ReplacesVM,
[string]
$LicensingRestrictions,
<#[string]
$AgencyName,#>
[string]
$SupportHours,
[string]
$DataCenter,
[string]
$Environment,
[int]
$StartupPriority,
[string]
$DR_Protection,
[string]
$OperatingSystem,
[int]
$CPU,
[int]
$MemoryGB,
[string]
$CIDRBlock,
[int]
$Disk1,
[int]
$Disk2,
[int]
$Disk3,
[int]
$Disk4,
[int]
$Disk5,
[int]
$Disk6,
[int]
$Disk7,
[int]
$Disk8,
[int]
$Disk9,
[int]
$Disk10,
[int]
$Disk11,
[int]
$Disk12,
[int]
$Disk13,
[int]
$Disk14,
[int]
$Disk15,
[int]
$Disk16
)
begin {
$UrlContextInfo = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/contextinfo"
$InvokeWebRequestParams = @{
Uri = $UrlContextInfo;
Method = "Post";
UseBasicParsing = $true;
}
If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
#$RequestDigest = Invoke-RestMethod -Uri $UrlContextInfo -Method Post -UseDefaultCredentials
$RequestDigest = Invoke-RestMethod @InvokeWebRequestParams
$RequestDigest = $RequestDigest.GetContextWebInformation.FormDigestValue
$UrlList = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VM Guests')"
$InvokeWebRequestParams = @{
Uri = $UrlList;
UseBasicParsing = $true;
}
If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
#$List = Invoke-RestMethod -uri $UrlList -UseDefaultCredentials
$List = Invoke-RestMethod @InvokeWebRequestParams
$ListItemEntityTypeFullName = $list.entry.content.properties.ListItemEntityTypeFullName
$UrlListItems = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VM Guests')/items"
$header = @{
"accept" = "application/json;odata=verbose"
"X-RequestDigest" = $RequestDigest
}
}
process {
[PSCustomObject]$NewRecord = @{
"__metadata" = @{type = $ListItemEntityTypeFullName }
Title = $HostName
}
write-host $PSBoundParameters
switch($PSBoundParameters.Keys){
# '' {$NewRecord += @{ = }}
'LicensingRestrictions' {$NewRecord += @{LicensingRestrictions = $LicensingRestrictions}}
'DataCenter' {$NewRecord += @{DataCenter = $DataCenter}}
'Environment' {$NewRecord += @{Environment = $Environment}}
'StartupPriority' {$NewRecord += @{StartupPriority = [string]$StartupPriority}}
'OperatingSystem' {$NewRecord += @{OS = $OperatingSystem}}
'DR_Protection' {$NewRecord += @{DR_Protection = $DR_Protection}}
'CPU' {$NewRecord += @{Processors = $CPU}}
'MemoryGB' {$NewRecord += @{RAM = $MemoryGB}}
'Disk1' {$NewRecord += @{Disk_x0020_C_x003a_ = $Disk1}}
'Disk2' {$NewRecord += @{Disk2_x002d_SwapDisk = $Disk2}}
'Disk3' {$NewRecord += @{Disk_x0020_D_x003a_ = $Disk3}}
}
$body = $NewRecord | ConvertTo-Json
$InvokeWebRequestParams = @{
Uri = $UrlListItems;
Method = "Post";
Body = $body;
ContentType = "application/json;odata=verbose";
Headers = $header;
UseBasicParsing = $true;
}
If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
#Invoke-RestMethod -Method Post -Uri $UrlListItems -Body $body -ContentType "application/json;odata=verbose" -Headers $header -UseDefaultCredentials
Invoke-RestMethod @InvokeWebRequestParams
}
end {
}
}
@@ -0,0 +1,80 @@
<#
.SYNOPSIS
Updates ServiceNow SCTask after a Linux VM is deleted
.DESCRIPTION
Updates ServiceNow SCTask after a Linux VM is deleted
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Remove-ITDLinuxServerMissingCmdb {
[CmdletBinding()]
param (
[string]
$SCTaskNum,
[string]
$ComputerName
)
begin {
}
process {
# get current user, SCTask, Ritm, custom variables
$assignTo = Get-ServiceNowRecord -Table 'User' -Filter @('email', '-eq', ($env:username + "@nd.gov"))
$SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
$RitmNum = $SCTask.request_item.display_value
$Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable
[string]$SNHostName = ($RITM.CustomVariable | Where-Object Name -EQ server_name).Value
Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = "VMware VM Removal for $SNHostName"; assigned_to = $assignTo.name }
If ($ComputerName -ne $SNHostName) {
# false is good
Write-Error -Message ("ComputerName entered in parameters does not match Host Name field in " + $SCTaskNum) -ErrorAction Stop
}
$VMs = Get-VM -Name $ComputerName -ErrorAction SilentlyContinue | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
switch (@($VMs).count) {
{ 0 } {
Write-Warning "$ComputerName not found in vCenter... is it Azure?"
}
{ $_ -gt 1 } {
Write-Warning '-gt 1'
Write-Error -Message ("Multiple virtual machines with name $ComputerName were found. Are there SRM placeholders? If so, unconfigure SRM and run this again. If there are no placeholders, confirm the virtual machine name.") -ErrorAction Stop
}
1 {
Write-Warning '1'
$TagAssignment = Get-TagAssignment -Entity $VMs
$vCenterInfo = $TagAssignment | select Tag, Entity | ConvertTo-Json -Depth 1
If ($VMs.PowerState -eq 'PoweredOn') {
#$VMs | Stop-VMGuest -Confirm:$false
$VMs | Stop-VM -Confirm:$false
}
If ($vCenterInfo) {
Update-ServiceNowRecord -ID $SCTaskNum -Values @{work_notes = ("vCenter Information: `n " + $vCenterInfo) } # enter work_notes into sctask
}
}
}
$CommentsForWorkNotes = ("VMware VM $SNHostName has been deleted. ")
#$HardwareRemovalDescription = ("$SNHostName hardware is ready for removal.")
# if no errors, close sctask
#$CommentsForWorkNotes += "VMware: Virtual machine named $ComputerName deleted."
Update-ServiceNowRecord -ID $SCTaskNum -Values @{work_notes = $CommentsForWorkNotes; state = "Closed Complete"; close_notes = $CommentsForWorkNotes}
}
end {
}
}
@@ -0,0 +1,130 @@
<#
.SYNOPSIS
Updates ServiceNow SCTask after a Linux VM is deleted
.DESCRIPTION
Updates ServiceNow SCTask after a Linux VM is deleted
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Remove-ITDVMviaSNowTask {
[CmdletBinding()]
param (
[string]
$SCTaskNum,
[string]
$ComputerName
)
begin {
}
process {
# get current user, SCTask, Ritm, custom variables
switch ($env:username) {
'svcitdiaasauto' {
$assignTo = Get-ITDServiceNowUser -Username svcvmwareadm
}
Default {
$assignTo = Get-ITDServiceNowUser -Username $Env:username
}
}
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$RitmNum = $SCTask.request_item.display_value
Write-Verbose -Message "Retrieve $RitmNum and its VariableSet"
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $RitmNum -IncludeVariableSet -ErrorAction Stop
###### the name in the $ComputerName parameter must match a name in the form to continue
Write-Verbose -Message "Looking for a match of `$ComputerName $ComputerName and one of the rows' `$TempCi.FQDN.display_value"
$MatchFound = $false
ForEach ($Row in $Ritm.VariableSet) {
$TempCi = Get-ITDServiceNowRecord -Table cmdb_ci -SysId ($Row.host_name_ref) -ErrorAction Stop
If ($ComputerName -eq $TempCi.FQDN.display_value) {
$Ci = $TempCi
$MatchFound = $true
}
}
If ($MatchFound -eq $false) {
Write-Error -Message "ComputerName $ComputerName was not found in VariableSet for $RitmNum" -ErrorAction Stop
}
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTask.number.display_value -Values @{assigned_to = $assignTo.name }
$FQDN = $Ci.fqdn.display_value
switch ( $Ci.model_id.display_value ) {
{ $_ -like "*VMware*" } {
$hardware_platform = "VMware";
$hardware_type = 'Virtual Machine'
$VMs = Get-VM -Name $FQDN -ErrorAction SilentlyContinue | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
switch ( @($VMs).count ) {
{ 0 } {
Write-Warning "$FQDN not found in vCenter... is it Azure? Or does it not exist?"
}
{ $_ -gt 1 } {
Write-Verbose -Message "Multiple virtual machines with name $FQDN were found."
Write-Error -Message ("Multiple virtual machines with name $FQDN were found. Are there SRM placeholders? If so, unconfigure SRM and run this again. If there are no placeholders, confirm the virtual machine name.") -ErrorAction Stop
}
1 {
Write-Verbose -Message "One virtual machine with name $FQDN were found."
If ($VMs.PowerState -eq 'PoweredOff') {
# do nothing
}
Else {
Write-Error -Message "VMware VM $FQDN is still powered on. "
}
$TagAssignment = Get-TagAssignment -Entity $VMs
$vCenterInfo = $TagAssignment | select Tag, Entity | ConvertTo-Json -Depth 1
If ($VMs.PowerState -eq 'PoweredOn') {
Write-Verbose -Message "Power off VMware VM $FQDN"
$CommentsForWorkNotes += ("`nVMware: VM $FQDN has been powered off. ")
$VMs | Stop-VM -Confirm:$false
}
#If ($vCenterInfo) {
# enter work_notes into sctask
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = ("vCenter Information: `n " + $vCenterInfo)
}
#}
}
}
}
{ $_ -like "*Microsoft Virtual Machine*" } {
$hardware_platform = "Azure";
$hardware_type = 'Virtual Machine'
}
{ $_ -like "*HP*" } {
$hardware_platform = 'HPE';
$hardware_type = 'Physical'
}
default { $hardware_platform = 'Other' }
}
$CommentsForWorkNotes = ("$hardware_platform $hardware_type $FQDN has been deleted. ")
# Set SharePoint status to "Delete"
#Set-ITDVMwareSharePointVMRecord -Title $FQDN -Status Delete -Verbose
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = $CommentsForWorkNotes;
state = 'Closed Complete';
close_notes = $CommentsForWorkNotes
}
}
end {
}
}
@@ -0,0 +1,117 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Set-ITDVMwareVMHardening {
[CmdletBinding()]
param(
[string[]]
$Name
)
Begin {
}
Process {
If ($Name) {
$VMs = Get-VM -Name $Name | Where-Object { $_.ExtensionData.Summary.Config.ManagedBy.Type -ne "placeholderVm" }
}
Else {
$VMs = Get-VM -Name $Name | Where-Object { $_.ExtensionData.Summary.Config.ManagedBy.Type -ne "placeholderVm" }
}
$SettingName = @(
"tools.setInfo.sizeLimit",
"isolation.device.edit.disable",
"isolation.device.connectable.disable",
"isolation.tools.copy.disable",
"isolation.tools.dnd.disable",
"isolation.tools.setGUIOptions.enable",
"isolation.tools.paste.disable",
"isolation.tools.diskShrink.disable",
"isolation.tools.diskWiper.disable",
"log.keepOld",
"log.rotateSize"
)
$Result = [System.Collections.ArrayList]@()
ForEach ($VM in $VMs) {
$GetAdvSetting = Get-AdvancedSetting -Entity $VM -Name $SettingName | select Entity, Name, Value
$obj = [PSCustomObject]@{
'Entity' = $VM.Name
'Uid' = $VM.Uid.split('@')[1].split(':')[0]
"tools.setInfo.sizeLimit" = ($GetAdvSetting | Where-Object Name -EQ 'tools.setInfo.sizeLimit').Value
"isolation.device.edit.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.device.edit.disable').Value
"isolation.device.connectable.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.device.connectable.disable').Value
"isolation.tools.copy.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.copy.disable').Value
"isolation.tools.dnd.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.dnd.disable').Value
"isolation.tools.setGUIOptions.enable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.setGUIOptions.enable').Value
"isolation.tools.paste.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.paste.disable').Value
"isolation.tools.diskShrink.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.diskShrink.disable').Value
"isolation.tools.diskWiper.disable" = ($GetAdvSetting | Where-Object Name -EQ 'isolation.tools.diskWiper.disable').Value
"log.keepOld" = ($GetAdvSetting | Where-Object Name -EQ 'log.keepOld').Value
"log.rotateSize" = ($GetAdvSetting | Where-Object Name -EQ 'log.rotateSize').Value
}
$Result.Add($obj)
}
$Result
# remediate VMs
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'tools.setInfo.sizeLimit' -ne 1048576 }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'tools.setInfo.sizeLimit' -Value '1048576' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.device.edit.disable' -ne "TRUE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.device.edit.disable' -Value 'TRUE' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.device.connectable.disable' -ne "TRUE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.device.connectable.disable' -Value TRUE -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.tools.copy.disable' -ne "TRUE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.tools.copy.disable' -Value 'TRUE' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.tools.dnd.disable' -ne "TRUE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.tools.dnd.disable' -Value 'TRUE' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.tools.setGUIOptions.enable' -ne "FALSE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.tools.setGUIOptions.enable' -Value 'FALSE' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.tools.paste.disable' -ne "TRUE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.tools.paste.disable' -Value 'TRUE' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.tools.diskShrink.disable' -ne "TRUE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.tools.diskShrink.disable' -Value 'TRUE' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'isolation.tools.diskWiper.disable' -ne "TRUE" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'isolation.tools.diskWiper.disable' -Value 'TRUE' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'log.keepOld' -ne "10" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'log.keepOld' -Value '10' -Confirm:$false -Force:$true
}
ForEach ($VM in ($Result | Where-Object { $_.Entity -notlike "vCLS*" -and $_.'log.rotateSize' -ne "1024000" }) ) {
Get-VM -Name $VM.Entity -Server $VM.Uid | New-AdvancedSetting -Name 'log.rotateSize' -Value '10' -Confirm:$false -Force:$true
}
}
End {
}
}
@@ -0,0 +1,330 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Set-ITDVMwareVMTag {
[CmdletBinding()]
param
(
[string]
$ComputerName,
[string]
$AppName,
[string]
$Dtap,
<#[string]
$OperatingSystem,#>
[string]
$StartupPriority,
[string]
$LicensingRestrictions,
[string]
$DRProtection,
[string]
$SRMRecoveryType
)
begin {
}
process {
$VMs = Get-VM -Name $ComputerName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
If ($VMs) {
ForEach ($VM in $VMs) {
#AppName Tag
If ($AppName) {
Write-Verbose ($VM.Name + ": AppName Tag Start")
$OldTag = Get-TagAssignment -Category AppName -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $AppName
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " AppName old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$false -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") } #Errors with Remove-TagAssignment : Cannot bind argument to parameter 'TagAssignment' because it is null. --- but still works
#Get-Tag -Category AppName -Name $NewTagName -Server $VIServer
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category AppName -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)#
}
Write-Verbose ($VM.Name + ": AppName Tag End")
}
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
#DTAP Tag
If ($DTAP) {
Write-Verbose ($VM.Name + ": DTAP Tag Start")
$OldTag = Get-TagAssignment -Category DTAP -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $DTAP
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " DTAP old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$false -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") } #Errors with Remove-TagAssignment : Cannot bind argument to parameter 'TagAssignment' because it is null. --- but still works
#Get-Tag -Category AppName -Name $NewTagName -Server $VIServer
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category DTAP -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
Write-Verbose ($VM.Name + ": DTAP Tag End")
}
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
#Startup Priority
If ($StartupPriority) {
Write-Verbose ($VM.Name + ": StartupPriority Tag Start")
$OldTag = Get-TagAssignment -Category 'StartupPriority' -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $StartupPriority
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " StartupPriority old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$false -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") } #Errors with Remove-TagAssignment : Cannot bind argument to parameter 'TagAssignment' because it is null. --- but still works
#Get-Tag -Category AppName -Name $NewTagName -Server $VIServer
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category 'StartupPriority' -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
Write-Verbose ($VM.Name + ": StartupPriority Tag End")
}
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
<# OS Tag
If ($OperatingSystem) {
Write-Verbose ($VM.Name + ": OS Tag Start")
$OldTag = Get-TagAssignment -Category "Operating System" -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $OperatingSystem
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " OS old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$False -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") }
If ($NewTagName -ne "None") {
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category 'Operating System' -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
else {
Write-Verbose ($VM.Name + " tag invalid or None " + $VIServer)
}
}
Write-Verbose ($VM.Name + ": OS Tag End")
}
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
#>
# Licensing Tag
If ($LicensingRestrictions) {
Write-Verbose ($VM.Name + ": Licensing Restrictions Tag Start")
$OldTag = Get-TagAssignment -Category "LicensingRestrictions" -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $LicensingRestrictions
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " Licensing old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$False -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") }
If ($NewTagName -ne "None") {
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category 'LicensingRestrictions' -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
else {
Write-Verbose ($VM.Name + " tag invalid or None " + $VIServer)
}
}
Write-Verbose ($VM.Name + ": Licensing Tag End")
}
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
# SRM Recovery Type Tag
If ($SRMRecoveryType) {
Write-Verbose ($VM.Name + ": SRM Recovery Type Tag Start")
$OldTag = Get-TagAssignment -Category "SRM Recovery Type" -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $SRMRecoveryType
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " SRM Recovery Type old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$False -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") }
If ($NewTagName -ne "None") {
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category 'SRM Recovery Type' -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
else {
Write-Verbose ($VM.Name + " tag invalid or None " + $VIServer)
}
}
Write-Verbose ($VM.Name + ": SRM Recovery Type Tag End")
}
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
# DR Protection
If ($DRProtection) {
Write-Verbose ($VM.Name + ": DR Protection Tag Start")
$OldTag = Get-TagAssignment -Category "DR Protection" -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $DRProtection
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " DR Protection old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$False -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") }
If ($NewTagName -ne "None") {
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category 'DR Protection' -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
else {
Write-Verbose ($VM.Name + " tag invalid or None " + $VIServer)
}
}
Write-Verbose ($VM.Name + ": DR Protection Tag End")
}
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
}
<# SRM Recovery Type Tags
Write-Verbose ($VM.Name + ": SRM Recovery Type Tag Start")
$OldTag = Get-TagAssignment -Category "SRM Recovery Type" -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
If ($VM.ExtensionData.summary.config.ManagedBy.Type -eq "placeholderVm" ) {
#If VM is placeholder
$NewTagName = "Placeholder"
}
Else {
$NewTagName = $SPItem.SRM_RecoveryVMtype
}
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " SRM Recovery Type old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$False -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") }
If ($NewTagName -ne "None") {
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category 'SRM Recovery Type' -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
else {
Write-Verbose ($VM.Name + " tag invalid or None " + $VIServer)
}
}
Write-Verbose ($VM.Name + ": SRM Recovery Type Tag End")#>
$OldTag = $null
$VIServer = $null
$OldTagName = $null
$NewTagName = $null
<#VR RPO Tag
Write-Verbose ($VM.Name + ": SRM Tag Start")
$OldTag = Get-TagAssignment -Category 'VR RPO' -Entity $VM
$VIServer = $VM.Uid.split('@')[1].split(':')[0]
$OldTagName = $OldTag.tag.name
$NewTagName = $SPItem.DR_Protection -replace "VMware: "
If ($OldTagName -ne $NewTagName) {
Write-Verbose ($VM.Name + " SRM old and new tags different")
Write-Verbose ("Old Tag " + $OldTagName)
Write-Verbose ("New Tag " + $NewTagName)
If ($OldTag) { $OldTag | Remove-TagAssignment -Confirm:$false -ErrorAction SilentlyContinue; Write-Host ($VM.Name + " Tag Removed") } #Errors with Remove-TagAssignment : Cannot bind argument to parameter 'TagAssignment' because it is null. --- but still works
#Get-Tag -Category AppName -Name $NewTagName -Server $VIServer
If ($NewTagName -ne "None") {
New-TagAssignment -Entity (Get-VM $VM.Name -Server $VIServer -OutVariable VM) -Tag (Get-Tag -Server $VIServer -Category 'VR RPO' -Name $NewTagName) -Server $VIServer
Write-Verbose ($VM.Name + " tag updated " + $VIServer)
}
else {
Write-Verbose ($VM.Name + " tag invalid or None " + $VIServer)
}
}#>
}
Else {
}
#}
<#catch {
Write-Error ($VM.Name + " tag errored")
Write-Error $error[-1]
}#>
}
end {
}
}
@@ -0,0 +1,119 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Set-ITDVMwareVMTagFromCmdb {
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ParameterSetName = 'VMName'
)]
[string]
$VMName
)
begin {
#$Result = [System.Collections.ArrayList]@()
}
process {
$HostName = $VMName.split('.')[0]
Write-Verbose -Message "Looking up Cmdb Object named $HostName"
$Cmdb = Get-ITDServiceNowRecord -Table cmdb_ci_server -Filter "name=$HostName"
If($null -eq $Cmdb) {
Write-Warning -Message "No Cmdb Object found for $HostName"
return
}
$VM = Get-VM -Name $VMName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" } | Sort-Object Name
$OldTags = Get-TagAssignment -Entity $VM
$obj = [PSCustomObject]@{
VMName = $VMName;
DTAP = $null;
AppName = $null;
LicensingRestrictions = $null;
DRProtection = $null;
SRMRecoveryType = $null;
}
# DTAP
If ($Cmdb.environment.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'DTAP' }).Tag.Name
If ($Cmdb.environment.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $VMName DTAP Tag to " + $Cmdb.environment.display_value)
Set-ITDVMwareVMTag -ComputerName $VMName -Dtap $Cmdb.environment.display_value
}
Else {
}
}
# AppName
If ($Cmdb.u_nd_application_svc.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'AppName' }).Tag.Name
If ($Cmdb.u_nd_application_svc.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $VMName AppName Tag to " + $Cmdb.u_nd_application_svc.display_value)
Set-ITDVMwareVMTag -ComputerName $VMName -AppName $Cmdb.u_nd_application_svc.display_value
}
Else {
}
}
# Licensing Restrictions
If ($Cmdb.u_nd_licensing_restrictions.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'LicensingRestrictions' }).Tag.Name
If ($Cmdb.u_nd_licensing_restrictions.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $VMName Licensing Restrictions Tag to " + $Cmdb.u_nd_licensing_restrictions.display_value)
Set-ITDVMwareVMTag -ComputerName $VMName -LicensingRestrictions $Cmdb.u_nd_licensing_restrictions.display_value
}
Else {
}
}
# startup priority TBD
# startup priority is not in Cmdb
# SRM Recovery Type
If ($Cmdb.u_srm_recovery_type.display_value) {
$TagAssignmentValue = ($OldTags | Where-Object { $_.Tag.Category.Name -eq 'SRM Recovery Type' }).Tag.Name
If ($Cmdb.u_srm_recovery_type.display_value -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $VMName SRM Recovery Type Tag to " + $Cmdb.u_srm_recovery_type.display_value)
Set-ITDVMwareVMTag -ComputerName $VMName -SRMRecoveryType $Cmdb.u_srm_recovery_type.display_value
}
Else {
}
}
#
# DR Protection
If ( ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO") ) { #-replace "VMware: " -replace "RPO", "VR RPO"
$TagAssignmentValue = ($OldTags | Where-Object {$_.Tag.Category.Name -eq 'DR Protection' }).Tag.Name
If ( ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO") -ne $TagAssignmentValue) {
Write-Verbose -Message ("Setting $VMName DR Protection Tag to " + ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: ") )
Set-ITDVMwareVMTag -ComputerName $VMName -DRProtection ($Cmdb.u_nd_dr_protection.display_value -replace "VMware: " -replace "RPO", "VR RPO")
}
Else {
}
}
}
end {
}
}
@@ -0,0 +1,250 @@
<#
.SYNOPSIS
Function to process a VMware change request
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Set-ITDVMwareVMViaSnowTask {
[CmdletBinding()]
param (
[string]
$SCTaskNum,
[switch]
$Override,
[switch]
$CloseTask
)
begin {
$FreePercentThreshold = 0.20 # 20% free space required before disk expansions are automated
}
process {
# get current user, SCTask, Ritm
$assignTo = Get-ITDServiceNowUser -Username $Env:USERNAME
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet
$RitmNum = $Ritm.number.value
# Get Hostname and CMDB object
[string]$SCTaskDescriptionHostname = $SCTask.description.display_value.split(' ')[-1]
$TaskCmdb = @()
Write-Verbose -Message ("Gathering VariableSet data from $RitmNum")
$MatchFound = $false
ForEach ($Row in $Ritm.VariableSet) {
$TempCi = Get-ITDServiceNowRecord -Table cmdb_ci -SysId ($Row.host_name_ref) -ErrorAction Stop
If ($SCTaskDescriptionHostname -eq $TempCi.name.display_value) {
$Ci = $TempCi
$MatchFound = $true
}
}
If ($MatchFound -eq $false) {
Write-Error -Message "ComputerName $ComputerName was not found in VariableSet for $RitmNum" -ErrorAction Stop
}
$FQDN = $Ci.fqdn.display_value
If ( @($Ci).count -gt 1 ) {
Write-Error -Message "More than one CMDB object found that matches the hostname in this task's description" -ErrorAction Stop
}
# update SCTask description and assignment for humans
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{assigned_to = $assignTo.name }
# search for VMware VM
try {
$VM = Get-VM -Name $Ci.fqdn.display_value | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
catch {
Write-Error "Error on VM lookup. Are you connected to vCenter?" -ErrorAction Stop
}
switch ( @($VM).count ) {
{ 0 -or $null } {
# no matches
Write-Error -Message "Zero VM matches found, ending script" -ErrorAction Stop
}
{ $_ -ne 1 } {
# more than one match
Write-Error -Message "Multiple VM matches found, ending script" -ErrorAction Stop
}
{ 1 } {
# exactly one match, gather request information, and populate variables
Write-Verbose -Message ("VM: " + $VM.Name)
[int]$CPU = ($Ritm.VariableSet | Where-Object { $_.host_name_ref -EQ $Ci.sys_id.value } ).Processors
[int]$MemoryGB = ($Ritm.VariableSet | Where-Object { $_.host_name_ref -EQ $Ci.sys_id.value } ).memory_gb
[int]$Disk1 = ($Ritm.VariableSet | Where-Object { $_.host_name_ref -EQ $Ci.sys_id.value } ).disk_1_os
[int]$Disk2 = ($Ritm.VariableSet | Where-Object { $_.host_name_ref -EQ $Ci.sys_id.value } ).disk_2_swap_disk
3..16 | ForEach-Object {
$DiskNum = $_
Write-Verbose "Populating variable Disk$DiskNum"
###Set-Variable -Name "Disk$DiskNum" -Value ([int](($Ritm.CustomVariable | Where-Object Name -Like "disk_$DiskNum*").Value))
Set-Variable -Name "Disk$DiskNum" -Value ([int]( ($Ritm.VariableSet | Where-Object { $_.host_name_ref -EQ $Ci.sys_id.value } )."disk_$DiskNum"))
}
# CPU modification
If ($CPU -ne 0 -and $CPU -ne $VM.NumCpu) {
Write-Verbose -Message ($VM.Name + " attempt changing CPU from " + $VM.NumCPU + " to " + $CPU)
try {
$OldCpu = $VM.NumCpu
$VM | Set-VM -NumCpu $CPU -Confirm:$false -ErrorAction Stop
$CommentsForWorkNotes += "CPU was updated from $OldCpu to $CPU. `n"
}
catch {
}
}
# MemoryGB modification
If ($MemoryGB -ne 0 -and $MemoryGB -ne $VM.MemoryGB) {
Write-Verbose -Message ($VM.Name + " attempt changing MemoryGB to " + $MemoryGB)
try {
$OldMemoryGB = $VM.MemoryGB
$VM | Set-VM -MemoryGB $MemoryGB -Confirm:$false -ErrorAction Stop
$CommentsForWorkNotes += "MemoryGB was updated from $OldMemoryGB to $MemoryGB. `n"
}
catch {
}
}
# Disk modification loop
$VMDisks = $VM | Get-HardDisk
1..16 | ForEach-Object {
Write-Verbose "Start Loop for Disk $_"
$HardDisk = $null
$DiskGBNewValue = $null
$DiskVarName = $null
$DiskNum = $_
$DiskGBNewValue = (Get-Variable -Name Disk$DiskNum).Value
switch ($DiskNum){
1 {
$DiskVarName = "Disk1"
}
2 {
$DiskVarName = "Disk2"
}
Default {
$DiskVarName = ("Disk" + $DiskNum)
}
}
If ( (Get-Variable -Name $DiskVarName).Value -ne 0 ) {
Write-Verbose -Message ("DiskNum: $DiskNum, DiskGBNewValue: $DiskGBNewValue")
$HardDisk = $VM | Get-HardDisk -Name "Hard disk $DiskNum" -ErrorAction SilentlyContinue
If ($HardDisk) {
$Datastore = $HardDisk | Get-Datastore
$DiskGBOldValue = $HardDisk.CapacityGB
$HardDiskIncreaseGB = $DiskGBNewValue - $DiskGBOldValue
If ($HardDiskIncreaseGB -ge 500) {
# manual intervention
}
$FreePercentBefore = ($Datastore.FreeSpaceGB) / $Datastore.CapacityGB
$FreePercentAfter = ($Datastore.FreeSpaceGB - $HardDiskIncreaseGB) / $Datastore.CapacityGB
Write-Verbose -Message ("Datastore " + $Datastore.Name + " free space will lower from " + [math]::round($FreePercentBefore, 4) + " to " + [math]::round($FreePercentAfter, 4) + "") -Verbose
Write-Verbose -Message ("Override is " + $Override)
If ( ($FreePercentAfter -gt $FreePercentThreshold) -or ($Override -eq $true)) {
try {
Write-Verbose -Message ("Hard disk $DiskNum : Increasing from " + $HardDisk.CapacityGB + "GB to " + $DiskGBNewValue + "GB") -Verbose
$VM | Get-HardDisk -Name "Hard disk $DiskNum" | Set-HardDisk -CapacityGB $DiskGBNewValue -Confirm:$false
$CommentsForWorkNotes += "Hard disk $DiskNum CapacityGB was modified from $DiskGBOldValue GB to $DiskGBNewValue GB. `n"
$DiskChanged = $true
}
catch {
Write-Error -Message "Disk $DiskNum expansion failed" -ErrorAction Stop
}
}
Else {
try {
Write-Error -Message ("Hard disk $DiskNum failed. " + $FreePercentThreshold * 100 + "% free space is required for automated disk expansions. " + $Datastore.Name + " would be " + [math]::round($FreePercentAfter, 4) + ".") -ErrorAction Stop
}
catch {
Write-Error -Message ("Hard disk $DiskNum failed. " + $FreePercentThreshold * 100 + "% free space is required for automated disk expansions. " + $Datastore.Name + " would be " + [math]::round($FreePercentAfter, 4) + ".") -ErrorAction Stop
}
}
}
Else {
Write-Verbose "Hard disk $DiskNum was not found. New disk will attempt to be created." -Verbose
# get licensing and storage format of existing disks
$VMTag = Get-TagAssignment -Entity $VM -Category LicensingRestrictions
If (@($VMDisks | Where-Object StorageFormat -Like "*Thick*").count -gt 0) {
$StorageFormat = 'EagerZeroedThick'
}
Else {
$StorageFormat = 'Thin'
}
# if not SQL, validate available space and create if possible. if VM is SQL, stop
If ($VMTag.Tag.Name -notlike "*SQL*") {
# place new disk with disk 1 and validate datastore free space
$Datastore = $VM | Get-HardDisk -Name "Hard disk 1" | Get-Datastore
$DiskGBOldValue = 0
$HardDiskIncreaseGB = $DiskGBNewValue - $DiskGBOldValue
If ($HardDiskIncreaseGB -ge 500) {
# manual intervention ?
}
$FreePercentBefore = ($Datastore.FreeSpaceGB) / $Datastore.CapacityGB
$FreePercentAfter = ($Datastore.FreeSpaceGB - $HardDiskIncreaseGB) / $Datastore.CapacityGB
#create the disk, with decided storageformat and persistent persistence on hard disk 1 datastore
If ($FreePercentAfter -gt $FreePercentThreshold) {
try {
Write-Warning -Message ("Hard disk $DiskNum : Creating new disk " + $DiskGBNewValue + " GB")
#Write-Warning -Message ("Datastore " + $Datastore.Name + " free space will lower from " + [math]::round($FreePercentBefore,4)*100 + "% to " + [math]::round($FreePercentAfter,4)*100 + "%")
Write-Warning -Message ("Datastore " + $Datastore.Name + " free space will lower from " + [math]::round($FreePercentBefore, 4) + " to " + [math]::round($FreePercentAfter, 4) + "")
$VM | New-HardDisk -CapacityGB $DiskGBNewValue -StorageFormat $StorageFormat
$CommentsForWorkNotes += "Hard disk $DiskNum was created with $DiskGBNewValue GB. "
$DiskChanged = $true
}
catch {
}
}
Else {
Write-Error -Message ("Hard disk $_ failed. " + $FreePercentThreshold * 100 + "% free space is required for automated disk expansions. " + $Datastore.Name + " would be " + [math]::round($FreePercentAfter, 4) + ".")
$DiskChanged = $false
$DiskError = $true
}
}
Else {
# require human review
Write-Error -Message ($HostName + " has SQL licensing, create the new disk manually due to SQL Server best practices. Once complete, rerun to validate size and close task.") -ErrorAction Stop
}
}
}
}
# update sctask and ritm, reassign if disk changed
$CommentsToAdd = "VMware VM " + $VM.Name + " was modified: `n" + $CommentsForWorkNotes
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{comments = $CommentsToAdd }
Update-ITDServiceNowRecord -ItemType 'Request Item' -Number $Ritm.number.value -Values @{comments = $CommentsToAdd }
If ($CloseTask) {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{close_notes = $CommentsToAdd; state = "Closed Complete" }
}
}
}
}
end {
}
}
@@ -0,0 +1,239 @@
function Sync-ITDVMwareVMMetadataToSharePoint {
[CmdletBinding()]
param (
[string[]]
$VMName,
[switch]
$SRMImplemented,
[switch]
$WhatIf
)
begin {
}
process {
# validate vcenter connection
# search for sharepoint record
# if multiple, error
# get VM (non-placeholder) information
# name, cpu, memoryGB, disks, cluster, datacenter
# compare, discover fields that are mismatched
# if SRMImplement -eq $true, set SP record to match that
# set sharepoint record to values pulled from vcenter
If ($global:DefaultVIServers) {
}
Else {
Write-Error -Message "Not connected to vCenter" -ErrorAction Stop
}
Write-Verbose -Message "Get SharePoint Cluster List"
$SharePointClusterList = Get-ITDSharePointVMClusterList
Write-Verbose -Message "Get SharePoint Guest List"
$SharePointVMList = Get-ITDSharePointVMGuestList
ForEach ($ComputerName in $VMName) {
Write-Verbose -Message "Start $ComputerName"
$RecordToUpdate = $SharePointVMList | Where-Object Title -EQ $ComputerName
$VM = Get-VM -Name $ComputerName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
switch (@($VM).count) {
{ $_ -le 0 } {
Write-Error -Message "No virtual machine found with name $ComputerName" -ErrorAction Stop
}
{ $_ -gt 1 } {
Write-Error -Message "More than one virtual machine found with name $ComputerName" -ErrorAction Stop
}
{ 1 } {
switch (@($RecordToUpdate).count) {
{ $_ -le 0 } {
Write-Error "SharePoint record with Title $ComputerName not found. Create the new record first." -ErrorAction Stop
}
{ $_ -gt 1 } {
Write-Error "More than one SharePoint record found with Title equal to $ComputerName" -ErrorAction Stop
}
{ 1 } {
# get virtual hard disks and load variables
$VMDisks = $VM | Get-HardDisk
$VMDisk1 = ($VMDisks | Where-Object Name -EQ "Hard Disk 1").CapacityGB
$VMDisk2 = ($VMDisks | Where-Object Name -EQ "Hard Disk 2").CapacityGB
$VMDisk3 = ($VMDisks | Where-Object Name -EQ "Hard Disk 3").CapacityGB
$VMDisk4 = ($VMDisks | Where-Object Name -EQ "Hard Disk 4").CapacityGB
$VMDisk5 = ($VMDisks | Where-Object Name -EQ "Hard Disk 5").CapacityGB
$VMDisk6 = ($VMDisks | Where-Object Name -EQ "Hard Disk 6").CapacityGB
$VMDisk7 = ($VMDisks | Where-Object Name -EQ "Hard Disk 7").CapacityGB
$VMDisk8 = ($VMDisks | Where-Object Name -EQ "Hard Disk 8").CapacityGB
$VMDisk9 = ($VMDisks | Where-Object Name -EQ "Hard Disk 9").CapacityGB
$VMDisk10 = ($VMDisks | Where-Object Name -EQ "Hard Disk 10").CapacityGB
$VMDisk11 = ($VMDisks | Where-Object Name -EQ "Hard Disk 11").CapacityGB
$VMDisk12 = ($VMDisks | Where-Object Name -EQ "Hard Disk 12").CapacityGB
$VMDisk13 = ($VMDisks | Where-Object Name -EQ "Hard Disk 13").CapacityGB
$VMDisk14 = ($VMDisks | Where-Object Name -EQ "Hard Disk 14").CapacityGB
$VMDisk15 = ($VMDisks | Where-Object Name -EQ "Hard Disk 15").CapacityGB
$VMDisk16 = ($VMDisks | Where-Object { $_.Name.split(' ')[2] -notmatch '\b([1-9]|1[0-5])\b' } | Measure-Object -Sum CapacityGB).Sum
If ($null -eq $VMDisk1 ) { $VMDisk1 = 0 }
If ($null -eq $VMDisk2 ) { $VMDisk2 = 0 }
If ($null -eq $VMDisk3 ) { $VMDisk3 = 0 }
If ($null -eq $VMDisk4 ) { $VMDisk4 = 0 }
If ($null -eq $VMDisk5 ) { $VMDisk5 = 0 }
If ($null -eq $VMDisk6 ) { $VMDisk6 = 0 }
If ($null -eq $VMDisk7 ) { $VMDisk7 = 0 }
If ($null -eq $VMDisk8 ) { $VMDisk8 = 0 }
If ($null -eq $VMDisk9 ) { $VMDisk9 = 0 }
If ($null -eq $VMDisk10) { $VMDisk10 = 0 }
If ($null -eq $VMDisk11) { $VMDisk11 = 0 }
If ($null -eq $VMDisk12) { $VMDisk12 = 0 }
If ($null -eq $VMDisk13) { $VMDisk13 = 0 }
If ($null -eq $VMDisk14) { $VMDisk14 = 0 }
If ($null -eq $VMDisk15) { $VMDisk15 = 0 }
If ($null -eq $VMDisk16) { $VMDisk16 = 0 }
# Get VMware Cluster
# what vcenter says, and what it should be
$vCenterCluster = $VM | Get-Cluster
$vCenterSharePointClusterItem = $SharePointClusterList | Where-Object Name -EQ $vCenterCluster.Name
# what sharepoint currently is
$SharePointClusterFieldId = $RecordToUpdate.ClusterId
$SharePointClusterFieldName = $SharePointClusterList | Where-Object Id -EQ $SharePointClusterFieldId
# Get VMware Datacenter
$Datacenter = $VM | Get-Datacenter
switch ($Datacenter.Name) {
'DCN Datacenter' { $DatacenterSharePointName = "DCN" }
'Fargo Datacenter' { $DatacenterSharePointName = "Fargo" }
'Grand Forks Vantis' { $DatacenterSharePointName = "Grand Forks" }
'Primary Datacenter' { $DatacenterSharePointName = "Bismarck" }
'Secondary Datacenter' { $DatacenterSharePointName = "Mandan" }
'VDI Datacenter' { $DatacenterSharePointName = "VDI" }
}
# one sharepoint record and one virtual machine, compare and set params
$SetITDVMwareSharePointVMRecordParams = @{
Title = $ComputerName;
}
[string]$SpecialInstructions = ([string](Get-Date) + " - synchronization from vCenter, the following was changed: ")
If ($VM.NumCPU -ne $RecordToUpdate.Processors) {
$SetITDVMwareSharePointVMRecordParams += @{CPU = $VM.NumCpu }
$SpecialInstructions += ("CPU adjusted from " + $RecordToUpdate.Processors + " to " + $VM.NumCpu + ". ")
}
If ($VM.MemoryGB -ne $RecordToUpdate.RAM) {
$SetITDVMwareSharePointVMRecordParams += @{MemoryGB = $VM.MemoryGB }
$SpecialInstructions += ("MemoryGB adjusted from " + $RecordToUpdate.RAM + " to " + $VM.MemoryGB + ". ")
}
If ($VMDisk1 -ne $RecordToUpdate.Disk_x0020_C_x003a_) {
$SetITDVMwareSharePointVMRecordParams += @{Disk1OS = $VMDisk1 }
$SpecialInstructions += ("Disk1GB adjusted from " + $RecordToUpdate.Disk_x0020_C_x003a_ + " to " + $VMDisk1 + ". ")
}
If ($VMDisk2 -ne $RecordToUpdate.Disk2_x002d_SwapDisk) {
$SetITDVMwareSharePointVMRecordParams += @{Disk2Swap = $VMDisk2 }
$SpecialInstructions += ("Disk2GB adjusted from " + $RecordToUpdate.Disk2_x002d_SwapDisk + " to " + $VMDisk2 + ". ")
}
If ($VMDisk3 -ne $RecordToUpdate.Disk_x0020_D_x003a_) {
$SetITDVMwareSharePointVMRecordParams += @{Disk3 = $VMDisk3 }
$SpecialInstructions += ("Disk3GB adjusted from " + $RecordToUpdate.Disk_x0020_D_x003a_ + " to " + $VMDisk3 + ". ")
}
If ($VMDisk4 -ne $RecordToUpdate.Disk_x0020__x002d__x0020_Other) {
$SetITDVMwareSharePointVMRecordParams += @{Disk4 = $VMDisk4 }
$SpecialInstructions += ("Disk4GB adjusted from " + $RecordToUpdate.Disk_x0020__x002d__x0020_Other + " to " + $VMDisk4 + ". ")
}
If ($VMDisk5 -ne $RecordToUpdate.Disk5) {
$SetITDVMwareSharePointVMRecordParams += @{Disk5 = $VMDisk5 }
$SpecialInstructions += ("Disk5GB adjusted from " + $RecordToUpdate.Disk5 + " to " + $VMDisk5 + ". ")
}
If ($VMDisk6 -ne $RecordToUpdate.Disk6) {
$SetITDVMwareSharePointVMRecordParams += @{Disk6 = $VMDisk6 }
$SpecialInstructions += ("Disk6GB adjusted from " + $RecordToUpdate.Disk6 + " to " + $VMDisk6 + ". ")
}
If ($VMDisk7 -ne $RecordToUpdate.Disk7) {
$SetITDVMwareSharePointVMRecordParams += @{Disk7 = $VMDisk7 }
$SpecialInstructions += ("Disk7GB adjusted from " + $RecordToUpdate.Disk7 + " to " + $VMDisk7 + ". ")
}
If ($VMDisk8 -ne $RecordToUpdate.Disk8) {
$SetITDVMwareSharePointVMRecordParams += @{Disk8 = $VMDisk8 }
$SpecialInstructions += ("Disk8GB adjusted from " + $RecordToUpdate.Disk8 + " to " + $VMDisk8 + ". ")
}
If ($VMDisk9 -ne $RecordToUpdate.Disk9) {
$SetITDVMwareSharePointVMRecordParams += @{Disk9 = $VMDisk9 }
$SpecialInstructions += ("Disk9GB adjusted from " + $RecordToUpdate.Disk9 + " to " + $VMDisk9 + ". ")
}
If ($VMDisk10 -ne $RecordToUpdate.Disk10) {
$SetITDVMwareSharePointVMRecordParams += @{Disk10 = $VMDisk10 }
$SpecialInstructions += ("Disk10GB adjusted from " + $RecordToUpdate.Disk10 + " to " + $VMDisk10 + ". ")
}
If ($VMDisk11 -ne $RecordToUpdate.Disk11) {
$SetITDVMwareSharePointVMRecordParams += @{Disk11 = $VMDisk11 }
$SpecialInstructions += ("Disk11GB adjusted from " + $RecordToUpdate.Disk11 + " to " + $VMDisk11 + ". ")
}
If ($VMDisk12 -ne $RecordToUpdate.Disk12) {
$SetITDVMwareSharePointVMRecordParams += @{Disk12 = $VMDisk12 }
$SpecialInstructions += ("Disk12GB adjusted from " + $RecordToUpdate.Disk12 + " to " + $VMDisk12 + ". ")
}
If ($VMDisk13 -ne $RecordToUpdate.Disk13) {
$SetITDVMwareSharePointVMRecordParams += @{Disk13 = $VMDisk13 }
$SpecialInstructions += ("Disk13GB adjusted from " + $RecordToUpdate.Disk13 + " to " + $VMDisk13 + ". ")
}
If ($VMDisk14 -ne $RecordToUpdate.Disk14) {
$SetITDVMwareSharePointVMRecordParams += @{Disk14 = $VMDisk14 }
$SpecialInstructions += ("Disk14GB adjusted from " + $RecordToUpdate.Disk14 + " to " + $VMDisk14 + ". ")
}
If ($VMDisk15 -ne $RecordToUpdate.Disk15) {
$SetITDVMwareSharePointVMRecordParams += @{Disk15 = $VMDisk15 }
$SpecialInstructions += ("Disk15GB adjusted from " + $RecordToUpdate.Disk15 + " to " + $VMDisk15 + ". ")
}
If ($VMDisk16 -ne $RecordToUpdate.Disk16) {
$SetITDVMwareSharePointVMRecordParams += @{Disk16 = $VMDisk16 }
$SpecialInstructions += ("Disk16GB adjusted from " + $RecordToUpdate.Disk16 + " to " + $VMDisk16 + ". ")
}
If ($vCenterCluster.Name -ne $SharePointClusterFieldName.Name) {
$SetITDVMwareSharePointVMRecordParams += @{ClusterId = $vCenterSharePointClusterItem.Id }
$SpecialInstructions += ("ClusterId adjusted from " + $RecordToUpdate.ClusterId + " to " + $vCenterSharePointClusterItem.Id + ". ")
$SpecialInstructions += ("Cluster adjusted to " + $vCenterSharePointClusterItem.Name + ". ")
}
If ($DatacenterSharePointName -ne $RecordToUpdate.Datacenter) {
$SetITDVMwareSharePointVMRecordParams += @{'Datacenter' = $DatacenterSharePointName }
$SpecialInstructions += ("Datacenter adjusted from " + $RecordToUpdate.Datacenter + " to " + $DatacenterSharePointName + ". ")
}
If($PSBoundParameters.ContainsKey('SRMImplemented')){
$SetITDVMwareSharePointVMRecordParams += @{SRM_Status = 'Implemented'}
$SpecialInstructions += ("SRM_Status set to Implemented. SRM_RecoveryVMtype set to Reserved. SRM_ConfiguredDate set to " + (Get-Date))
}
$SetITDVMwareSharePointVMRecordParams += @{SpecialInstructions = $SpecialInstructions }
If ($WhatIf) {
Write-Warning -Message ("The following fields in SharePoint record #" + $RecordToUpdate.ID + " for Title " + $RecordToUpdate.Title + " would be changed:")
$SetITDVMwareSharePointVMRecordParams
}
Else {
$SetITDVMwareSharePointVMRecordParams
Set-ITDVMwareSharePointVMRecord @SetITDVMwareSharePointVMRecordParams #-Verbose
}
}
}
}
}
}
}
end {
$postParams = [PSCustomObject]@{
AutomationName = "Infra-VMware";
Action = 'Change';
Units = 3;
Platform = 'ServiceNow-Overhead-SharePointDualEntry';
}
Invoke-RestMethod -Uri http://itdnettools.nd.gov/services/automation-tracking.py -Method POST -Body ($postParams | ConvertTo-Json) | Out-Null
}
}
@@ -0,0 +1,154 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Sync-ITDVMwareVMTagsFromCmdb {
[CmdletBinding()]
param (
)
begin {
}
process {
$GetITDServiceNowRecordParams = @{
#Filter = "model_idLIKEVMware"
Table = 'cmdb_ci_server';
IncludeTotalCount = $true;
Fields = @(
'name',
'fqdn',
'environment',
'u_nd_type',
'model_id',
'os',
'os_version',
'u_nd_application_svc',
'u_nd_licensing_restrictions',
'u_nd_dr_protection',
'u_srm_recovery_type'
)
}
Write-Verbose -Message 'Retrieve all CMDB CIs'
$AllCmdb = Get-ITDServiceNowRecord @GetITDServiceNowRecordParams
$AllCmdbValues = $AllCmdb | Select-Object @{n = 'Name'; e = { $_.Name.display_value } },
@{n = 'fqdn'; e = { $_.fqdn.display_value } },
@{n = 'DTAP'; e = { $_.environment.display_value } },
@{n = 'environment'; e = { $_.u_nd_type.display_value } },
@{n = 'type'; e = { $_.u_nd_type.display_value } },
@{n = 'model_id'; e = { $_.model_id.display_value } },
@{n = 'os'; e = { $_.os.display_value } },
@{n = 'os_version'; e = { $_.os_version.display_value } },
@{n = 'u_nd_application_svc'; e = { $_.u_nd_application_svc.display_value } },
@{n = 'u_nd_dr_protection'; e = { $_.u_nd_dr_protection.display_value } },
@{n = 'u_nd_licensing_restrictions'; e = { $_.u_nd_licensing_restrictions.display_value } },
@{n = 'u_srm_recovery_type'; e = { $_.u_srm_recovery_type.display_value } }
# DTAP from all unique options from the cmdb_ci_server table field name "Environment"
Write-Verbose -Message "Start Environment Tag sync"
$CmdbValues = ($AllCmdbValues | Select-Object -Unique DTAP | Select-Object -ExpandProperty DTAP)
$TagValues = (Get-Tag -Category DTAP -Server itdvmvc1.nd.gov).Name
$Compare = Compare-Object -ReferenceObject $CmdbValues -DifferenceObject $TagValues
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '<=')) {
Write-Verbose -Message ("Create DTAP tag for " + $c.InputObject)
New-Tag -Category DTAP_SNow -Name $c.InputObject -Server 'itdvmvc1.nd.gov'
}
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '=>')) {
Write-Verbose -Message ("Remove DTAP tag for " + $c.InputObject)
Get-Tag -Category DTAP_SNow -Name $c.InputObject -Server 'itdvmvc1.nd.gov' | Remove-Tag -Confirm:$false
}
$TagValues = $null
$Compare = $null
Write-Verbose -Message "End Environment Tag sync"
# AppName, get list from ServiceNow table cmdb_ci_service
Write-Verbose -Message "Start AppName Tag sync"
$AllAppNames = (Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -Filter "operational_status=1" -IncludeTotalCount -Fields name).name.display_value | Where-Object { $_ -like "*-*" }
$TagValues = (Get-Tag -Category AppName -Server itdvmvc1.nd.gov).Name
$Compare = Compare-Object -ReferenceObject $AllAppNames -DifferenceObject $TagValues
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '<=')) {
Write-Verbose -Message ("Create AppName tag for " + $c.InputObject)
New-Tag -Category AppName -Name $c.InputObject -Server 'itdvmvc1.nd.gov'
}
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '=>')) {
Write-Verbose -Message ("Remove AppName tag for " + $c.InputObject)
Get-Tag -Category AppName -Name $c.InputObject -Server 'itdvmvc1.nd.gov' | Remove-Tag -Confirm:$false
}
$TagValues = $null
$Compare = $null
Write-Verbose -Message "End AppName Tag sync"
# Licensing Restrictions
Write-Verbose -Message "Start Licensing Restrictions Tag sync"
$AllLicensingRestrictions = ($AllCmdbValues | Select-Object -Unique u_nd_licensing_restrictions | Select-Object -ExpandProperty u_nd_licensing_restrictions)
$TagValues = (Get-Tag -Category LicensingRestrictions -Server itdvmvc1.nd.gov).Name
$Compare = Compare-Object -ReferenceObject $AllLicensingRestrictions -DifferenceObject $TagValues
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '<=')) {
Write-Verbose -Message ("Create AppName tag for " + $c.InputObject)
New-Tag -Category LicensingRestrictions -Name $c.InputObject -Server 'itdvmvc1.nd.gov'
}
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '=>')) {
Write-Verbose -Message ("Remove AppName tag for " + $c.InputObject)
Get-Tag -Category LicensingRestrictions -Name $c.InputObject -Server 'itdvmvc1.nd.gov' | Remove-Tag -Confirm:$false
}
$TagValues = $null
$Compare = $null
# Startup Priority
# Startup Priority is not in CMDB
# DR_Protection
Write-Verbose -Message "Start DR Protection Tag sync"
$AllDRProtection = ($AllCmdbValues | Select-Object -Unique u_nd_dr_protection | Select-Object -ExpandProperty u_nd_dr_protection) -replace "VMware: " -replace "RPO", "VR RPO" | Sort-Object
$TagValues = (Get-Tag -Category "DR Protection" -Server itdvmvc1.nd.gov).Name
$Compare = Compare-Object -ReferenceObject $AllDRProtection -DifferenceObject $TagValues
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '<=')) {
Write-Verbose -Message ("Create DR Protection tag for " + $c.InputObject)
New-Tag -Category "DR Protection" -Name $c.InputObject -Server 'itdvmvc1.nd.gov'
}
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '=>')) {
Write-Verbose -Message ("Create Protection tag for " + $c.InputObject)
Get-Tag -Category "DR Protection" -Name $c.InputObject -Server 'itdvmvc1.nd.gov' | Remove-Tag -Confirm:$false
}
$TagValues = $null
$Compare = $null
Write-Verbose -Message "End DR Protection Tag sync"
# SRM Recovery Type
Write-Verbose -Message "Start SRM Recovery Type Tag sync"
$AllSRMRecoveryType = ($AllCmdbValues | Select-Object -Unique u_srm_recovery_type | Select-Object -ExpandProperty u_srm_recovery_type)
$TagValues = (Get-Tag -Category "SRM Recovery Type" -Server itdvmvc1.nd.gov).Name
$Compare = Compare-Object -ReferenceObject $AllSRMRecoveryType -DifferenceObject $TagValues | Where-Object InputObject -NE "Placeholder"
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '<=')) {
Write-Verbose -Message ("Create SRM Recovery Type tag for " + $c.InputObject)
New-Tag -Category LicensingRestrictions -Name $c.InputObject -Server 'itdvmvc1.nd.gov'
}
ForEach ($c in ($Compare | Where-Object SideIndicator -EQ '=>')) {
Write-Verbose -Message ("Remove SRM Recovery Type tag for " + $c.InputObject)
Get-Tag -Category LicensingRestrictions -Name $c.InputObject -Server 'itdvmvc1.nd.gov' | Remove-Tag -Confirm:$false
}
$TagValues = $null
$Compare = $null
Write-Verbose -Message "End SRM Recovery Type Tag sync"
}
end {
}
}
@@ -0,0 +1,56 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Update-ITDSNowVMTask {
[CmdletBinding()]
param (
[string]
$SCTaskNum,
[string]
$CommentsToAdd,
[switch]
$CloseTask
)
begin {
}
process {
# get current user, SCTask, Ritm
$assignTo = Get-ServiceNowRecord -Table 'User' -Filter @('email', '-eq', ($env:username + "@nd.gov"))
$SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
$RitmNum = $SCTask.request_item.display_value
$Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable
$Hostname = ($Ritm.CustomVariable | Where-Object Name -EQ 'server_name').Value
# update SCTask description and assignment for humans
Write-Warning "$SCTaskNum assigned to $env:username"
Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = "VMware VM modification for $HostName"; assigned_to = $assignTo.name }
If ($CommentsToAdd) {
Update-ServiceNowRecord -ID $SCTask.number -Values @{comments = $CommentsToAdd } # enter comments into SCTASK
Update-ServiceNowRecord -ID $RitmNum -Values @{comments = $CommentsToAdd } # enter comments into RITM
}
If ($CloseTask) {
Update-ServiceNowRecord -ID $SCTask.number -Values @{close_notes = $CommentsToAdd; state = "Closed Complete" }
}
}
end {
}
}
@@ -0,0 +1,169 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Update-ITDSNowVMTaskDescription {
[CmdletBinding()]
param (
)
begin {
}
process {
<# Server Builds
Write-Verbose -Message "Start Server Builds"
$Filter = @('assignment_group', '-like', 'NDIT-Server Build Automation'), '-and', @('short_description', '-eq', 'Automated Server Build Task for Windows Virtual Machine'), '-and', @('state', '-eq', '2')
$OpenTasks = Get-ServiceNowRecord -Table 'Catalog Task' -Filter $Filter | Sort-Object Number
ForEach ($OpenTask in $OpenTasks) {
# get SCTask, Ritm
$SCTaskNum = $OpenTask.number
$SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
$RitmNum = $SCTask.request_item.display_value
$Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable -WarningAction SilentlyContinue
$ComputerName = ($Ritm.CustomVariable | Where-Object Name -EQ host_name).Value
$OperatingSystem = ($Ritm.CustomVariable | Where-Object Name -EQ operating_system).Value
switch (($Ritm.CustomVariable | Where-Object Name -EQ target_platform).Value) {
'azure' { $target_platform = "Azure" }
'vmware' { $target_platform = "VMware" }
}
# update short description
$shortdescription = "$target_platform $OperatingSystem VM Build for $ComputerName"
If ( ($RITM.CustomVariable | Where-Object Name -EQ dr_protection).Value -ne 'No DR') {
$shortdescription += ", with SRM protection"
}
Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = $shortdescription; }
}
Write-Verbose -Message "End Server Builds"
#>
<# VM Modifications
Write-Verbose -Message "Start VM Modifications"
$Filter = @('assignment_group', '-like', 'NDIT-Server Build Automation'), '-and', @('short_description', '-eq', 'Upgrade/Code Deployment'), '-and', @('state', '-eq', '1')
$OpenTasks = Get-ServiceNowRecord -Table 'Catalog Task' -Filter $Filter | Sort-Object Number
ForEach ($OpenTask in $OpenTasks) {
Write-Verbose -Message "Start $OpenTask.number"
# get SCTask, Ritm
$SCTaskNum = $OpenTask.number
$SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
$RitmNum = $SCTask.request_item.display_value
$Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable
$ComputerName = ($Ritm.CustomVariable | Where-Object Name -EQ server_name).Value.tolower()
# update short description
$shortdescription = "VM Modification for $ComputerName"
Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = $shortdescription; }
Write-Verbose -Message "End $OpenTask.number"
}
Write-Verbose -Message "End VM Modifications"
#>
# VM removal / retire
Write-Verbose -Message "Start Remove Server description updates"
#$Filter = @('assignment_group', '-like', 'NDIT-Server Build Automation'), '-and', @('short_description', '-like', 'Retire Server'), '-and', @('state', '-eq', '1')
$Filter = "active=true^short_descriptionSTARTSWITHRemove Server: "
#$OpenTasks = Get-ServiceNowRecord -Table 'Catalog Task' -Filter $Filter | Sort-Object Number
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter -IncludeTotalCount | Sort-Object Number
$AllRitms = [System.Collections.ArrayList]@()
ForEach ($OpenTask in $OpenTasks) {
Write-Verbose -Message ("Start " + $OpenTask.number)
# get SCTask, Ritm
$SCTaskNum = $OpenTask.number.value
$SCTask = $OpenTask
If ($AllRitms | Where-Object sys_id -EQ $SCTask.request_item.value) {
$Ritm = $AllRitms | Where-Object sys_id -EQ $SCTask.request_item.display_value
}
Else {
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
$null = $AllRitms.Add($Ritm)
}
$short_description_hostname = $SCTask.short_description.display_value.split(' ')[2]
$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -Filter ("name=" + $short_description_hostname)
$HostName = $Ci.Name.display_value
$FQDN = $Ci.FQDN.display_value
# determine if vmware, azure, or physical
switch ($Ci.model_id.display_value) {
{ $_ -like "*VMware*" } { $hardware_platform = "VMware"; $hardware_type = 'Virtual Machine' }
{ $_ -like "*Microsoft Virtual Machine*" } { $hardware_platform = "Azure"; $hardware_type = 'Virtual Machine' }
{ $_ -like "*HP*" } { $hardware_platform = 'HPE'; $hardware_type = 'Physical' }
default { $hardware_platform = 'Unknown'; $hardware_type = 'Other' }
}
# determine if windows, rhel, or other
switch ($Ci.sys_class_name.display_value) {
'Linux Server' { $OS = 'Linux' }
'Windows Server' { $OS = 'Windows' }
'Default' { $OS = 'Other' }
}
$short_description_new = "$hardware_platform $OS Removal for "
If ($FQDN) {
$short_description_new += $FQDN
}
Else {
$short_description_new += $ComputerName
}
#Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = $shortdescription; }
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{short_description = $short_description_new}
Write-Verbose -Message ("End " + $OpenTask.number.display_value)
}
Write-Verbose -Message "End VM removal/retire"
<# Other Server Requests
Write-Verbose -Message "Start Other Server"
$Filter = @('assignment_group', '-like', 'NDIT-Server Build Automation'), '-and', @('short_description', '-eq', 'Other Server Request'), '-and', @('state', '-eq', '1')
$OpenTasks = Get-ServiceNowRecord -Table 'Catalog Task' -Filter $Filter | Sort-Object Number
ForEach ($OpenTask in $OpenTasks) {
Write-Verbose -Message "Start $OpenTask.number"
# get SCTask, Ritm
$SCTaskNum = $OpenTask.number
$SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
$RitmNum = $SCTask.request_item.display_value
$Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable
$ComputerName = ($Ritm.CustomVariable | Where-Object Name -EQ server_name).Value
$OperatingSystem = ($Ritm.CustomVariable | Where-Object Name -EQ operating_system).Value
# update short description
$shortdescription = "Other Server Request for $ComputerName"
Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = $shortdescription; }
Write-Verbose -Message "End $OpenTask.number"
}
Write-Verbose -Message "End Other Server"
#>
}
end {
<#
$postParams = [PSCustomObject]@{
AutomationName = "Infra-VMware";
Action = 'Change';
Units = 3;
Platform = 'ServiceNow-Overhead';
}
Invoke-RestMethod -Uri http://itdnettools.nd.gov/services/automation-tracking.py -Method POST -Body ($postParams | ConvertTo-Json)
#>
}
}