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,27 @@
##### Teams Used for entire vertical teams, not specific applications, systems, or products
New-PSUAccessControl -Role "Team-Windows" -Tag "Team-Windows_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "Team-Windows" -Tag "Team-Windows_Modify" -Type "View, Edit, Create, Delete, Execute"
New-PSUAccessControl -Role "Team-Network" -Tag "Team-Network_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "Team-Linux" -Tag "Team-Linux_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "Team-Tier2" -Tag "Team-Tier2_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "Team-Mgmt" -Tag "Team-Mgmt_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "Team-Mgmt" -Tag "Team-Mgmt_Modify" -Type "View, Edit, Create, Delete, Execute"
##### Apps (or specific AppNames)
<# New App Tag example
New-PSUAccessControl -Role "App-Infra-XXXXX" -Tag "Infra-XXXXX_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "App-Infra-XXXXX" -Tag "Infra-XXXXX_Modify" -Type "View, Edit, Create, Delete, Execute"
#>
New-PSUAccessControl -Role "App-Infra-VMware" -Tag "Infra-VMware_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "App-Infra-VMware" -Tag "Infra-VMware_Modify" -Type "View, Edit, Create, Delete, Execute"
New-PSUAccessControl -Role "App-ITD-WindowsServer" -Tag "ITD-WindowsServer_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "App-ITD-WindowsServer" -Tag "ITD-WindowsServer_Modify" -Type "View, Edit, Create, Delete, Execute"
New-PSUAccessControl -Role "App-Shared-PowerSchool" -Tag "Shared-PowerSchool_Execute" -Type "View, Execute"
New-PSUAccessControl -Role "App-Shared-PowerSchool" -Tag "Shared-PowerSchool_Modify" -Type "View, Edit, Create, Delete, Execute"
@@ -0,0 +1,14 @@
Set-PSUAuthenticationMethod -Type "Form" -ScriptBlock {
param(
[PSCredential]$Credential
)
#
# You can call whatever cmdlets you like to conduct authentication here.
# Just make sure to return the $Result with the Success property set to $true
#
New-PSUAuthenticationResult -ErrorMessage 'Bad username or password'
}
Set-PSUAuthenticationMethod -Type "Windows"
Set-PSUAuthenticationMethod -Type "Saml2" -Disabled
@@ -0,0 +1,87 @@
Set-PSUAuthenticationMethod -Type "Form" -ScriptBlock {
param(
[PSCredential]$Credential
)
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
# is this a UPN?
if ( $Credential.UserName.IndexOf('@') -gt -1 ) {
# juggle back and forth from SID to get NTAccount format
$NTAccountName = ([System.Security.Principal.NTAccount]$Credential.UserName).Translate([System.Security.Principal.SecurityIdentifier]).Translate([System.Security.Principal.NTAccount]).Value
} elseif ( $Credential.UserName.IndexOf('\') -gt -1 ) {
# already NTAccount format
$NTAccountName = $Credential.UserName
} else {
# someone didn't enter their domain...
$NTAccountName = "NDGOV\" + $Credential.GetNetworkCredential().UserName
}
# split domain and username
$DomainName, $UserName = $NTAccountName.Split('\',2)
# perform auth with AD
$PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext( 'Domain', $DomainName )
$Authenticated = $PrincipalContext.ValidateCredentials( $UserName, $Credential.GetNetworkCredential().Password, 'Negotiate, Sealing' )
if ( $Authenticated ) {
# discover the user principal, needed for the user DN
$UserPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($PrincipalContext, [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName, $NTAccountName )
# get the user's domain
#$UserDomainContext = [System.DirectoryServices.ActiveDirectory.DirectoryContext]::new( 'Domain', $DomainName, $Credential.UserName, $Credential.GetNetworkCredential().Password )
#$UserDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain( $UserDomainContext )
# get the computer's domain
#$ComputerDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
# hold all the user groups
[System.Collections.Generic.List[hashtable]]$Groups = @()
# get groups from user's domain
[adsisearcher]::new( $UserDomain.GetDirectoryEntry(), "(&(objectCategory=group)(objectClass=group)(member:1.2.840.113556.1.4.1941:=$($UserPrincipal.DistinguishedName)))", @('name') ).FindAll().ForEach({
$Groups.Add(@{
Type = 'Group'
Value = $_.Properties['name'][0]
Issuer = $UserDomain.Name
})
})
<#
# get groups from the computer's domain (if different)
if ( $UserDomain.Name -ne $ComputerDomain.Name ) {
# lookup the user's foreign security principal in the computer's domain
$ForeignSecurityPrincipal = [adsisearcher]::new( $ComputerDomain.GetDirectoryEntry(), "(&(objectCategory=foreignSecurityPrincipal)(objectClass=foreignSecurityPrincipal)(name=$($UserPrincipal.Sid)))", @('distinguishedName') ).FindOne().Properties['distinguishedName'][0]
# find all the group memberships
[adsisearcher]::new( $ComputerDomain.GetDirectoryEntry(), "(&(objectCategory=group)(objectClass=group)(member:1.2.840.113556.1.4.1941:=$ForeignSecurityPrincipal))", @('name') ).FindAll().ForEach({
$Groups.Add(@{
Type = 'Group'
Value = $_.Properties['name'][0]
Issuer = $ComputerDomain.Name
})
})
}
#>
New-PSUAuthenticationResult -Success -UserName $UserPrincipal.UserPrincipalName -Claims {
$Groups | ForEach-Object { New-PSUAuthorizationClaim @_ }
}
} else {
New-PSUAuthenticationResult -ErrorMessage 'Bad username or password :)'
}
}
@@ -0,0 +1,86 @@
Set-PSUAuthenticationMethod -Type "Form" -ScriptBlock {
param(
[PSCredential]$Credential
)
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
# is this a UPN?
if ( $Credential.UserName.IndexOf('@') -gt -1 ) {
# juggle back and forth from SID to get NTAccount format
$NTAccountName = ([System.Security.Principal.NTAccount]$Credential.UserName).Translate([System.Security.Principal.SecurityIdentifier]).Translate([System.Security.Principal.NTAccount]).Value
} elseif ( $Credential.UserName.IndexOf('\') -gt -1 ) {
# already NTAccount format
$NTAccountName = $Credential.UserName
} else {
# someone didn't enter their domain...
$NTAccountName = "NDGOV\" + $Credential.GetNetworkCredential().UserName
}
# split domain and username
$DomainName, $UserName = $NTAccountName.Split('\',2)
# perform auth with AD
$PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext( 'Domain', $DomainName )
$Authenticated = $PrincipalContext.ValidateCredentials( $UserName, $Credential.GetNetworkCredential().Password, 'Negotiate, Sealing' )
if ( $Authenticated ) {
# discover the user principal, needed for the user DN
$UserPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($PrincipalContext, [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName, $NTAccountName )
# get the user's domain
$UserDomainContext = [System.DirectoryServices.ActiveDirectory.DirectoryContext]::new( 'Domain', $DomainName, $Credential.UserName, $Credential.GetNetworkCredential().Password )
$UserDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain( $UserDomainContext )
# get the computer's domain
#$ComputerDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
# hold all the user groups
[System.Collections.Generic.List[hashtable]]$Groups = @()
# get groups from user's domain
#[adsisearcher]::new( $UserDomain.GetDirectoryEntry(), "(&(objectCategory=group)(objectClass=group)(member:1.2.840.113556.1.4.1941:=$($UserPrincipal.DistinguishedName)))", @('name') ).FindAll().ForEach({
[adsisearcher]::new( $UserDomain.GetDirectoryEntry(), "(&(objectCategory=group)(objectClass=group)(member:1.2.840.113556.1.4.1941:=$($UserPrincipal.DistinguishedName))(name=ITD-PSUniversal-*))", @('name') ).FindAll().ForEach({
$Groups.Add(@{
Type = 'Group'
Value = $_.Properties['name'][0]
Issuer = $UserDomain.Name
})
})
<#
# get groups from the computer's domain (if different)
if ( $UserDomain.Name -ne $ComputerDomain.Name ) {
# lookup the user's foreign security principal in the computer's domain
$ForeignSecurityPrincipal = [adsisearcher]::new( $ComputerDomain.GetDirectoryEntry(), "(&(objectCategory=foreignSecurityPrincipal)(objectClass=foreignSecurityPrincipal)(name=$($UserPrincipal.Sid)))", @('distinguishedName') ).FindOne().Properties['distinguishedName'][0]
# find all the group memberships
[adsisearcher]::new( $ComputerDomain.GetDirectoryEntry(), "(&(objectCategory=group)(objectClass=group)(member:1.2.840.113556.1.4.1941:=$ForeignSecurityPrincipal))", @('name') ).FindAll().ForEach({
$Groups.Add(@{
Type = 'Group'
Value = $_.Properties['name'][0]
Issuer = $ComputerDomain.Name
})
})
}
#>
New-PSUAuthenticationResult -Success -UserName $UserPrincipal.UserPrincipalName -Claims {
$Groups | ForEach-Object { New-PSUAuthorizationClaim @_ }
}
} else {
New-PSUAuthenticationResult -ErrorMessage 'Bad username or password :)'
}
}
@@ -0,0 +1,6 @@
New-PSUApp -Name "PSUVariableReview" -FilePath "dashboards\PSUVariableReview\PSUVariableReview.ps1" -BaseUrl "/PSUVariableReview" -Authenticated -AutoDeploy
New-PSUApp -Name "Infra-VMware_Snapshot" -FilePath "dashboards\Infra-VMware_Snapshot\Infra-VMware_Snapshot.ps1" -BaseUrl "/Infra-VMware_Snapshot" -Authenticated -AutoDeploy
New-PSUApp -Name "ServiceNowDumps" -FilePath "dashboards\ServiceNowDumps\ServiceNowDumps.ps1" -BaseUrl "/ServiceNowDumps" -Authenticated -AutoDeploy
New-PSUApp -Name "NewITDADServiceAccount" -FilePath "dashboards\NewITDADServiceAccount\NewITDADServiceAccount.ps1" -BaseUrl "/NewITDADServiceAccount" -Authenticated -AutoDeploy
New-PSUApp -Name "ITD-WindowsServer_FileManagement" -FilePath "dashboards\ITD-WindowsServer_FileManagement\ITD-WindowsServer_FileManagement.ps1" -BaseUrl "/ITD-WindowsServer_FileManagement" -Authenticated -AutoDeploy
New-PSUApp -Name "ServiceNow" -FilePath "dashboards\ServiceNow\ServiceNow.ps1" -BaseUrl "/ServiceNow" -Authenticated -AutoDeploy
@@ -0,0 +1,107 @@
New-PSUEndpoint -Url "/Get-ITDService" -Method @('GET') -Endpoint {
# Enter your script to process requests.
$GetServiceParams = @{}
If ($Name) {
#$GetServiceParams.Name = $Name
}
Else {
# Write-Error "Please add query string to Url" # moar notes
}
If ($ComputerName) {
$ComputerName = $ComputerName -split ','
}
Else {
$ComputerName = $env:COMPUTERNAME
}
$Services = Invoke-Command -ComputerName $ComputerName -ArgumentList $Name -ScriptBlock {
$GetServiceParams = @{
Name = $args[0]
}
Get-Service @GetServiceParams -ErrorAction SilentlyContinue
}
Write-Output ($Services | select pscomputername, name, displayname, status, servicetype, @{n = 'DependentServicesName'; e = { $_.servicesdependedon.name } })
}
New-PSUEndpoint -Url "/Get-ITDADUser" -Method @('GET') -Endpoint {
#If($Identity){
# Get-ADUser -Identity $Identity -Properties LockedOut,MemberOf
# }
Invoke-PSUScript -Script 'Get-ITDADUser_script.ps1' -Identity $Identity -Wait
} -Authentication -Role @('ITD-PSUniversal-API-Execute')
New-PSUEndpoint -Url "/Get-ITDADGroup" -Method @('GET') -Endpoint {
If ($Identity) {
Get-ADGroup -Identity $Identity
}
}
New-PSUEndpoint -Url "/Get-ITDADGroupMember" -Method @('GET') -Endpoint {
# test notes
If ($Identity) {
Get-ADGroupMember -Identity $Identity | select SamAccountName, Name, DistinguishedName
}
}
New-PSUEndpoint -Url "/New-ITDVMwareVMSnapshot" -Method @('POST') -Endpoint {
$User = ConvertFrom-Json $Body
#New-User $User
Write-Output $User
}
New-PSUEndpoint -Url "/zm" -Method @('GET') -Endpoint {
$env:username
Connect-ITDvCenter
Get-Datacenter
Disconnect-VIServer -Server * -Confirm:$false
}
New-PSUEndpoint -Url "/Get-ITDVMwareVM" -Method @('GET') -Endpoint {
# Enter your script to process requests.
Connect-ITDvCenter
$Names = $Name -split ','
$Result = [System.Collections.ArrayList]@()
$LoopOutput = ForEach ($n in $Names) {
$VM = Get-VM -Name $n
$VMDisks = $VM | Get-HardDisk
$obj = [PSCustomObject]@{
Name = $VM.Name;
PowerState = $VM.PowerState;
NumCpu = $VM.NumCpu;
MemoryGB = $VM.MemoryGB;
ProvisionedSpaceGB = ($VMDisks | Measure-Object -Sum CapacityGB).Sum
}
$null = $Result.Add($obj)
}
#>
Disconnect-VIServer -Server * -Confirm:$false | Out-Null
Write-Output $Result
}
New-PSUEndpoint -Url "/SyncVMwareVMtoSharePointAPI" -Method @('GET') -Endpoint {
# Enter your script to process requests.
Connect-ITDvCenter
If ($Name) {
$VM = Get-VM -Name $Name
$VMDisks = $VM | Get-HardDisk
$obj = [PSCustomObject]@{
Name = $VM.Name;
PowerState = $VM.PowerState;
NumCpu = $VM.NumCpu;
MemoryGB = $VM.MemoryGB;
ProvisionedSpaceGB = ($VMDisks | Measure-Object -Sum CapacityGB).Sum
}
Write-Output "VMware:"
Write-Output $obj
Sync-ITDVMwareVMMetadataToSharePoint -ComputerName $Name
}
#>
Disconnect-VIServer -Server * -Confirm:$false | Out-Null
}
@@ -0,0 +1,5 @@
New-PSUEnvironment -Name "7.2.19" -Version "7.2.19" -Path "C:\Program Files\PowerShell\7\pwsh.exe" -Variables @('*') -Description "PowerShell environment for version 7.2.19. This was automatically detected on the server."
New-PSUEnvironment -Name "Windows PowerShell 5.1" -Version "5.1.20348.2582" -Path "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Variables @('*') -Description "PowerShell environment for version 5.1.20348.2582. This was automatically detected on the server."
New-PSUEnvironment -Name "Integrated" -Version "7.3.7" -Path "Universal.Server" -Variables @('*') -Description "An environment for running scripts directly in the PowerShell Universal server."
New-PSUEnvironment -Name "Agent" -Version "7.3.7" -Path "Universal.Agent" -Variables @('*') -Description "An environment for running scripts in an external PowerShell Universal agent process."
New-PSUEnvironment -Name "PowerShell 7" -Version "7.2.19" -Path "pwsh" -Variables @('*') -Description "The current version of PowerShell 7."
@@ -0,0 +1,15 @@
$Parameters = @{
Image = "/PSUniversal_Extras/logo.png"
Title = "PowerShell Universal"
Links = @(
New-PSULoginPageLink -Text 'ServiceNow' -Url 'https://northdakota.service-now.com/'
New-PSULoginPageLink -Text 'VMware vCenter' -Url 'https://itdvmvc1.nd.gov/ui'
New-PSULoginPageLink -Text 'Microsoft Azure' -Url 'https://portal.azure.com'
New-PSULoginPageLink -Text 'Passwordstate' -Url 'https://itdpv.nd.gov'
New-PSULoginPageLink -Text 'Solarwinds' -Url 'https://solarwinds.nd.gov/'
New-PSULoginPageLink -Text 'Panorama' -Url 'https://panorama-gov.nd.gov/php/login.php'
New-PSULoginPageLink -Text 'Ansible' -Url 'https://ansible.nd.gov/#/login'
New-PSULoginPageLink -Text 'Confluence Wiki' -Url 'https://wiki.nd.gov/i/dashboard.action'
)
}
New-PSULoginPage @Parameters
@@ -0,0 +1 @@
New-PSUPublishedFolder -RequestPath "/PSUniversal_Extras" -Path "E:\PSUniversal_Extras" -Name "PSUniversal_Extras"
@@ -0,0 +1,160 @@
New-PSURole -Name "Administrator" -Description "Administrators can manage settings, create and edit any entity and view all the entities with PowerShell Universal." -Policy {
param(
[Security.ClaimsPrincipal]$User
)
<#
Policies should return $true or $false to determine whether the user has the particular
claim that require them for that role.
#>
#$false
<#
$UserName = ($User.Identity.Name)
$UserName = $UserName.Substring($UserName.IndexOf('\') + 1, ($UserName.Length - ($UserName.IndexOf('\') + 1)))
$IsMember = $false;
# Perform LDAP Group Member Lookup
$Searcher = New-Object DirectoryServices.DirectorySearcher
$Searcher.SearchRoot = 'LDAP://OU=USERS, OU=ITD, DC=nd, DC=gov' # INSERT ROOT LDAP HERE
$Searcher.Filter = "(&(objectCategory=person)(memberOf=CN=ITD-PSUniversal-Admin,OU=ITDGROUPS,OU=GROUPS,OU=ITD,DC=nd,DC=gov))" #GROUP INSERT DN TO CHECK HERE
$Users = $Searcher.FindAll()
$Users | ForEach-Object {
If ($_.Properties.samaccountname -eq $UserName) {
$IsMember = $true;
"$UserName is a member of admin group!" | Out-File "C:\test\adgroup.txt"
}
else {
"$UserName is NOT member of admin group!" | Out-File "C:\test\adgroup.txt"
}
}
return $IsMember
#>
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains 'ITD-PSUniversal-Admin'
}
New-PSURole -Name "Operator" -Description "Operators have access to manage and execute scripts, create other entities within PowerShell Universal but cannot manage PowerShell Universal itself." -Policy {
param(
[Security.ClaimsPrincipal]$User
)
<#
Policies should return $true or $false to determine whether the user has the particular
claim that require them for that role.
#>
$false
}
New-PSURole -Name "Reader" -Description "Readers have read-only access to PowerShell Universal. They cannot make changes to any entity within the system." -Policy {
param(
[Security.ClaimsPrincipal]
$User
)
<#
Policies should return $true or $false to determine whether the user has the particular
claim that require them for that role.
#>
$User | ConvertTo-Json | Set-Content ("C:\temp\user-" + $User.Identity.Name + ".json")
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -match "ITD-PSUniversal-*"
}
New-PSURole -Name "Execute" -Description "Execute scripts within PowerShell Universal." -Policy {
param(
[Security.ClaimsPrincipal]$User
)
<#
Policies should return $true or $false to determine whether the user has the particular
claim that require them for that role.
#>
$false
}
New-PSURole -Name "User" -Description "Does not have access to the admin console but can be assigned resources like APIs, scripts, dashboards and pages." -Policy {
param(
[Security.ClaimsPrincipal]$User
)
<#
Policies should return $true or $false to determine whether the user has the particular
claim that require them for that role.
#>
$false
}
###### Team-TeamName nd.gov Active Directory groups
New-PSURole -Name "Team-Windows" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-Team-Windows"
}
New-PSURole -Name "Team-Linux" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-Team-Linux"
}
New-PSURole -Name "Team-ConnectND" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-Team-ConnectND"
}
New-PSURole -Name "Team-Network" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-Team-Network"
}
New-PSURole -Name "Team-Tier2" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-Team-Tier2"
}
New-PSURole -Name "Team-Mgmt" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-Team-Mgmt"
}
###### ITD App-AppName nd.gov Active Directory Groups
<# New Role for Apps example
New-PSURole -Name "App-Infra-XXXXX" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-App-Infra-XXXXX"
}
#>
New-PSURole -Name "App-Infra-VMware" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-App-Infra-VMware"
}
New-PSURole -Name "App-ITD-WindowsServer" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-App-ITD-WindowsServer"
}
New-PSURole -Name "App-Shared-Powerschool" -Policy {
param($User)
$Roles = $User.Claims | Where-Object Type -eq Group | Select-Object -ExpandProperty Value
$Roles -contains "ITD-PSUniversal-App-Shared-PowerSchool"
}
@@ -0,0 +1,13 @@
New-PSUSchedule -Cron "0 13 * * 1-5" -Script "Infra-VMware.VirtualMachine\Move-ITDVMwareVMToAppNameFolder_Auto.ps1" -TimeZone "America/Chicago" -Parameters @{
NewBuilds = $true
} -Name "Move-ITDVMwareVMToAppNameFolder_Auto"
New-PSUSchedule -Cron "7/30 8-16 * * *" -Script "ITD-WindowsServer.Lifecycle\New-ITDWindowsVm_Auto.ps1" -TimeZone "America/Chicago" -Name "New-ITDWindowsVm_Auto" -Paused
New-PSUSchedule -Cron "0 * * * *" -Script "Infra-VMware.Snapshot\Remove-ITDVMwareVMSnapshotExpired.ps1" -TimeZone "America/Chicago" -Name "Remove-ITDVMwareVMSnapshotExpired" -Paused -RandomDelay
New-PSUSchedule -Cron "27 8-16/2 * * 1-5" -Script "ITD-WindowsServer.General\Remove-ITDWindowsServer.ps1" -TimeZone "America/Chicago" -Name "Remove-ITDWindowsServer" -Paused -RandomDelay -RandomDelayMaximum 300
New-PSUSchedule -Cron "33 8-16/2 * * *" -Script "Infra-VMware.VirtualMachine\Set-ITDVMwareVMTagFromCmdb.ps1" -TimeZone "America/Chicago" -Name "Set-ITDVMwareVMTagFromCmdb_NewBuilds" -Paused
New-PSUSchedule -Cron "0 */1 * * *" -Script "Infra-VMware.VirtualMachine\Sync-ITDServerBuildRITMs.ps1" -TimeZone "America/Chicago" -Name "Sync-ITDServerBuildRITMs.ps1" -Paused -RandomDelay -RandomDelayMaximum 600
New-PSUSchedule -Cron "23 8-16/2 * * *" -Script "Infra-VMware.VirtualMachine\Sync-ITDVMwareVMTagsFromCmdb.ps1" -TimeZone "America/Chicago" -Name "Sync-ITDVMwareVMTagsFromCmdb" -Paused
New-PSUSchedule -Cron "13 8-17 * * *" -Script "Infra-Servers-PowerShellUniversal\Update-ITDModule.ps1" -TimeZone "America/Chicago" -Name "Update-ITDModule.ps1" -Paused -RandomDelay -RandomDelayMaximum 600
New-PSUSchedule -Cron "*/20 * * * *" -Script "Infra-VMware.VirtualMachine\Update-ITDSnowVMTaskDescription.ps1" -TimeZone "America/Chicago" -Name "Update-ITDSnowVMTaskDescription" -Paused -RandomDelay
New-PSUSchedule -Cron "*/20 * * * *" -Script "Infra-VMware.Snapshot\Update-ITDVMwareVMSnapshotStatus.ps1" -TimeZone "America/Chicago" -Name "Update-ITDVMwareVMSnapshotStatus" -Paused -RandomDelay
New-PSUSchedule -Cron "* * * * *" -Script "ZM-Test\Test-ITDSchedule.ps1" -TimeZone "America/Chicago" -Credential "ndgov_svcitdvmvcauto" -Environment "Agent" -Name "ZM-Test\Test-ITDSchedule" -Paused
@@ -0,0 +1,39 @@
New-PSUScript -Name "Add-ITDADUserSPN.ps1" -Description "Add-ITDADUserSPN.ps1" -Tag @('ITD-WindowsServer_Modify','Team-Windows_Execute') -Path "Infra-ActiveDirectory.Object\Add-ITDADUserSPN.ps1" -Environment "Agent" -ErrorAction "Stop" -Credential "ndgov_svcitdpsuad"
New-PSUScript -Name "Add-ITDServerBuildRitmToSql.ps1" -Description "Add-ITDServerBuildRitmToSql.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.VirtualMachine\Add-ITDServerBuildRitmToSql.ps1" -Environment "Agent"
New-PSUScript -Name "Add-ITDSolarwindsNode.ps1" -Description "Add-ITDSolarwindsNode.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "Infra-Monitoring-Solarwinds\Add-ITDSolarwindsNode.ps1" -Environment "PowerShell 7" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "Approve-ITDWindowsServer.ps1" -Description "Approve-ITDWindowsServer.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.General\Approve-ITDWindowsServer.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "Get-HelloWorld.ps1" -Description "Get-HelloWorld.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ZM-Test\Get-HelloWorld.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "Get-ITDExpiredFiles.ps1" -Description "Get-ITDExpiredFiles.ps1" -Tag @('ITD-WindowsServer_Modify','Team-Windows_Execute') -Path "ITD-WindowsServer.FileManagement\Get-ITDExpiredFiles.ps1" -Environment "PowerShell 7" -ErrorAction "Stop" -Credential "ndgov_svcitdpsuwin"
New-PSUScript -Name "Get-ITDVMwareLunIdNextAvailable.ps1" -Description "Get-ITDVMwareLunIdNextAvailable.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.Administration\Get-ITDVMwareLunIdNextAvailable.ps1"
New-PSUScript -Name "Get-ITDVMwareVMGuestIPsForPA.ps1" -Description "Get-ITDVMwareVMGuestIPsForPA.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.Administration\Get-ITDVMwareVMGuestIPsForPA.ps1"
New-PSUScript -Name "Move-ITDVMwareVMToAppNameFolder_Auto.ps1" -Description "Move-ITDVMwareVMToAppNameFolder_Auto.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.VirtualMachine\Move-ITDVMwareVMToAppNameFolder_Auto.ps1" -Environment "Agent" -Credential "ndgov_svcitdvmvcauto"
New-PSUScript -Name "New-ITDADServiceAccount.ps1" -Description "New-ITDADServiceAccount.ps1" -Tag @('ITD-WindowsServer_Modify','Team-Windows_Execute') -Path "Infra-ActiveDirectory.Object\New-ITDADServiceAccount.ps1" -Environment "Agent" -ErrorAction "Stop" -Credential "ndgov_svcitdpsuad"
New-PSUScript -Name "New-ITDPSUScript.ps1" -Description "New-ITDPSUScript.ps1" -Tag @('ITD-WindowsServer_Modify','Team-Windows_Execute') -Path "Infra-Servers-PowerShellUniversal\New-ITDPSUScript.ps1" -Environment "Integrated"
New-PSUScript -Name "New-ITDVMwareSharePointVMRecordFromRITM.ps1" -Description "New-ITDVMwareSharePointVMRecordFromRITM.ps1 [[-Fqdn] <string>] [[-RitmNum] <string>]" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.VirtualMachine\New-ITDVMwareSharePointVMRecordFromRITM.ps1" -Environment "PowerShell 7" -Credential "ndgov_svcitdiaassprw"
New-PSUScript -Name "New-ITDVMwareVMSnapshotTask.ps1" -Description "New-ITDVMwareVMSnapshotTask.ps1" -Tag @('Infra-VMware_Modify','Team-Linux_Execute','Team-Network_Execute','Team-Tier2_Execute','Team-Windows_Execute') -Path "Infra-VMware.Snapshot\New-ITDVMwareVMSnapshotTask.ps1" -Environment "PowerShell 7" -Credential "ndgov_svcitdvmsnapmgr" -Role @('Team-Windows')
New-PSUScript -Name "New-ITDWindowsVm_Auto.ps1" -Description "New-ITDWindowsVm_Auto.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.Lifecycle\New-ITDWindowsVm_Auto.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-ITDWindowsVm_Step3.ps1" -Description "New-ITDWindowsVm_Step3.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.Lifecycle\New-ITDWindowsVm_Step3.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-ITDWindowsVmAzure_Manual.ps1" -Description "New-ITDWindowsVmAzure_Manual.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.General\New-ITDWindowsVmAzure_Manual.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-ITDWindowsVmAzure_Step1.ps1" -Description "New-ITDWindowsVmAzure_Step1.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.Lifecycle\New-ITDWindowsVmAzure_Step1.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-ITDWindowsVmAzure_Step2.ps1" -Description "New-ITDWindowsVmAzure_Step2.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.Lifecycle\New-ITDWindowsVmAzure_Step2.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-ITDWindowsVmVMware_Manual.ps1" -Description "New-ITDWindowsVmVMware_Manual.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.General\New-ITDWindowsVmVMware_Manual.ps1" -Environment "Agent" -DisableManualInvocation -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-ITDWindowsVmVMware_Step1.ps1" -Description "New-ITDWindowsVmVMware_Step1.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.Lifecycle\New-ITDWindowsVmVMware_Step1.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-ITDWindowsVmVMware_Step2.ps1" -Description "New-ITDWindowsVmVMware_Step2.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.Lifecycle\New-ITDWindowsVmVMware_Step2.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "New-TestNestedInvoke.ps1" -Description "New-TestNestedInvoke.ps1" -Tag @('Team-Windows_Modify') -Path "ZM-Test\New-TestNestedInvoke.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "Remove-ITDExpiredFiles.ps1" -Description "Remove-ITDExpiredFiles.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.FileManagement\Remove-ITDExpiredFiles.ps1" -Environment "PowerShell 7" -ErrorAction "Stop" -Credential "ndgov_svcitdpsuwin"
New-PSUScript -Name "Remove-ITDSolarwindsNode.ps1" -Description "Remove-ITDSolarwindsNode.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "Infra-Monitoring-Solarwinds\Remove-ITDSolarwindsNode.ps1" -Environment "PowerShell 7" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "Remove-ITDVMwareVMSnapshotExpired.ps1" -Description "Remove-ITDVMwareVMSnapshotExpired.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.Snapshot\Remove-ITDVMwareVMSnapshotExpired.ps1" -Environment "PowerShell 7" -Credential "ndgov_svcitdvmsnapmgr"
New-PSUScript -Name "Remove-ITDWindowsServer.ps1" -Description "Remove-ITDWindowsServer.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "ITD-WindowsServer.General\Remove-ITDWindowsServer.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "Set-ITDVMwareVMTagFromCmdb.ps1" -Description "Set-ITDVMwareVMTagFromCmdb.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.VirtualMachine\Set-ITDVMwareVMTagFromCmdb.ps1" -Environment "Agent" -Credential "ndgov_svcitdvmvcauto"
New-PSUScript -Name "Sync-ITDServerBuildRITMs.ps1" -Description "Sync-ITDServerBuildRITMs.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.VirtualMachine\Sync-ITDServerBuildRITMs.ps1" -Environment "Agent"
New-PSUScript -Name "Sync-ITDVMwareVMMetadataToSharePoint.ps1" -Description "Sync-ITDVMwareVMMetadataToSharePoint.ps1" -Tag @('Infra-VMware_Modify','Team-Mgmt_Execute') -Path "Infra-VMware.VirtualMachine\Sync-ITDVMwareVMMetadataToSharePoint.ps1" -Environment "Agent" -Credential "ndgov_svcitdiaassprw"
New-PSUScript -Name "Sync-ITDVMwareVMTagsFromCmdb.ps1" -Description "Sync-ITDVMwareVMTagsFromCmdb.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.VirtualMachine\Sync-ITDVMwareVMTagsFromCmdb.ps1" -Environment "Agent" -Credential "ndgov_svcitdvmvcauto"
New-PSUScript -Name "Sync-ITDVMwareVMToSql.ps1" -Description "Sync-ITDVMwareVMToSql.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.Administration\Sync-ITDVMwareVMToSql.ps1" -Environment "PowerShell 7" -Credential "ndgov_itdvcenterscript"
New-PSUScript -Name "Test-InvokeZM.ps1" -Description "Test-InvokeZM.ps1" -Path "ZM-Test\Test-InvokeZM.ps1"
New-PSUScript -Name "Test-ITDSchedule.ps1" -Description "Test-ITDSchedule.ps1" -Tag @('Infra-VMware_Modify') -Path "ZM-Test\Test-ITDSchedule.ps1"
New-PSUScript -Name "Test-PSUVariable.ps1" -Description "Test-PSUVariable.ps1" -Tag @('Infra-VMware_Execute') -Path "ZM-Test\Test-PSUVariable.ps1"
New-PSUScript -Name "test-sql.ps1" -Description "test-sql.ps1" -Path "ZM-Test\test-sql.ps1"
New-PSUScript -Name "Update-ITDModule.ps1" -Description "Update-ITDModule.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-Servers-PowerShellUniversal\Update-ITDModule.ps1" -Environment "7.2.24"
New-PSUScript -Name "Update-ITDSnowVMTaskDescription.ps1" -Description "Update-ITDSnowVMTaskDescription.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.VirtualMachine\Update-ITDSnowVMTaskDescription.ps1" -Environment "Agent" -ErrorAction "Stop"
New-PSUScript -Name "Update-ITDSolarwindsNodeFromSNowRitm.ps1" -Description "Update-ITDSolarwindsNodeFromSNowRitm.ps1" -Tag @('ITD-WindowsServer_Modify') -Path "Infra-Monitoring-Solarwinds\Update-ITDSolarwindsNodeFromSNowRitm.ps1" -Environment "PowerShell 7" -Credential "ndgov_svcitdiaasauto"
New-PSUScript -Name "Update-ITDVMwareVMSnapshotStatus.ps1" -Description "Update-ITDVMwareVMSnapshotStatus.ps1" -Tag @('Infra-VMware_Modify') -Path "Infra-VMware.Snapshot\Update-ITDVMwareVMSnapshotStatus.ps1" -Environment "PowerShell 7" -Credential "ndgov_svcitdvmsnapmgr"
@@ -0,0 +1,6 @@
$Parameters = @{
LogLevel = "Error"
HideRunAs = $true
HideRunOn = $true
}
Set-PSUSetting @Parameters
@@ -0,0 +1,16 @@
New-PSUTag -Name "Infra-VMware_Execute" -Color "#d4380d"
New-PSUTag -Name "Team-Windows_Execute" -Color "#391085"
New-PSUTag -Name "Team-Network_Execute" -Color "#c41d7f"
New-PSUTag -Name "Infra-VMware_Modify" -Color "#fa541c"
New-PSUTag -Name "Team-Windows_Modify" -Color "#722ed1"
New-PSUTag -Name "Team-Network_Modify" -Color "#f759ab"
New-PSUTag -Name "Team-Linux_Execute" -Color "#096dd9"
New-PSUTag -Name "Team-Linux_Modify" -Color "#40a9ff"
New-PSUTag -Name "Team-Tier2_Execute" -Color "#389e0d"
New-PSUTag -Name "Team-Tier2_Modify" -Color "#7cb305"
New-PSUTag -Name "Shared-PowerSchool_Execute"
New-PSUTag -Name "Shared-PowerSchool_Modify"
New-PSUTag -Name "ITD-WindowsServer_Execute" -Color "#874d00"
New-PSUTag -Name "ITD-WindowsServer_Modify" -Color "#d48806"
New-PSUTag -Name "Team-Mgmt_Execute" -Color "#780650"
New-PSUTag -Name "Team-Mgmt_Modify" -Color "#c41d7f"
@@ -0,0 +1,12 @@
New-PSUVariable -Name "sql_itdpsu1" -Vault "Database" -Type "PSCredential"
New-PSUVariable -Name "ndgov_svcitdvmsnapmgr" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-VMware"
New-PSUVariable -Name "ndgov_svcitdvmvcauto" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-VMware" -Role @('App-Infra-VMware')
New-PSUVariable -Name "ndgov_svcitdpsuad" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-WindowsServer" -Role @('Team-Windows','Team-Tier2')
New-PSUVariable -Name "snow_vmcred" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-VMware"
New-PSUVariable -Name "ndgov_svcitdiaasauto" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-WindowsServer" -Role @('App-ITD-WindowsServer','Administrator')
New-PSUVariable -Name "ndgov_itdsccmsrvcpia" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-WindowsServer" -Role @('App-ITD-WindowsServer')
New-PSUVariable -Name "ndgov_svcitdpsuwin" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-WindowsServer" -Role @('App-ITD-WindowsServer')
New-PSUVariable -Name "ndgov_svcitdvmvcro" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-VMware"
New-PSUVariable -Name "ndgov_svcitdiaassprw" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-VMware"
New-PSUVariable -Name "ndgov_itdvcenterscript" -Vault "Database" -Type "PSCredential" -Description "Owner: Infra-VMware" -Role @('App-Infra-VMware')
New-PSUVariable -Name "azure_iaasserviceprincipal" -Vault "Database" -Type "System.String" -Description "Owner: App-ITD-WindowsServer" -Role @('App-ITD-WindowsServer')
@@ -0,0 +1,21 @@
[CmdletBinding()]
param (
[string]
$AppName
)
begin {
}
process {
switch ($AppName) {
'Infra-VMware' {
return
}
}
}
end {
}
@@ -0,0 +1,26 @@
Param(
[string]
$Name,
[ValidateSet(
'Infra-ActiveDirectory.Object',
'Infra-VMware.Snapshot',
'ITD-WindowsServer.General',
'Shared-Powerschool'
)]
[string]
$Path
)
switch ($Path){
<# example switch condition and actions
{ $_ -like "App-XXXXX"} {$TagNamesEnforced = @('Shared-XXXXX_Modify)}
#>
{ $_ -eq "Infra-ActiveDirectory.Object" } { $TagNamesEnforced = @('ITD-WindowsServer_Modify') }
{ $_ -like "Infra-VMware*" } { $TagNamesEnforced = @('Infra-VMware_Modify') }
{ $_ -like "ITD-WindowsServer*" } { $TagNamesEnforced = @('ITD-WindowsServer_Modify') }
{ $_ -like "Shared-PowerSchool*" } { $TagNamesEnforced = @('Shared-PowerSchool_Modify') }
}
New-PSUScript -Name $Name -Path "$Path\$Name" -Tag @($TagNamesEnforced) -ScriptBlock {#code goes here
}
@@ -0,0 +1,15 @@
Param (
[string]
$Name,
[Parameter(ParameterSetName="PSCredential")]
[ValidateSet("Secret","Simple")]
[string]
$Type,
[string[]]
$Role
)
New-PSUVariable -Name $Name -Type $Type -Database -Role $Role
@@ -0,0 +1,3 @@
# It all starts with a single line of powershell code.
Write-Verbose ($Secret:svcitdiaasauto_test.username) -Verbose
Get-ADUser -Identity svcitddomainjoin | Set-ADUser -Description (Get-Date) -Credential $Secret:svcitdiaasauto_test
@@ -0,0 +1,42 @@
[CmdletBinding()]
Param(
[string]$ScriptName
)
$AllPSUScripts = Get-PSUScript
If ($ScriptName){
$AllPSUScripts = $AllPSUScripts | Where-Object Name -eq $ScriptName
}
$Folders = $AllPSUScripts | Group-Object Folder
ForEach ($Folder in $Folders) {
Write-Verbose -Message ("Start folder " + $Folder.Name) -Verbose
$ScriptsInFolder = $null
$TagNamesEnforced = $null
$TagNamesExisting = $null
$TagNamesToAssign = $null
switch ($Folder.Name) {
{ $_ -like "Infra-VMware*" } { $TagNamesEnforced = 'VMware-Admin_Modify' }
Default { Write-Verbose -Message ("Folder " + $Folder.Name + " does not have enforced tags")}
}
If ($TagNamesEnforced) {
$ScriptsInFolder = $AllPSUScripts | Where-Object Folder -EQ $Folder.Name
ForEach ($PSUScript in $ScriptsInFolder) {
$TagNamesExisting = $null
$TagNamesToAssign = $null
Write-Verbose -Message ("Start " + $PSUScript.Name) -Verbose
If($PSUScript.Tag.Name -notcontains $TagNamesEnforced){
Write-Verbose -Message ($PSUScript.Name + " enforced tag missing, attempting to fix") -Verbose
$TagNamesExisting = $PSUScript.Tag.Name
#Get-PSUScript -Name $PSUScript.Name | Set-PSUScript -Tag @('VMware-Admin_Execute','Network-Engineer_Execute') #### WORKING EXAMPLE
[string[]]$TagNamesToAssign = $TagNamesEnforced
If ($TagNamesExisting){$TagNamesToAssign += $TagNamesExisting}
Get-PSUScript -Name $PSUScript.Name | Set-PSUScript -Tag $TagNamesToAssign
}
Write-Verbose -Message ("End " + $PSUScript.Name) -Verbose
}
}
Write-Verbose -Message "End $Folder" -Verbose
}
@@ -0,0 +1,4 @@
# It all starts with a single line of powershell code.
$ITDModules = Get-Module -Name ITD* -ListAvailable
Write-Output $ITDModules
@@ -0,0 +1,2 @@
# It all starts with a single line of powershell code.
Get-Service -ErrorAction SilentlyContinue
@@ -0,0 +1,21 @@
Write-Verbose "UAJob" -Verbose
$UAJob
Write-Verbose "UAJobId" -Verbose
$UAJobId
Write-Verbose "UAScript" -Verbose
$UAScript
Write-Verbose "UAScriptId" -Verbose
$UAScriptId
Write-Verbose "UASchedule" -Verbose
$UASchedule
Write-Verbose "UAScheduleId" -Verbose
$UAScheduleId
Write-Verbose "AccessToken" -Verbose
$AccessToken
@@ -0,0 +1,6 @@
# It all starts with a single line of powershell code.
$Secret:svcitdiaasauto
$Secret:testuser01
$Secret:SNowVMCred
$Secret:AzureVMServicePrincipal
$Secret:svcitdvmvcauto
@@ -0,0 +1,7 @@
# It all starts with a single line of powershell code.
$Secret:itdpsu1
$Secret:norolecred
$Secret:vmcred
$Secret:wincred
$Secret:svcitdvmsnapmgr
$Sercet:svcitdiaasauto_test
@@ -0,0 +1,8 @@
# It all starts with a single line of powershell code.
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_NPD"
$SqlQuery = "INSERT INTO [Infra_VMware_VirtualMachine_VMSnapshots_NPD] (VMName, DateTime, RequestedBy, DurationHours,Status,ExpireDateTime,NotifyEmail,PSUJobIdRequest) Values ('itdscmt1.nd.gov', '2024/07/30 09:24:08', 'prvzmeier@nd.gov', 2, 'Requested', '2024/07/30 11:23:51','zmeier@nd.gov','');SELECT SCOPE_IDENTITY();"
(Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:itdpsu1 -Verbose)
@@ -0,0 +1,42 @@
#######
Write-Verbose -Message "Determine if ITD_PwshGallery is registered" -Verbose
If(Get-PSRepository -Name ITD_PwshGallery -ErrorAction SilentlyContinue){
Write-Verbose -Message "ITD_PwshGallery found." -Verbose
} Else {
$RegisterPSRepositoryParams = @{
Name = 'ITD_PwshGallery';
InstallationPolicy = 'Trusted';
SourceLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
PublishLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
ScriptSourceLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
ScriptPublishLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
}
Register-PSRepository @RegisterPSRepositoryParams
}
Write-Verbose -Message "Retrieve list of all available modules and versions"
$ITDModules = Find-Module -Name "ITD.*" -Repository ITD_PwshGallery
Write-Verbose -Message "Compare local module versions to repository versions, and update if needed"
ForEach($ITDModule in $ITDModules){
$VersionsAvailable = $null
$MostRecentVersion = $null
$RepoVersion = $null
$VersionsAvailable = Get-Module -Name $ITDModule.name -ListAvailable
$MostRecentVersion = $VersionsAvailable | Sort-Object Version -Descending | Select -First 1
$RepoVersion = $ITDModule.Version
If($null -eq $MostRecentVersion) {
Write-Verbose -Message ($ITDModule.Name + " was not found locally, installing module now.") -Verbose
Install-Module -Name $ITDModule.Name -Scope AllUsers -Repository ITD_PwshGallery
} Else {
Write-Verbose -Message ($ITDModule.Name + " was found locally, comparing versions and updating if needed..") -Verbose
Write-Host -Message ($ITDModule.Name)
Write-Host -Message ("Local version is " + $MostRecentVersion.Version)
Write-Host -Message ("The Repo version is " + $RepoVersion)
Write-Host -Message ("")
Update-Module -Name $ITDModule.Name -Scope AllUsers
}
}
@@ -0,0 +1,2 @@
# It all starts with a single line of powershell code. # TEST
Get-PSUIdentity
@@ -0,0 +1,6 @@
param (
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:SNowVMCred -Verbose
Get-ITDServiceNowRecord -ItemType 'Catalog task' -Number 'SCTASK0258692'
@@ -0,0 +1,22 @@
[CmdletBinding()]
param(
[Parameter(ParameterSetName = 'Email')]
[string]
$Email,
[Parameter(ParameterSetName = 'UserName')]
[string]
$UserName
)
#Get-Module ITD.ServiceNow -ListAvailable | select modulebase
New-ITDServiceNowSession -Environment Test -Credential $Secret:SNowVMCred
Get-ITDServiceNowSession
switch($PSCmdlet.ParameterSetName){
'Email' { Get-ITDServiceNowUser -Email $Email}
'UserName' { Get-ITDServiceNowUser -Username $UserName }
}
@@ -0,0 +1,124 @@
$Url = "https://northdakotatest.service-now.com"
$HeaderAuth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $Secret:SNowVMCred.UserName, $Secret:SnowVMCred.GetNetworkCredential().Password)))
$SNOWSessionHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$SNOWSessionHeader.Add('Authorization', ('Basic {0}' -f $HeaderAuth))
$SNOWSessionHeader.Add('Accept', 'application/json')
$Type = "application/json"
$PSUJobId = 123456
$DomainName = 'nd.gov'
$RequestedBy = 'zmeier@nd.gov'
$StartDateTime = Get-Date
New-ITDServiceNowSession -Environment Test -Credential $Secret:SNowVMCred
Get-ITDServiceNowSession
Write-Verbose -Message "Prep variables" -Verbose
$TemplateName = 'NDIT-SPS-Server Add/Chg/Del'
$RequestedByUsername = 'khellman'
$Category = 'Systems Platforms - Systems'
$ShortDescription = 'test'
$Description = 'test'
$Priority = 3
$Impact = 3
$Justification = 'justification'
$Implementation = 'implementation'
$RiskImpactAnalysis = 'riskimpactanalysis'
$BackoutPlan = 'backoutplan'
$TestPlan = 'testplan'
$WhoIsImpacted = 'whoimpacted'
$ChangeManagerUsername = 'khellman'
$ChangeCoordinatorUsername = 'khellman'
$AssignmentGroup = 'NDIT-Computer Systems Windows'
$AssignedToUsername = 'khellman'
$StartTime = Get-Date
$EndTime = $StartTime.AddMinutes(1)
$ChgTemplateStd = Get-ITDServiceNowChangeTemplateStandard -Name $TemplateName
$ChgTemplateStdSysId = $ChgTemplateStd.sys_id.value
Write-Warning -Message ("ChgTemplateStdSysId = " + $ChgTemplateStdSysId)
Write-Verbose -Message "Start NewRecord" -Verbose
[PSCustomObject]$NewRecord = @{
category = $Category;
u_subcategory = $Subcategory
impact = $Impact;
urgency = $Urgency;
short_description = $ShortDescription;
description = $Description;
justification = $Justification;
implementation_plan = $Implementation;
risk_impact_analysis = $RiskImpactAnalysis;
backout_plan = $BackoutPlan;
test_plan = $TestPlan
u_who_is_impacted = $WhoIsImpacted;
start_date = (Get-Date -Date $StartTime -AsUTC).ToString('yyyy-MM-dd HH:mm:ss')
end_date = (Get-Date -Date $EndTime -AsUTC).ToString('yyyy-MM-dd HH:mm:ss')
}
Write-Verbose -Message "Start RequestedBy" -Verbose
If ($RequestedBy) {
$ReqBy = Get-ITDServiceNowUser -Username $RequestedBy
If (@($ReqBy).count -gt 1) {
Write-Error "Multiple requested users found, creation failed." -ErrorAction Stop
}
Else {
$NewRecord += @{requested_by = $ReqBy.sys_id }
}
}
Write-Verbose -Message "Start AssignmentGroup" -Verbose
If ($AssignmentGroup) {
$AssGroup = Get-ITDServiceNowUserGroup -Name $AssignmentGroup
If (@($AssGroup).count -gt 1) {
Write-Error "Multiple assignment groups found, creation failed." -ErrorAction Stop
}
Else {
$NewRecord += @{assignment_group = $AssGroup.sys_id }
}
}
Write-Verbose -Message "Start ChgManagerName" -Verbose
$ChgManagerUsername = Get-ITDServiceNowUser -Username $ChangeManagerUsername
If (@($ChgManagerUsername).count -gt 1) {
Write-Error "Multiple users found for ChangeManagerUsername, creation failed." -ErrorAction Stop
}
Else {
$NewRecord += @{u_change_manager = $ChgManagerUsername.sys_id }
}
Write-Verbose -Message "Start ChgCoordName" -Verbose
$ChgCoordUsername = Get-ITDServiceNowUser -Username $ChangeCoordinatorUsername
If (@($ChgCoordUsername).count -gt 1) {
Write-Error "Multiple users found for ChangeCoordinator, creation failed." -ErrorAction Stop
}
Else {
$NewRecord += @{u_change_coordinator = $ChgCoordUsername.sys_id }
}
Write-Verbose -Message "Start AssignedTousername" -Verbose
If ($AssignedToUsername) {
$AssTo = Get-ITDServiceNowUser -Username $AssignedToUsername
If (@($AssTo).count -gt 1) {
Write-Error "Multiple assignment users found, incident creation failed." -ErrorAction Step
}
Else {
$NewRecord += @{assigned_to = $AssTo.sys_id }
}
}
$Uri = ($Url + "/api/sn_chg_rest/change/standard/$ChgTemplateStdSysId")
Write-Verbose -Message "Standard CHG Template SysId = $Uri" -Verbose
$InvokeRestMethodParams = @{
Method = 'Post';
Uri = $Uri;
Body = $NewRecord | ConvertTo-Json;
Headers = $SnowSessionHeader
ContentType = "application/json"
}
#Write-Output $InvokeRestMethodParams
$result = (Invoke-RestMethod @InvokeRestMethodParams).result
Write-Output $result
#>
@@ -0,0 +1,26 @@
[CmdletBinding()]
param (
[string]
$SCTaskNum
)
#RitmSearch ('variables.208bd5b31b0d0dd04d8943b1b24bcb69%3DInfra.ActiveDirectory.Object')
#$RitmSearch = Get-ITDServiceNowRecord -ItemType 'Request Item' -Filter ('active%3Dtrue^variables.208bd5b31b0d0dd04d8943b1b24bcb69%3DInfra-ActiveDirectory.Object') -Verbose
New-ITDServiceNowSession -Environment Production -Credential $Secret:SNowVMCred
# search Generic Active Directory Service Account tasks
$SCTaskSearch = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter ('active=true^variables.208bd5b31b0d0dd04d8943b1b24bcb69=Infra-ActiveDirectory.Object') -Verbose
Write-Verbose -Message ("SCTaskSearch found: " + @($SCTaskSearch).count) -Verbose
ForEach ($SCTask in $SCTaskSearch) {
# get ritm and look for addl comments about AD
$RitmToReview = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId $SCTask.request_item.value -IncludeCustomVariable
$task_short_description_search = 'Admin task to gather Server Information'
$StringSearchStart = "Please create a new nd.gov Active Directory service account with the following details, following guidelines found in KB0016867.*"
If ($RitmToReview.customvariable.additional_comments.value -like $StringSearchStart -and $SCTask.short_description -eq $task_short_description_search ){
Write-Verbose -Message ($SCTask.Number + " match, update short_description")
Update-ITDServiceNowRecord -ItemType "Catalog Task" -Number $SCTask.number -Values @{
short_description = 'Active Directory Service Account Provisioning'
}
}
}
@@ -0,0 +1,131 @@
Param(
[string]
$SCTaskNum
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:SNowVMCred
$Filter = 'active=true^short_descriptionSTARTSWITHAutomated Server Build Task for Windows Machine'
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter | Sort-Object Number
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum" -Verbose
$OpenTasks = $OpenTasks | Where-Object {$_.number.value -EQ $SCTaskNum}
}
$AllRitms = [System.Collections.ArrayList]@()
Write-Verbose -Message ("OpenTasks found: " + @($OpenTasks).Count) -Verbose
ForEach ($OpenTask in $OpenTasks) {
$Ci = $null
$BuildComplete = $null
# get SCTask, Ritm
$SCTaskNum = $OpenTask.number.value
Write-Verbose -Message "Start $SCTasknum" -Verbose
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$shortdescription = $SCTask.short_description.display_value
$shortdescription_hostname = $shortdescription.split(' ')[7]
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)
}
$ComputerName = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).host_name
$OperatingSystem = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).operating_system
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' { $target_platform = "Azure" }
'vmware' { $target_platform = "VMware" }
}
$FormFQDN = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).host_name
$FormHostName = $FormFQDN.split('.')[0]
$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -Filter ("name=" + $FormHostName)
If ($Ci) {
Write-Verbose -Message ("Ci found, sys_id = " + $Ci.sys_id + ", name = " + $Ci.name + ", fqdn = " + $Ci.fqdn) -Verbose
}
Else {
# Ci does not exist
Write-Verbose -Message ("Ci not found") -Verbose
}
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 = 'Other' }
}
Write-Verbose -Message "Confirm all agents are running"
$ProcessList = @('ccmexec', 'cohesity*', 'nessus*', 'cortex*')
switch ($target_platform) {
'VMware' {
$ProcessList += 'vmtoolsd'
}
'Azure' {
Write-Verbose -Message "vmtoolsd not required for Azure VM"
}
Default {
Write-Verbose -Message "no Ci means no platform check"
}
}
try {
#$Secret:itdsccmsrvcpiandgov
$RunningProcess = Invoke-Command -Credential $Secret:itdsccmsrvcpiandgov -ComputerName $FormFQDN -ArgumentList $ProcessList -ErrorAction Stop -ScriptBlock {
Get-Process
}
If ($RunningProcess) {
ForEach ($ProcessName in $ProcessList) {
If ($RunningProcess -match $ProcessName) {
Write-Verbose -Message "Process $ProcessName found." -Verbose
}
Else {
Write-Warning -Message "Process $ProcessName not found"
$BuildComplete = $false
}
}
}
}
catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
Write-Warning -Message "$FormFQDN unreachable via PSRemoting"
$BuildComplete = $false
}
# if Task has been open for more than x hours, update description for humans to review
$Hours = 6
If ($SCTask.opened_at.value -lt (Get-Date).AddHours(-$Hours)) {
$work_notes = ("New build Ci has not been found after $Hours hours, problem may have occurred. Please review.`nPSU Job Id #" + $UAJob.Id)
$shortdescription = "$target_platform $OperatingSystem VM Build for $ComputerName, NEED HUMAN REVIEW"
<#Update-ServiceNowRecord -ID $SCTask.number -Values @{
work_notes = $work_notes;
shortdescription = $shortdescription;
}#>
}
If ($BuildComplete -ne $false) {
Write-Verbose "All required processes running, Windows is ready for use. Update SCTask to notify physical/virtual hardware stakeholders." -Verbose
$work_notes = ("$target_platform $hardware_type $FormFQDN Windows Guest OS complete. `nPSU Job Id #" + $UAJob.Id)
$shortdescription = "$target_platform $hardware_type $FormFQDN Windows Guest OS complete."
Write-Verbose -Message "Work notes: $work_notes" -Verbose
Write-Verbose -Message "Short description: $shortdescription" -Verbose
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = $work_notes;
close_notes = "$FQDN $target_platform Windows Guest OS complete.";
#short_description = $shortdescription;
state = 'Closed Complete'
}
}
Write-Verbose -Message "End $SCTasknum" -Verbose
}
@@ -0,0 +1,13 @@
Param(
[string]
$ComputerName
)
If ($PSBoundParameters.ContainsKey('ComputerName')) {
$GetITDExpiredFilesParams = @{
ComputerName = $ComputerName;
}
Get-ITDExpiredFilesAuto @GetITDExpiredFilesParams -Credential $Secret:itdsccmsrvcpiandgov -Verbose | Select-Object Name,DirectoryName,Extension,LastWriteTime,Length,PSComputerName
} Else {
Get-ITDExpiredFilesAuto -Credential $Secret:itdsccmsrvcpiandgov -Verbose | Select-Object Name,DirectoryName,Extension,LastWriteTime,Length,PSComputerName
}
@@ -0,0 +1,59 @@
[CmdletBinding()]
param (
[string]
$ComputerName,
[int]
$CPU = 1,
[int]
$MemoryGB = 4,
[int]
$DiskOsGB = 128,
[int]
$DiskDataGB = 0,
[string]
$Subnet,
[string]
$OS,
[string]
$Environment,
[string]
$Subscription,
[string]
$AppName,
[string]
$LicensingRestrictions
)
$params = @{
ComputerName = $ComputerName;
CPU = $CPU;
MemoryGB = $MemoryGB;
DiskOsGB = $DiskOsGB;
DiskDataGB = $DiskDataGB;
Subnet = $Subnet;
OS = $OS;
Environment = $Environment;
Subscription = $Subscription;
AppName = $AppName;
LicensingRestrictions = $LicensingRestrictions;
Credential = $Credential;
}
Write-Verbose -Message "Connect to Azure using Service Principal" -Verbose
$tenantId = '2dea0464-da51-4a88-bae2-b3db94bc0c54'
$AppId = '60244573-7130-4026-9c6d-47de73f8ca29'
$SecureStringPwd = 'Pqt8Q~E-dDmQugcPPWdaK2t_4retS41VVVVOZbOx' # $Secret:AzureVMServicePrincipal # $IaasAutoAzApp
$PSCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, ($SecureStringPwd | ConvertTo-SecureString -AsPlainText -Force)
Connect-AzAccount -ServicePrincipal -Credential $PSCredential -Tenant $tenantId
New-ITDWindowsVmAzure @params -Credential $PrvCred -Verbose
@@ -0,0 +1,82 @@
Param(
[string]
$ComputerName,
[switch]
$WhatIf,
[switch]
$Quiet
)
$RemoveITDExpiredFilesAutoParams = @{
}
If ($PSBoundParameters.ContainsKey('ComputerName')) {
Write-Verbose -Message "ComputerName parameter"
$RemoveITDExpiredFilesAutoParams += @{ComputerName = $ComputerName }
}
If ($PSBoundParameters.ContainsKey('WhatIf')) {
Write-Verbose -Message "WhatIf parameter"
$RemoveITDExpiredFilesAutoParams += @{WhatIf = $true }
}
$StartTime = (Get-Date)
$FilesRemoved = Remove-ITDExpiredFilesAuto @RemoveITDExpiredFilesAutoParams -Verbose -Credential $Secret:itdsccmsrvcpiandgov
# get information for notes
$DiskBytesRecovered = ($FilesRemoved | Measure-Object -Sum length).Sum
$Notes = "PSComputerName~Length~FullName" + "`n"
$Notes += ForEach ($File in $FilesRemoved) {
If ($File) {
$File.PSComputerName + "~" + $File.Length + "~" + $File.FullName + "`n"
}
}
$Notes += "$DiskBytesRecovered bytes of disk saved."
Write-Verbose -Message "Notes: `n$Notes" -Verbose
$EndTime = (Get-Date)
If ($PSBoundParameters.ContainsKey('Quiet') -and $Quiet -eq $true) {
Write-Verbose -Message "Quiet mode enabled. No ServiceNow interactions will be done." -Verbose
}
Else {
Write-Verbose -Message "Quiet mode disabled. ServiceNow CHG will be generated."
# create std chg and close it
New-ITDServiceNowSession Test -Credential $Secret:SNowVMCred
$NewITDServiceNowChangeRequestParams = @{
TemplateName = 'NDIT-SPS-Server Add/Chg/Del'
RequestedByUsername = 'zmeier';
Category = 'Systems Platforms - Systems';
Subcategory = 'Windows';
Impact = 3;
ShortDescription = "Remove files flagged for expiration and cleanup - Remove-ITDExpiredFilesAuto_script - $UAJobId";
Description = "Remove files flagged for expiration and cleanup";
Justification = "Some files are generated on a recurring basis causing increase in disk space usage. This automation removes specific file types from specified file paths that have been flagged for removal.";
Implementation = "PSUniversal execution";
RiskImpactAnalysis = "Low, files can be discovered before the removal";
BackoutPlan = "Restore from backup (if applicable)"
TestPlan = "n/a"
WhoIsImpacted = "Windows System Administrators";
StartTime = $StartTime
EndTime = $EndTime;
AssignmentGroup = 'NDIT-Computer Systems Windows';
ChangeManagerUsername = 'khellman';
ChangeCoordinatorUsername = 'gpgolberg';
AssignedToUsername = 'zmeier';
}
If ($PSBoundParameters.ContainsKey('WhatIf')) {
$NewITDServiceNowChangeRequestParams.ShortDescription += " -WhatIf"
}
$CHG = New-ITDServiceNowChangeRequest @NewITDServiceNowChangeRequestParams
Update-ITDServiceNowRecord -ItemType "Change Request" -Number $CHG.Number.Value -Values @{
work_notes = $Notes;
}
Complete-ITDServiceNowChangeRequest -Number $CHG.Number.value -CloseCode "Successful" -CloseNotes "Files removed."
}
@@ -0,0 +1,10 @@
Param(
[Parameter(Mandatory = $true)]
[string[]]
$ComputerName
)
ForEach ($cn in $ComputerName) {
Write-Verbose -Message "Attempt Solarwinds removal for $cn" -Verbose
Remove-ITDSolarwindsNode -ComputerName $cn -Credential $Secret:svcitdiaasauto -Verbose
}
@@ -0,0 +1,86 @@
param(
[string]
$SCTaskNum
)
#New-ServiceNowSession -Url 'northdakota.service-now.com' -Credential $Secret:SNowVMCred -Verbose
New-ITDServiceNowSession -Environment Production -Credential $Secret:SNowVMCred
#$Filter = @('assignment_group', '-like', 'NDIT-Server Build Automation'), '-and', @('short_description', '-like', 'VMware Windows Removal for'), '-and', @('state', '-eq', '1')
$Filter = "active=true^short_descriptionLIKEWindows Removal for "
#sysparm_query%3Dactive=true^short_descriptionLIKEWindows Removal for
#$OpenTasks = Get-ServiceNowRecord -Table 'Catalog Task' -Filter $Filter -WarningAction SilentlyContinue | Sort-Object Number
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter -IncludeTotalCount | Sort-Object {$_.Number.value}
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum"
$OpenTasks = $OpenTasks | Where-Object {$_.number.value -EQ $SCTaskNum}
}
$AllRitms = [System.Collections.ArrayList]@()
Write-Verbose -Message ("Number of OpenTasks is " + @($OpenTasks).count) -Verbose
Connect-ITDvCenter -Credential $Secret:svcitdiaasauto
ForEach ($OpenTask in $OpenTasks) {
# get SCTask, Ritm
$SCTask = $OpenTask
$SCTaskNum = $OpenTask.number.display_value
Write-Verbose -Message ("Start " + $SCTaskNum) -Verbose
$short_description = $SCTask.short_description.display_value
$short_description_hostname = $short_description.split(' ')[4]
$RitmNum = $SCTask.request_item.display_value
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)
}
#$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -Filter ("name=" + $short_description_hostname)
#$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -SysId ($Ritm.VariableSet | Where-Object .host_name_ref) -ErrorAction Stop
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 ($short_description_hostname -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
}
$HostName = $Ci.Name.display_value
$FQDN = $Ci.FQDN.display_value
Write-Verbose -Message ("Ci Name " + $Ci.Name.display_value) -Verbose
Write-Verbose -Message ("Ci FQDN " + $Ci.FQDN.display_value) -Verbose
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' }
}
try {
Write-Verbose -Message "Start Removal of $FQDN, $hardware_platform $hardware_type" -Verbose
Remove-ITDWindowsServer -ComputerName $FQDN -SCTaskNum $SCTaskNum -Credential $Secret:svcitdiaasauto -Verbose # $Secret:svcitdiaasauto
#$short_description_new = "$hardware_platform $hardware_type $FQDN is ready for removal."
#Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = $short_description; }
#Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{short_description = $short_description_new}
Write-Verbose -Message "End Removal of $FQDN" -Verbose
}
catch {
Write-Error $error[0]
}
Write-Verbose -Message "End $SCTasknum" -Verbose
}
Disconnect-ITDvCenter
@@ -0,0 +1,13 @@
Param(
[string]
$ComputerName
)
If ($PSBoundParameters.ContainsKey('ComputerName')) {
$GetITDExpiredFilesParams = @{
ComputerName = $ComputerName;
}
Get-ITDExpiredFiles @GetITDExpiredFilesParams -Credential $Secret:ndgov_svcitdpsuwin -Verbose | Select-Object Name,DirectoryName,Extension,LastWriteTime,Length,PSComputerName | Format-Table -AutoSize
} Else {
Get-ITDExpiredFiles -Credential $Secret:ndgov_svcitdpsuwin -Verbose | Select-Object Name,DirectoryName,Extension,LastWriteTime,Length,PSComputerName | Format-Table -AutoSize
}
@@ -0,0 +1,119 @@
[CmdletBinding()]
param (
[string]
$ComputerName,
[switch]
$WhatIf
)
Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose
$RequestedBy = $UAJob.Identity.Name # user that started the job
$PSUJobId = $UAJob.Id
$FilesRemovedSuccess = @()
$FilesRemovedFailure = @()
$GetITDExpiredFilesAutoParams += @{}
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch($UAJob.ComputerName){
"ITDWINAUTOT1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$Table = "Infra_WindowsServer_FileManagement_RemoveITDExpiredFiles_NPD"
}
"ITDWINAUTOP1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$Table = "Infra_WindowsServer_FileManagement_RemoveITDExpiredFiles_PRD"
}
}
If ($PSBoundParameters.ContainsKey('ComputerName')) {
Write-Verbose -Message "ComputerName parameter found" -Verbose
$GetITDExpiredFilesParams = @{
Credential = $Secret:ndgov_svcitdpsuwin
}
$GetITDExpiredFilesParams += @{
ComputerName = $ComputerName;
}
}
$FilesToRemove = Get-ITDExpiredFiles @GetITDExpiredFilesParams
Write-Verbose -Message ("Found " + $FilesToRemove.count + " expired files to remove") -Verbose
ForEach ($File in $FilesToRemove) {
Write-Verbose -Message ("Start~" + $File.PSComputerName + "~" + $File.FullName )
$ComputerName = $File.PSComputerName
$DateTime = Get-Date
$FullName = $File.FullName
$InvokeCommandParams = @{
ComputerName = $File.PSComputerName;
#Credential = $Secret:ndgov_svcitdpsuwin;
ErrorAction = 'Stop';
ArgumentList = @($File.FullName);
ScriptBlock = { Get-Item -Path $args[0] | Remove-Item }
}
switch ($WhatIf) {
$true {
Write-Verbose -Message "WhatIf switch true" -Verbose
try {
Write-Verbose -Message ("Process~" + $File.PSComputerName + "~" + $File.FullName + " removed")
Write-Host -Message ($Server.ComputerName + " -- " + 'What if: Performing the operation "Remove File" on target ' + $File.FullName)
# log success
$FilesRemovedSuccess += [PSCustomObject]@{
DateTime = $DateTime.tostring("yyyy/MM/dd HH:mm:ss");
ComputerName = $ComputerName;
FullName = $FullName;
}#>
Write-Output $File
}
catch {
Write-Verbose -Message ("Process~" + $File.PSComputerName + "~" + $File.FullName + " failure")
# log failure
$FilesRemovedFailure += [PSCustomObject]@{
DateTime = $DateTime.tostring("yyyy/MM/dd HH:mm:ss");
ComputerName = $ComputerName;
FullName = $FullName;
}
}
}
Default {
try {
Write-Verbose -Message "WhatIf switch default" -Verbose
Invoke-Command @InvokeCommandParams
Write-Verbose -Message ("Process~" + $File.PSComputerName + "~" + $File.FullName + " removed")
# log success to sql, add obj to array
$SqlQuery = "INSERT INTO [$Table] (PSUJobId, DateTime, ComputerName, Status, FullName) Values ('$PSUJobId', '$DateTime', '$ComputerName', 'Success', '$FullName')"
$SqlRecord = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
$FilesRemovedSuccess += [PSCustomObject]@{
DateTime = $DateTime.tostring("yyyy/MM/dd HH:mm:ss");
ComputerName = $ComputerName;
FullName = $FullName;
}
Write-Output $File
}
catch {
Write-Verbose -Message ("Start~" + $File.PSComputerName + "~" + $File.FullName + " failure")
# log failure to sql, add obj to array
$SqlQuery = "INSERT INTO [$Table] (PSUJobId, DateTime, ComputerName, Status, FullName) Values ('$PSUJobId', '$DateTime', '$ComputerName', 'Failure', '$FullName')"
$SqlRecord = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
$FilesRemovedFailure += [PSCustomObject]@{
DateTime = $DateTime.tostring("yyyy/MM/dd HH:mm:ss");
ComputerName = $ComputerName;
FullName = $FullName;
}
}
}
}
# create CHG request for the work
Write-Verbose -Message "Submit CHG for the work. TBD" -Verbose
Write-Verbose -Message ("End~" + $File.PSComputerName + "~" + $File.FullName ) -Verbose
### Generate CHG
}
@@ -0,0 +1,146 @@
# cron expression
# 47 8-16 * * 1-5
Param(
[string]
$SCTaskNum
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
$Filter = 'active=true^short_descriptionSTARTSWITHAutomated Server Build Task for Windows Machine'
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter | Sort-Object Number
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum" -Verbose
$OpenTasks = $OpenTasks | Where-Object { $_.number.value -EQ $SCTaskNum }
}
$AllRitms = [System.Collections.ArrayList]@()
Write-Verbose -Message ("OpenTasks found: " + @($OpenTasks).Count) -Verbose
ForEach ($OpenTask in $OpenTasks) {
$Ci = $null
$BuildComplete = $null
# get SCTask, Ritm
$SCTaskNum = $OpenTask.number.value
Write-Verbose -Message "Start $SCTasknum" -Verbose
try {
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$shortdescription = $SCTask.short_description.display_value
$shortdescription_hostname = $shortdescription.split(' ')[7]
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)
}
$ComputerName = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).host_name
$OperatingSystem = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).operating_system
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' { $target_platform = "Azure" }
'vmware' { $target_platform = "VMware" }
}
$FormFQDN = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).host_name
$FormHostName = $FormFQDN.split('.')[0]
$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -Filter ("name=" + $FormHostName)
If ($Ci) {
Write-Verbose -Message ("Ci found, sys_id = " + $Ci.sys_id + ", name = " + $Ci.name + ", fqdn = " + $Ci.fqdn) -Verbose
}
Else {
# Ci does not exist
Write-Verbose -Message ("Ci not found") -Verbose
}
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 = 'Other' }
}
Write-Verbose -Message "Confirm all agents are running"
$ProcessList = @('ccmexec', 'cohesity*', 'nessus*', 'cortex*')
switch ($target_platform) {
'VMware' {
$ProcessList += 'vmtoolsd'
}
'Azure' {
Write-Verbose -Message "vmtoolsd not required for Azure VM"
}
Default {
Write-Verbose -Message "no Ci means no platform check"
}
}
}
catch {
Write-Error $error[0]
}
If ( $ComputerName -like "*.nd.gov" ) {
try {
$AgentCount = 0
$svcitdpsuwin = Get-ITDPassword -UserName ndgov\svcitdpsuwin -Title ndgov\svcitdpsuwin
$RunningProcess = Invoke-Command -Credential $svcitdpsuwin -ComputerName $FormFQDN -ArgumentList $ProcessList -ErrorAction Stop -ScriptBlock {
Get-Process
}
If ($RunningProcess) {
ForEach ($ProcessName in $ProcessList) {
If ($RunningProcess -match $ProcessName) {
Write-Verbose -Message "Process $ProcessName found." -Verbose
$AgentCount = $AgentCount + 1
}
Else {
Write-Warning -Message "Process $ProcessName not found"
# do not increase agentcount count
}
}
}
}
catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
Write-Warning -Message "$FormFQDN unreachable via PSRemoting"
$BuildComplete = $false
}
} Else {
Write-Verbose -Message ($SCTaskNum + $ComputerName + " is not nd.gov, manual agent validation required.") -Verbose
}
<# if Task has been open for more than x hours, update description for humans to review
$Hours = 6
If ($SCTask.opened_at.value -lt (Get-Date).AddHours(-$Hours)) {
$work_notes = ("New build Ci has not been found after $Hours hours, problem may have occurred. Please review.`nPSU Job Id #" + $UAJob.Id)
$shortdescription = "$target_platform $OperatingSystem VM Build for $ComputerName, NEED HUMAN REVIEW"
<#Update-ServiceNowRecord -ID $SCTask.number -Values @{
work_notes = $work_notes;
shortdescription = $shortdescription;
}
}#>
If ($AgentCount -ge @($ProcessList).count) {
Write-Verbose "All required processes running, Windows is ready for use. Update SCTask to notify physical/virtual hardware stakeholders." -Verbose
$work_notes = ("$target_platform $hardware_type $FormFQDN Windows Guest OS complete. `nPSU Job Id #" + $UAJob.Id)
$shortdescription = "$target_platform $hardware_type $FormFQDN Windows Guest OS complete."
Write-Verbose -Message "Work notes: $work_notes" -Verbose
Write-Verbose -Message "Short description: $shortdescription" -Verbose
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = $work_notes;
close_notes = "$FQDN $target_platform Windows Guest OS complete.";
short_description = $shortdescription;
state = 'Closed Complete'
}
}
Write-Verbose -Message "End $SCTasknum" -Verbose
}
@@ -0,0 +1,130 @@
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$ComputerName,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$CPU = 1,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$MemoryGB = 4,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskOsGB = 128,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskDataGB = 20,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Subnet,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$OS = 'Windows Server 2022 Datacenter',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Environment,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$AppName,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$LicensingRestrictions = 'No Licensing Restrictions',
[string]
$ResourceGroupNameOverride,
[ValidateSet('1', '2', '3')]
[int]
$AvailabilityZone
)
switch ($PSCmdlet.ParameterSetName) {
'ManualEntry' {
$NewITDWindowsVmAzureParams = @{
ComputerName = $ComputerName;
AppName = $AppName;
CPU = $CPU;
MemoryGB = $MemoryGB;
DiskOsGB = $DiskOsGB;
DiskDataGB = $DiskDataGB;
Subnet = $Subnet;
OS = $OS;
Environment = $Environment;
LicensingRestrictions = $LicensingRestrictions;
}
switch ($PSBoundParameters.Keys) {
'ResourceGroupNameOverride' { $NewITDWindowsVmAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride } }
'AvailabilityZone' { $NewITDWindowsVmAzureParams += @{ AvailabilityZone = $AvailabilityZone } }
}
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
Write-Verbose -Message "New-ITDServiceNowSession" -Verbose
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
$NewITDWindowsVmAzureParams = @{
ComputerName = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
CPU = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).processors );
MemoryGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).memory_gb );
DiskOsGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_1_os );
DiskDataGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_3 );
Subnet = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).cidr_block).name.display_value;
OS = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).target_os_version_windows );
Environment = ( $Ritm.customvariable.environment.value );
AppName = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).application_info).name.display_value;
LicensingRestrictions = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).licensing_restrictions );
}
switch ($PSBoundParameters.Keys) {
'ResourceGroupNameOverride' {
Write-Warning -Message "ResourceGroupNameOverride found $ResourceGroupNameOverride"
$NewITDWindowsVMAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride }
}
'AvailabilityZone' { Write-Warning -Message "ResourceGroupNameOverride found $ResourceGroupNameOverride"
$NewITDWindowsVMAzureParams += @{ AvailabilityZone = $AvailabilityZone }
}
}
}
}
Write-Verbose -Message "Connect to Azure using Service Principal" -Verbose
$tenantId = '2dea0464-da51-4a88-bae2-b3db94bc0c54'
$AppId = '60244573-7130-4026-9c6d-47de73f8ca29'
$SecureStringPwd = $Secret:azure_iaasserviceprincipal
$PSCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, ($SecureStringPwd | ConvertTo-SecureString -AsPlainText -Force)
Connect-AzAccount -ServicePrincipal -Credential $PSCredential -Tenant $tenantId
Write-Verbose -Message "NewITDWindowsVMAzureParams:" -Verbose
Write-Verbose -Message ("ComputerName " + $NewITDWindowsVMAzureParams.ComputerName) -Verbose
Write-Verbose -Message ("CPU " + $NewITDWindowsVMAzureParams.CPU) -Verbose
Write-Verbose -Message ("MemoryGB " + $NewITDWindowsVMAzureParams.MemoryGB) -Verbose
Write-Verbose -Message ("DiskOsGB" + $NewITDWindowsVMAzureParams.DiskOsGB) -Verbose
Write-Verbose -Message ("DiskDataGB " + $NewITDWindowsVMAzureParams.DiskDataGB) -Verbose
Write-Verbose -Message ("Subnet " + $NewITDWindowsVMAzureParams.Subnet) -Verbose
Write-Verbose -Message ("OS" + $NewITDWindowsVMAzureParams.OS) -Verbose
Write-Verbose -Message ("Environment" + $NewITDWindowsVMAzureParams.Environment) -Verbose
Write-Verbose -Message ("AppName" + $NewITDWindowsVMAzureParams.AppName) -Verbose
Write-Verbose -Message ("LicensingRestrictions" + $NewITDWindowsVMAzureParams.LicensingRestrictions) -Verbose
New-ITDWindowsVmAzure @NewITDWindowsVmAzureParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
@@ -0,0 +1,118 @@
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$ComputerName,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$CPU = 1,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$MemoryGB = 4,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskOsGB = 50,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskSwapGB = ($MemoryGB + 1),
[Parameter(ParameterSetName = 'ManualEntry')]
[int]
$DiskDataGB,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Subnet = '10.11.12.0/23',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$OS = 'Windows Server 2022 Datacenter',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Environment = 'Test',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Datacenter = 'Mandan',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$AppName = 'ITD-POC-zmeier',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$StartupPriority = 5,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$LicensingRestrictions = "No Licensing Restrictions"
)
switch ($PSCMdlet.ParameterSetName) {
'ManualEntry' {
$NewITDWindowsVmVMwareParams = @{
ComputerName = $ComputerName;
CPU = $CPU;
MemoryGB = $MemoryGB;
DiskOsGB = $DiskOsGB;
DiskSwapGB = $DiskSwapGB;
DiskDataGB = $DiskDataGB;
Subnet = $Subnet;
OS = $OS;
Environment = $Environment;
Datacenter = $Datacenter;
AppName = $AppName;
StartupPriority = $StartupPriority;
LicensingRestrictions = $LicensingRestrictions;
}
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
$NewITDWindowsVmVMwareParams = @{
ComputerName = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
CPU = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).processors );
MemoryGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).memory_gb );
DiskOsGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_1_os );
DiskSwapGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_2_swap_disk );
DiskDataGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_3 );
Subnet = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).cidr_block).name.display_value;
OS = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).target_os_version_windows );
Environment = ( $Ritm.customvariable.environment.value );
Datacenter = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).data_center );
AppName = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).application_info).name.display_value;
StartupPriority = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).startup_priority );
LicensingRestrictions = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).licensing_restrictions );
}
}
}
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdiaasauto -Verbose
Write-Verbose -Message "Attempt server provisioning" -Verbose
Write-Host $NewITDWindowsVmVMwareParams
New-ITDWindowsVmVMware @NewITDWindowsVmVMwareParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
Write-Warning -Message "New-ITDWindowsVmVMware function completed"
Write-Verbose -Message "Disconnect from vCenter" -Verbose
Disconnect-ITDvCenter
@@ -0,0 +1,92 @@
param(
[string]
$SCTaskNum
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
$Filter = "active=true^short_descriptionLIKEWindows Removal for "
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter -IncludeTotalCount | Sort-Object { $_.Number.value }
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum"
$OpenTasks = $OpenTasks | Where-Object { $_.number.value -EQ $SCTaskNum }
}
$AllRitms = [System.Collections.ArrayList]@()
Write-Verbose -Message ("Number of OpenTasks is " + @($OpenTasks).count) -Verbose
# retrieve ndgov\svcitdiaasauto password to be used for Remove-ITDWindowsServer function
$svcitdiaasauto = Get-ITDPassword -Title "IaaS Automation Account" -UserName "ndgov\svcitdiaasauto"
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter
ForEach ($OpenTask in $OpenTasks) {
# get SCTask, Ritm
$SCTask = $OpenTask
$SCTaskNum = $OpenTask.number.display_value
Write-Verbose -Message ("Start " + $SCTaskNum) -Verbose
If ($SCTask.work_notes.display_value -like "*needs human review*") {
Write-Verbose -Message ($SCTaskNum + " flagged for human review, skipping...") -Verbose
}
Else {
$short_description = $SCTask.short_description.display_value
$short_description_hostname = $short_description.split(' ')[4]
$RitmNum = $SCTask.request_item.display_value
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)
}
#$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -Filter ("name=" + $short_description_hostname)
#$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -SysId ($Ritm.VariableSet | Where-Object .host_name_ref) -ErrorAction Stop
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 ($short_description_hostname -eq $TempCi.FQDN.display_value) {
$Ci = $TempCi
$MatchFound = $true
}
}
If ($MatchFound -eq $false) {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = 'error during Windows decommission, needs human review'
}
Write-Warning -Message "ComputerName $ComputerName was not found in VariableSet for $RitmNum" -WarningAction Continue
}
$HostName = $Ci.Name.display_value
$FQDN = $Ci.FQDN.display_value
Write-Verbose -Message ("Ci Name " + $Ci.Name.display_value) -Verbose
Write-Verbose -Message ("Ci FQDN " + $Ci.FQDN.display_value) -Verbose
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' }
}
try {
Write-Verbose -Message "Start Removal of $FQDN, $hardware_platform $hardware_type" -Verbose
Remove-ITDWindowsServer -ComputerName $FQDN -SCTaskNum $SCTaskNum -Credential $svcitdiaasauto -Verbose
Write-Verbose -Message "End Removal of $FQDN" -Verbose
}
catch {
Write-Error $error[0]
}
Write-Verbose -Message "End $SCTasknum" -Verbose
}
}
Write-Verbose -Message "Disconnect to vCenter" -Verbose
Disconnect-ITDvCenter
@@ -0,0 +1,145 @@
[CmdletBinding()] #
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$FQDN,
[Parameter(ParameterSetName = 'FromSCTask')]
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$VMSizeOverride,
<#
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$CPU = 1,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$MemoryGB = 4,
#>
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskOsGB = 128,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskDataGB = 20,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Subnet,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$OS = 'Windows Server 2022 Datacenter',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$VMEnvironment,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$AppName,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$LicensingRestrictions = 'No Licensing Restrictions',
[string]
$ResourceGroupNameOverride,
[ValidateSet('1', '2', '3')]
[int]
$AvailabilityZone
)
switch ($PSCmdlet.ParameterSetName) {
'ManualEntry' {
$NewITDWindowsVmAzureParams = @{
FQDN = $FQDN;
AppName = $AppName;
VMSizeOverride = $VMSizeOverride;
#CPU = $CPU;
#MemoryGB = $MemoryGB;
DiskOsGB = $DiskOsGB;
DiskDataGB = $DiskDataGB;
Subnet = $Subnet;
OS = $OS;
VMEnvironment = $VMEnvironment;
LicensingRestrictions = $LicensingRestrictions;
}
switch ($PSBoundParameters.Keys) {
'ResourceGroupNameOverride' { $NewITDWindowsVmAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride } }
'AvailabilityZone' { $NewITDWindowsVmAzureParams += @{ AvailabilityZone = $AvailabilityZone } }
}
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
Write-Verbose -Message "New-ITDServiceNowSession" -Verbose
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
$NewITDWindowsVmAzureParams = @{
FQDN = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
DiskOsGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_1_os );
DiskDataGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_3 );
Subnet = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).cidr_block).name.display_value;
OS = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).target_os_version_windows );
VMEnvironment = ( $Ritm.customvariable.environment.value );
AppName = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).application_info).name.display_value;
LicensingRestrictions = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).licensing_restrictions );
}
switch ($PSBoundParameters.Keys) {
'ResourceGroupNameOverride' {
Write-Warning -Message "ResourceGroupNameOverride found $ResourceGroupNameOverride"
$NewITDWindowsVMAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride }
}
'AvailabilityZone' {
Write-Warning -Message "ResourceGroupNameOverride found $AvailabilityZone"
$NewITDWindowsVMAzureParams += @{ AvailabilityZone = $AvailabilityZone }
}
'VMSizeOverride' {
Write-Warning -Message "VMSizeOverride found $VMSizeOverride"
$NewITDWindowsVMAzureParams += @{ VMSizeOverride = $VMSizeOverride }
}
}
If ($NewITDWindowsVmAzureParams.VMSizeOverride) {
# do nothing
} Else {
$NewITDWindowsVMAzureParams += @{ CPU = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).processors );}
$NewITDWindowsVMAzureParams += @{ MemoryGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).memory_gb );}
}
}
}
Write-Verbose -Message "Connect to Azure using Service Principal" -Verbose
$tenantId = '2dea0464-da51-4a88-bae2-b3db94bc0c54'
$AppId = '60244573-7130-4026-9c6d-47de73f8ca29'
$SecureStringPwd = $Secret:azure_iaasserviceprincipal
$PSCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, ($SecureStringPwd | ConvertTo-SecureString -AsPlainText -Force)
Connect-AzAccount -ServicePrincipal -Credential $PSCredential -Tenant $tenantId
Write-Verbose -Message "NewITDWindowsVMAzureParams:" -Verbose
Write-Verbose -Message ("FQDN " + $NewITDWindowsVMAzureParams.FQDN) -Verbose
Write-Verbose -Message ("CPU " + $NewITDWindowsVMAzureParams.CPU) -Verbose
Write-Verbose -Message ("MemoryGB " + $NewITDWindowsVMAzureParams.MemoryGB) -Verbose
Write-Verbose -Message ("DiskOsGB" + $NewITDWindowsVMAzureParams.DiskOsGB) -Verbose
Write-Verbose -Message ("DiskDataGB " + $NewITDWindowsVMAzureParams.DiskDataGB) -Verbose
Write-Verbose -Message ("Subnet " + $NewITDWindowsVMAzureParams.Subnet) -Verbose
Write-Verbose -Message ("OS" + $NewITDWindowsVMAzureParams.OS) -Verbose
Write-Verbose -Message ("VMEnvironment" + $NewITDWindowsVMAzureParams.Environment) -Verbose
Write-Verbose -Message ("AppName" + $NewITDWindowsVMAzureParams.AppName) -Verbose
Write-Verbose -Message ("LicensingRestrictions" + $NewITDWindowsVMAzureParams.LicensingRestrictions) -Verbose
New-ITDWindowsVmAzureStep1 @NewITDWindowsVmAzureParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
@@ -0,0 +1,151 @@
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$ComputerName,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
<<<<<<< HEAD
[string]
$VMSizeOverride,
<<<<<<< HEAD
<#
=======
<#
>>>>>>> main
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
=======
>>>>>>> 828a9d5a994531efc47fe9ca78c93cfb076c6ba4
[int]
$CPU = 1,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$MemoryGB = 4,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskOsGB = 128,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskDataGB = 20,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Subnet,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$OS = 'Windows Server 2022 Datacenter',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Environment,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$AppName,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$LicensingRestrictions = 'No Licensing Restrictions',
[string]
$ResourceGroupNameOverride,
[ValidateSet('1', '2', '3')]
[int]
$AvailabilityZone
)
switch ($PSCmdlet.ParameterSetName) {
'ManualEntry' {
$NewITDWindowsVmAzureParams = @{
ComputerName = $ComputerName;
AppName = $AppName;
<<<<<<< HEAD
<<<<<<< HEAD
VMSizeOverride = $VMSizeOverride;
=======
VMSizeOverride = $VMSizeOverride;
>>>>>>> main
#CPU = $CPU;
#MemoryGB = $MemoryGB;
=======
CPU = $CPU;
MemoryGB = $MemoryGB;
>>>>>>> 828a9d5a994531efc47fe9ca78c93cfb076c6ba4
DiskOsGB = $DiskOsGB;
DiskDataGB = $DiskDataGB;
Subnet = $Subnet;
OS = $OS;
Environment = $Environment;
LicensingRestrictions = $LicensingRestrictions;
}
switch ($PSBoundParameters.Keys) {
'ResourceGroupNameOverride' { $NewITDWindowsVmAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride } }
'AvailabilityZone' { $NewITDWindowsVmAzureParams += @{ AvailabilityZone = $AvailabilityZone } }
}
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
Write-Verbose -Message "New-ITDServiceNowSession" -Verbose
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
$NewITDWindowsVmAzureParams = @{
ComputerName = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
CPU = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).processors );
MemoryGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).memory_gb );
DiskOsGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_1_os );
DiskDataGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_3 );
Subnet = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).cidr_block).name.display_value;
OS = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).target_os_version_windows );
Environment = ( $Ritm.customvariable.environment.value );
AppName = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).application_info).name.display_value;
LicensingRestrictions = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).licensing_restrictions );
}
switch ($PSBoundParameters.Keys) {
'ResourceGroupNameOverride' {
Write-Warning -Message "ResourceGroupNameOverride found $ResourceGroupNameOverride"
$NewITDWindowsVMAzureParams += @{ ResourceGroupNameOverride = $ResourceGroupNameOverride }
}
'AvailabilityZone' { Write-Warning -Message "ResourceGroupNameOverride found $ResourceGroupNameOverride"
$NewITDWindowsVMAzureParams += @{ AvailabilityZone = $AvailabilityZone }
}
}
}
}
Write-Verbose -Message "Connect to Azure using Service Principal" -Verbose
$tenantId = '2dea0464-da51-4a88-bae2-b3db94bc0c54'
$AppId = '60244573-7130-4026-9c6d-47de73f8ca29'
$SecureStringPwd = $Secret:azure_iaasserviceprincipal
$PSCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, ($SecureStringPwd | ConvertTo-SecureString -AsPlainText -Force)
Connect-AzAccount -ServicePrincipal -Credential $PSCredential -Tenant $tenantId
Write-Verbose -Message "NewITDWindowsVMAzureParams:" -Verbose
Write-Verbose -Message ("ComputerName " + $NewITDWindowsVMAzureParams.ComputerName) -Verbose
Write-Verbose -Message ("CPU " + $NewITDWindowsVMAzureParams.CPU) -Verbose
Write-Verbose -Message ("MemoryGB " + $NewITDWindowsVMAzureParams.MemoryGB) -Verbose
Write-Verbose -Message ("DiskOsGB" + $NewITDWindowsVMAzureParams.DiskOsGB) -Verbose
Write-Verbose -Message ("DiskDataGB " + $NewITDWindowsVMAzureParams.DiskDataGB) -Verbose
Write-Verbose -Message ("Subnet " + $NewITDWindowsVMAzureParams.Subnet) -Verbose
Write-Verbose -Message ("OS" + $NewITDWindowsVMAzureParams.OS) -Verbose
Write-Verbose -Message ("Environment" + $NewITDWindowsVMAzureParams.Environment) -Verbose
Write-Verbose -Message ("AppName" + $NewITDWindowsVMAzureParams.AppName) -Verbose
Write-Verbose -Message ("LicensingRestrictions" + $NewITDWindowsVMAzureParams.LicensingRestrictions) -Verbose
New-ITDWindowsVmAzureStep1 @NewITDWindowsVmAzureParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
@@ -0,0 +1,49 @@
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$FQDN
)
switch ($PSCmdlet.ParameterSetName) {
'ManualEntry' {
$NewITDWindowsVmAzureParams = @{
FQDN = $FQDN;
}
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
Write-Verbose -Message "New-ITDServiceNowSession" -Verbose
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
$NewITDWindowsVmAzureParams = @{
FQDN = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
AppName = ( (Get-ITDServiceNowRecord -Table cmdb_ci_service_auto -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).application_info).Name.display_value);
VMEnvironment = ( $Ritm.customvariable.environment.value );
}
}
}
Write-Verbose -Message "Connect to Azure using Service Principal" -Verbose
$tenantId = '2dea0464-da51-4a88-bae2-b3db94bc0c54'
$AppId = '60244573-7130-4026-9c6d-47de73f8ca29'
$SecureStringPwd = $Secret:azure_iaasserviceprincipal
$PSCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, ($SecureStringPwd | ConvertTo-SecureString -AsPlainText -Force)
Connect-AzAccount -ServicePrincipal -Credential $PSCredential -Tenant $tenantId
Write-Verbose -Message "NewITDWindowsVMAzureParams:" -Verbose
Write-Verbose -Message ("FQDN " + $NewITDWindowsVMAzureParams.FQDN) -Verbose
New-ITDWindowsVmAzureStep2 @NewITDWindowsVmAzureParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
@@ -0,0 +1,144 @@
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$FQDN,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$CPU = 1,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$MemoryGB = 4,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskOsGB = 50,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$DiskSwapGB = ($MemoryGB + 1),
[Parameter(ParameterSetName = 'ManualEntry')]
[int]
$DiskDataGB,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Subnet = '10.11.12.0/23',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$OS = 'Windows Server 2022 Datacenter',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$VMEnvironment = 'Test',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$Datacenter = 'Mandan',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$AppName = 'ITD-POC-zmeier',
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[int]
$StartupPriority = 5,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$LicensingRestrictions = "No Licensing Restrictions"
)
switch ($PSCMdlet.ParameterSetName) {
'ManualEntry' {
$NewITDWindowsVmVMwareParams = @{
FQDN = $FQDN;
CPU = $CPU;
MemoryGB = $MemoryGB;
DiskOsGB = $DiskOsGB;
DiskSwapGB = $DiskSwapGB;
DiskDataGB = $DiskDataGB;
Subnet = $Subnet;
OS = $OS;
VMEnvironment = $VMEnvironment;
Datacenter = $Datacenter;
AppName = $AppName;
StartupPriority = $StartupPriority;
LicensingRestrictions = $LicensingRestrictions;
}
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
$NewITDWindowsVmVMwareParams = @{
FQDN = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
CPU = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).processors );
MemoryGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).memory_gb );
DiskOsGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_1_os );
DiskSwapGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_2_swap_disk );
DiskDataGB = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).disk_3 );
Subnet = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).cidr_block).name.display_value;
OS = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).target_os_version_windows );
VMEnvironment = ( $Ritm.customvariable.environment.value );
Datacenter = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).data_center );
AppName = ( Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq "$FqdnFromSCTaskDescription" }).application_info).name.display_value;
StartupPriority = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).startup_priority );
LicensingRestrictions = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).licensing_restrictions );
}
}
}
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdiaasauto -Verbose
Write-Verbose -Message "Attempt server provisioning" -Verbose
Write-Host $NewITDWindowsVmVMwareParams
try {
New-ITDWindowsVmVMwareStep1 @NewITDWindowsVmVMwareParams -Credential $Secret:ndgov_svcitdiaasauto -Verbose
Write-Verbose -Message "New-ITDWindowsVmVMwareStep1 function completed"
$Step1Complete = $true
}
catch {
Write-Error -Message $error[0]
$Step1Complete = $false
throw
}
Write-Verbose -Message "Disconnect from vCenter" -Verbose
Disconnect-ITDvCenter
switch ($PSCmdlet.ParameterSetName) {
'FromSCTask' {
Write-Verbose -Message ("Update " + $SCTaskNum + " with Step 1 status") -Verbose
switch ($Step1Complete) {
$true {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = ("VMware build step 1 complete. `nPSU Job Id #" + $UAJob.Id)
}
}
$false {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = ("VMware build step 1 errored, needs human review. `nPSU Job Id #" + $UAJob.Id)
}
}
}
}
}
@@ -0,0 +1,87 @@
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTask')]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$FQDN,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$AppName,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$VMEnvironment
)
switch ($PSCMdlet.ParameterSetName) {
'ManualEntry' {
$NewITDWindowsVmVMwareStep2Params = @{
FQDN = $FQDN;
AppName = $AppName;
VMEnvironment = $VMEnvironment;
}
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
Write-Verbose -Message ("Ritm: " + $Ritm.Number) -Verbose
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
Write-Verbose -Message ("FqdnFromSCTaskDescription: " + ($SCTask.short_description).display_value.split(' ')[7] ) -Verbose
$NewITDWindowsVmVMwareStep2Params = @{
FQDN = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name );
VMEnvironment = ( ($Ritm.CustomVariable).environment.value );
AppName = ( (Get-ITDServiceNowRecord -Table cmdb_ci_service_auto -SysId ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).application_info).Name.display_value);
}
Write-Verbose -Message ("Params FQDN: " + $NewITDWindowsVmVMwareStep2Params.FQDN) -Verbose
}
}
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdiaasauto -Verbose
Write-Verbose -Message "Attempt VMware step 2" -Verbose
Write-Host $NewITDWindowsVmVMwareStep2Params
try {
New-ITDWindowsVmVMwareStep2 @NewITDWindowsVmVMwareStep2Params -Credential $Secret:ndgov_svcitdiaasauto -Verbose
Write-Warning -Message "New-ITDWindowsVmVMwareStep2 function completed"
$Step2Complete = $true
}
catch {
Write-Error -Message $error[0]
$Step2Complete = $false
throw
}
Write-Verbose -Message "Disconnect from vCenter" -Verbose
Disconnect-ITDvCenter
switch ($PSCmdlet.ParameterSetName) {
'FromSCTask' {
switch ($Step2Complete) {
$true {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = ("VM build step 2 complete. `nPSU Job Id #" + $UAJob.Id);
}
}
$false {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = ("VMware build step 2 errored, needs human review. `nPSU Job Id #" + $UAJob.Id)
}
}
}
}
}
@@ -0,0 +1,146 @@
<#
.SYNOPSIS
Processes automated server build tasks for Windows machines in ServiceNow, triggered via PowerShell Universal.
.DESCRIPTION
This script connects to the ServiceNow API, retrieves open catalog tasks that match a specific filter for automated server build tasks,
and processes them. This script is designed to run as a scheduled task. It can optionally filter tasks by a specific SCTask number.
.PARAMETER SCTaskNum
The ServiceNow task number to filter the tasks. If not provided, all tasks matching the filter will be processed.
.EXAMPLE
.\New-ITDWindowsVmBuildTask_Auto.ps1
This example runs the script and processes all open tasks that match the filter for automated server build tasks.
.EXAMPLE
.\New-ITDWindowsVmBuildTask_Auto.ps1 -SCTaskNum 'SCTASK0012345'
This example runs the script and processes only the task with the specified SCTask number.
.NOTES
Ensure that the ServiceNow instance URL and credentials are correctly configured in the New-ITDServiceNowSession function.
This script is not supported in Linux.
#>
Param(
[string]
$SCTaskNum
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
$Filter = 'active=true^short_descriptionSTARTSWITHAutomated Server Build Task for Windows Machine'
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter | Sort-Object Number
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum" -Verbose
$OpenTasks = $OpenTasks | Where-Object { $_.number.value -EQ $SCTaskNum }
}
$AllRitms = [System.Collections.ArrayList]@()
Write-Verbose -Message ("OpenTasks found: " + @($OpenTasks).Count) -Verbose
ForEach ($OpenTask in $OpenTasks) {
$PSUJob = $null
$SCTask = $null
$shortdescription = $null
$shortdescription_hostname = $null
$WorkNotesMsg = $null
$SCTaskNum = $OpenTask.number.Value
Write-Verbose -Message "Start $SCTaskNum" -Verbose
try {
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$shortdescription = $SCTask.short_description.display_value
$shortdescription_hostname = $shortdescription.split(' ')[7]
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
<#
If ($AllRitms | Where-Object { $_.number.display_value -EQ $SCTask.request_item.display_value }) {
Write-Verbose -Message ("Ritm already in memory") -Verbose
$Ritm = $AllRitms | Where-Object sys_id -EQ $SCTask.request_item.display_value
}
Else {
Write-Verbose -Message "Ritm is not in memory, retrieve it" -Verbose
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
$null = $AllRitms.Add($Ritm)
}
#>
# check for step messages in SCTask work_notes and determine next step
switch ($SCTask.work_notes.display_value) {
{ $_ -match "human review" } {
Write-Verbose -Message "Human review required, skipping" -Verbose
Break
}
{ $_ -match "build step 2 complete" } {
# execute Step 3
Write-Verbose -Message "Step 2 already complete, starting step 3" -Verbose
$PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVm_Step3.ps1" -SCTaskNum $SCTaskNum
#$WorkNotesMsg = ("VMware build Step 3 started.`nPSU Job Id #" + $PSUJob.Id)
Break
}
{ $_ -match "build Step 2 started"} {
Write-Verbose -Message "Step 2 already started, skipping" -Verbose
Break
}
{ $_ -match "build step 1 complete" } {
# execute Step 2
Write-Verbose -Message "Step 1 already complete, starting Step 2" -Verbose
# Determine if VMware or Azure and run appropriate build Step 2 function
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' {
$target_platform = "Azure"
Write-Verbose "Invoking PSUScript for Azure Step 2" -Verbose
$PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmAzure_Step2.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("VMware build Step 2 started.`nPSU Job Id #" + $PSUJob.Id)
}
'vmware' {
$target_platform = "VMware"
Write-Verbose "Invoking PSUScript for VMware Step 2" -Verbose
$PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmVMware_Step2.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("VMware build Step 2 started.`nPSU Job Id #" + $PSUJob.Id)
}
}
Break
}
{ $_ -match "build Step 1 started"} {
Write-Verbose -Message "Step 1 already started, skipping" -Verbose
Break
}
Default {
# execute Step 1
Write-Verbose -Message "No step messages found, starting Step 1" -Verbose
# Determine if VMware or Azure and run appropriate build function
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' {
$target_platform = "Azure"
Write-Verbose "Invoking PSUScript for Azure Step 1" -Verbose
$PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmAzure_Step1.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("Azure build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
}
'vmware' {
$target_platform = "VMware"
Write-Verbose "Invoking PSUScript for VMware Step 1" -Verbose
$PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmVMware_Step1.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("VMware build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
}
}
Break
}
}
}
catch {
Write-Error -Message $error[0]
}
If($null -eq $WorkNotesMsg){
# do nothing
} Else {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{work_notes = $WorkNotesMsg }
}
Write-Verbose -Message "End $SCTaskNum" -Verbose
}
#>
#Invoke-PSUScript -Name New-ITDWindowsVmVMware_Step1.ps1 -SCTaskNum "SCTASK0310457"
@@ -0,0 +1,126 @@
# used by both Azure and VMware build tasks
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, ParameterSetName = 'FromSCTASK')]
[string]
$SCTaskNum,
[Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
[string]
$FQDN
)
# get FQDN from SCTask/Ritm, or directly from user input
switch ($PSCmdlet.ParameterSetName) {
'ManualEntry' {
Write-Verbose -Message "FQDN manually entered"
}
'FromSCTask' {
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
"ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
}
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
Write-Verbose -Message ("Ritm: " + $Ritm.Number) -Verbose
$FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
Write-Verbose -Message ("FqdnFromSCTaskDescription: " + ($SCTask.short_description).display_value.split(' ')[7] ) -Verbose
$FQDN = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name ).tolower();
$OperatingSystem = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).operating_system
}
}
try {
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' { $target_platform = "Azure" }
'vmware' { $target_platform = "VMware" }
}
<# Is this needed?
$Ci = Get-ITDServiceNowRecord -Table cmdb_ci -Filter ("name=" + $FormHostName)
If ($Ci) {
Write-Verbose -Message ("Ci found, sys_id = " + $Ci.sys_id + ", name = " + $Ci.name + ", fqdn = " + $Ci.fqdn) -Verbose
}
Else {
# Ci does not exist
Write-Verbose -Message ("Ci not found") -Verbose
}
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 = 'Other' }
}
#>
Write-Verbose -Message "Confirm all required agents are running"
$ProcessList = @('ccmexec', 'cohesity*', 'nessus*', 'cortex*')
switch ($target_platform) {
'VMware' {
$ProcessList += 'vmtoolsd'
}
'Azure' {
Write-Verbose -Message "No Azure specific agents to check for" -Verbose
}
Default {
Write-Verbose -Message "no Ci means no platform check"
}
}
}
catch {
Write-Error $error[0]
}
If ( $FQDN -like "*.nd.gov" ) {
try {
$AgentCount = 0
$svcitdpsuwin = Get-ITDPassword -UserName ndgov\svcitdpsuwin -Title ndgov\svcitdpsuwin
$RunningProcess = Invoke-Command -Credential $svcitdpsuwin -ComputerName $FQDN -ErrorAction Stop -ScriptBlock {
Get-Process
}
If ($RunningProcess) {
ForEach ($ProcessName in $ProcessList) {
If ($RunningProcess -match $ProcessName) {
Write-Verbose -Message "Process $ProcessName found." -Verbose
$AgentCount = $AgentCount + 1
}
Else {
Write-Warning -Message "Process $ProcessName not found"
# do not increase agentcount count
}
}
}
}
catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
Write-Warning -Message "$FQDN unreachable via PSRemoting"
$BuildComplete = $false
}
}
Else {
Write-Verbose -Message ($SCTaskNum + $ComputerName + " is not nd.gov, manual agent validation required.") -Verbose
}
If ($AgentCount -ge @($ProcessList).count) {
Write-Verbose "All required processes running, Windows is ready for use. Update SCTask to notify physical/virtual hardware stakeholders." -Verbose
$work_notes = ("$target_platform $hardware_type $FQDN Windows Guest OS complete. `nPSU Job Id #" + $UAJob.Id)
$shortdescription = "$target_platform $hardware_type $FQDN Windows Guest OS complete."
Write-Verbose -Message "Work notes: $work_notes" -Verbose
Write-Verbose -Message "Short description: $shortdescription" -Verbose
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
work_notes = $work_notes;
close_notes = "$FQDN $target_platform Windows Guest OS complete.";
short_description = $shortdescription;
state = 'Closed Complete'
}
}
Write-Verbose -Message "End $SCTasknum" -Verbose
@@ -0,0 +1,96 @@
<#
.SYNOPSIS
Add Service Principal Name to a ITD AD Service Account
.DESCRIPTION
Add Service Principal Name to a ITD AD Service Account
.NOTES
example using setspn:
setspn.exe -s MSSQLSvc/test.nd.gov:1433 ndgov\svctest
setspn.exe -s MSSQLSvc/test:1433 ndgov\svctest
setspn.exe -s MSSQLSvc/test.nd.gov ndgov\svctest
setspn.exe -s MSSQLSvc/test ndgov\svctest
setspn.exe -s MSSQLSvc/test.nd.gov ndgov\svctest
.LINK
#>
[CmdletBinding()]
Param(
[string]
$SamAccountName,
[Parameter(HelpMessage = "Multiple entries can be submitted if the field loses focus, and you go back to it. For example, after each entry hit Tab, then Shift-Tab back.")]
[string[]]
$ServicePrincipalName = $null
)
Write-Verbose -Message "Prep Variables and Connections"
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" {
$ServiceNowEnvironment = 'Test'
}
"ITDWINAUTOP1" {
$ServiceNowEnvironment = 'Production'
}
}
$RequestedBy = $UAJob.Identity.Name # user that started the job
$PSUJobId = $UAJob.Id
$StartDateTime = Get-Date
Write-Verbose -Message "Find AD User" -Verbose
$ADUser = Get-ADUser -Identity $SamAccountName -ErrorAction Stop
Write-Verbose -Message "Add SPN(s)" -Verbose
try {
$ServicePrincipalName | ForEach-Object {
Write-Verbose -Message ("Attempt to add SPN value " + $_) -Verbose
$ADUser | Set-ADUser -ServicePrincipalNames @{Add=$_}
}
}
catch {
Write-Error $Error[0]
}
Start-Sleep -Seconds 2
Write-Verbose -Message "No errors when adding the SPNs, listing the SPNs here for human validation" -Verbose
$ValidateUser = Get-ADUser -Identity $SamAccountName -Properties ServicePrincipalNames | Select-Object SamAccountName, ServicePrincipalNames
$ValidateUser.ServicePrincipalNames
Write-Verbose -Message "Generate ServiceNow CHG" -Verbose
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred -Verbose
$NewITDServiceNowChangeRequestParams = @{
TemplateName = 'NDIT-SPS-Server Add/Chg/Del'
RequestedByUsername = $RequestedBy.split('@')[0] -replace 'prv';
Category = 'Systems Platforms - Systems';
Subcategory = 'Windows';
Impact = 3;
ShortDescription = "ServicePrincipalName added to ndgov\$SamAccountName - PSU Job Id $PSUJobId";
Description = "ServicePrincipalName added to ndgov\$SamAccountName - PSU Job Id $PSUJobId, see notes for details";
Justification = "ServicePrincipalName is required to be added to Active Directory Service Accounts by some applications";
Implementation = "PSUniversal execution";
RiskImpactAnalysis = "Low";
BackoutPlan = "Remove the new service principal name from the serviceprincipalname attribute."
TestPlan = "n/a"
WhoIsImpacted = "Windows System Administrators";
StartTime = $StartDateTime
EndTime = $StartDateTime.AddMinutes(1);
AssignmentGroup = 'NDIT-Computer Systems Windows';
ChangeManagerUsername = 'khellman';
ChangeCoordinatorUsername = 'gpgolberg';
AssignedToUsername = $RequestedBy.split('@')[0] -replace 'prv';
}
$CHG = New-ITDServiceNowChangeRequest @NewITDServiceNowChangeRequestParams -Verbose
$CHGNum = $CHG.Number.value
Write-Verbose -Message ("Completing SNow " + $CHG.Number.value) -Verbose
$CompleteITDServiceNowChangeRequestParams = @{
Number = $CHG.Number.value
CloseCode = "Successful"
CloseNotes = "ServicePrincipalNames added to ndgov\$SamAccountName - PSU Job Id $PSUJobId`n" + ($ServicePrincipalName | ForEach-Object {$_})
}
Complete-ITDServiceNowChangeRequest @CompleteITDServiceNowChangeRequestParams -Verbose
@@ -0,0 +1,9 @@
[CmdletBinding()]
Param(
[string]
$Identity
)
If($Identity){
Get-ADUser -Identity $Identity -Properties LockedOut,MemberOf
}
@@ -0,0 +1,30 @@
$Title = 'itdwinautot1.nd.gov'
$Username = 'svczmtest005'
$Credential = $Secret:svcitdiaasauto
$FullRecord = $false
ConvertTo-SecureString -String "things" -AsPlainText -Force
$Uri = 'https://itdpv.nd.gov/winapi/searchpasswords/?'
If ($Title) { $Uri += 'title=' + $Title + '&' }
If ($UserName) { $Uri += 'username=' + "$UserName" + '&' }
$Uri = $Uri.TrimEnd('&')
$InvokeResult = Invoke-RestMethod -Method Get -Uri $Uri -Credential $Credential
$OutResult = $InvokeResult | Select-Object PasswordListID, PasswordList, PasswordID, Title, Description, UserName, @{n = 'SecurePassword'; e = { $_.Password | ConvertTo-SecureString -AsPlainText -Force } }, AccountTypeId, AccountType
If (@($OutResult).count -eq 1) {
If ($PSCmdlet.ParameterSetName -eq "ToClipboard") {
$InvokeResult.Password | Set-Clipboard
}
If ($FullRecord) {
Write-Output $OutResult
}
Else {
$OutCred = New-Object System.Management.Automation.PSCredential($OutResult.UserName, $OutResult.SecurePassword)
Write-Output $OutCred
}
}
Else {
Write-Output $OutResult
}
@@ -0,0 +1,134 @@
<#
.SYNOPSIS
Creates an Active Directory user/service account for the nd.gov domain
.DESCRIPTION
Creates an Active Directory user/service account for the nd.gov domain.
.NOTES
The PasswordstateList parameter must be validated. If a Passwordstate Password List to the options, ensure that the ndgov\svcitdiaasauto Active Directory has modify access on the Password List.
Requires Integrated or Agent environment. If not chosen, an erroneous error is caused during the invocation of New-ITDADServiceAccount when the PSCredential object is created to be returned to the user, see below.
[error] Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "password" is null. Change the value of argument "password" to a non-null value."
The agent environment is selected to reduce parameter during script execution, and Run As Credential is enforced as svcitdpsuwin
.LINK
https://northdakota.service-now.com/kb_view.do?sysparm_article=KB0016867
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true,
HelpMessage = "Only nd.gov domain is supported at this time.")]
[ValidateSet("nd.gov")]
[string]
$DomainName = 'nd.gov',
[Parameter(Mandatory = $true,
HelpMessage = "This is the account name. This value will also be set on the Active Directory Surname attribute (GivenName or Surname are required for ServiceNow lookups)")]
[string]
$SamAccountName,
[Parameter(Mandatory = $true,
HelpMessage = "Will be set on the respective Passwordstate record property and Active Directory attribute. '1120' will automatically be appended to the entry.")]
[string]
$Description,
[Parameter(Mandatory = $true,
HelpMessage = "What goes into the Passwordstate record Title field. Generally a FQDN for the server that will use this service account.")]
[string]
$PasswordstateTitle,
[Parameter(Mandatory = $true,
HelpMessage = "The Passwordstate Password List where the credentials to be saved. Go here to retrieve the password for the new account.")]
[ValidateSet('CSRC', 'VMware_Systems','Peoplesoft Share PW')]
[string]
$PasswordstateList
)
Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose
$RequestedBy = $UAJob.Identity.Name # user that started the job
$PSUJobId = $UAJob.Id
$StartDateTime = (Get-Date)
$EndDateTime = $StartDateTime.AddMinutes(1)
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch ($UAJob.ComputerName) {
"ITDWINAUTOT1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_ActiveDirectory_Object_NewITDADServiceAccount_NPD"
$ServiceNowEnvironment = 'Test'
}
"ITDWINAUTOP1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_ActiveDirectory_Object_NewITDADServiceAccount_PRD"
$ServiceNowEnvironment = 'Production'
}
}
Write-Verbose -Message "fix samaccountname" -Verbose
$SamAccountName = $SamAccountName.Tolower()
# add to SQL
Write-Verbose -Message "Add request to SQL" -Verbose
$SqlQuery = "INSERT INTO [$SnapshotTable] (PSUJobId,RequestedBy,DateTime,Status,DomainName,SamAccountName,Description,PasswordstateTitle,PasswordstateList) Values ('$PSUJobId', '$RequestedBy', '$StartDateTime','Requested','$DomainName','$SamAccountName', '$Description', '$PasswordstateTitle', '$PasswordstateList');"
Write-Verbose -Message $SqlQuery -Verbose
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
# Do the work
Write-Verbose -Message "Create the account in Active Directory, and Passwordstate record" -Verbose
New-ITDADServiceAccount -SamAccountName $SamAccountName -Description $Description -PasswordstateList $PasswordstateList -PasswordstateTitle $PasswordstateTitle -Credential $Secret:ndgov_svcitdpsuad -Verbose
Write-Verbose -Message "Executing Get-ADUser -Identity $SamAccountName" -Verbose
# Validate the user
$ADUser = Get-ADUser -Identity $SamAccountName
If ($ADUser) {
Write-Output $ADUser
Write-Verbose -Message "Create CHG request for the work" -Verbose
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
$NewITDServiceNowChangeRequestParams = @{
TemplateName = 'NDIT-SPS-Server Add/Chg/Del'
RequestedByUsername = $RequestedBy.split('@')[0] -replace 'prv';
Category = 'Systems Platforms - Systems';
Subcategory = 'Windows';
Impact = 3;
ShortDescription = "New $DomainName Active Directory service account $SamAccountName created - PSU Job Id $PSUJobId";
Description = "New $DomainName Active Directory service account $SamAccountName created";
Justification = "New $DomainName Active Directory service account required for zero-trust policies, following guidelines found in KB0016867";
Implementation = "PSUniversal execution";
RiskImpactAnalysis = "Low";
BackoutPlan = "Delete the new user account"
TestPlan = "n/a"
WhoIsImpacted = "Windows System Administrators";
StartTime = $StartDateTime
EndTime = $StartDateTime.AddMinutes(1);
AssignmentGroup = 'NDIT-Computer Systems Windows';
ChangeManagerUsername = 'khellman';
ChangeCoordinatorUsername = 'gpgolberg';
AssignedToUsername = $RequestedBy.split('@')[0] -replace 'prv';
}
$CHG = New-ITDServiceNowChangeRequest @NewITDServiceNowChangeRequestParams -Verbose
$CHGNum = $CHG.Number.value
Write-Verbose -Message ("Completing SNow " + $CHG.Number.value) -Verbose
$CompleteITDServiceNowChangeRequestParams = @{
Number = $CHG.Number.value
CloseCode = "Successful"
CloseNotes = ("New $DomainName Active Directory account " + $obj.ADDomain + "\" + $obj.SamAccountName + " created.")
}
Complete-ITDServiceNowChangeRequest @CompleteITDServiceNowChangeRequestParams -Verbose
Write-Verbose -Message "Status Success" -Verbose
$SQLStatus = "Succcess"
}
Else {
Write-Verbose -Message "Status Failure" -Verbose
$SQLStatus = "Failure"
}
#>
Write-Verbose -Message "Update SQL with that CHG num and update Status" -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = '$SQLStatus', SNowCHGNum = '$CHGNum' WHERE PSUJobId = " + $PSUJobId)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
@@ -0,0 +1,31 @@
Param (
[string]
$PasswordstateList,
[string]
$PasswordstateTitle,
[string]
$Description,
[string]
$UserName
)
$Credential = $Secret:svcitdiaasauto
$NewITDPasswordParams = @{
PasswordList = $PasswordstateList;
Title = $PasswordstateTitle;
Description = $Description;
UserName = ("ndgov\$SamAccountName");
Credential = $Credential;
}
switch ($PSBoundParameters.Keys) {
PasswordStateNotes {
$NewITDPasswordParams.Notes = $PasswordstateNotes
}
}
$NewITDPasswordResult = New-ITDPassword @NewITDPasswordParams -ErrorAction Stop
@@ -0,0 +1 @@
# It all starts with a single line of powershell code.
@@ -0,0 +1,31 @@
Param(
[Parameter(Mandatory = $true)]
[string[]]
$ComputerName = $null,
[ValidateSet('All Day Every Day',
'Weekdays 700 to 1800',
'All Week 500 to 2300'
)]
[string]
$SupportHours
)
$Func = {
param($C, $SwSupportHours)
Write-Verbose -Message "Add to Solarwinds" -Verbose
Import-SWDiscovery -ComputerName $C -Integration ServiceNow
Start-Sleep -Seconds 10
Write-Verbose -Message "Set Solarwinds node custom properties if parameter exists" -Verbose
If($PSBoundParameters.ContainsKey('SupportHours')){
Write-Verbose -Message "SupportHours $SwSupportHours." -Verbose
Set-SWNodeCustomProperty -ComputerName $C -Property SupportHours -Value $SwSupportHours
}
}
$ComputerName | ForEach-Object {
Invoke-Command -ComputerName itdslrwnds.nd.gov -ScriptBlock $Func -ArgumentList $_,$SupportHours -Credential $Secret:ndgov_svcitdiaasauto
}
@@ -0,0 +1,10 @@
Param(
[Parameter(Mandatory = $true)]
[string[]]
$ComputerName
)
ForEach ($cn in $ComputerName) {
Write-Verbose -Message "Attempt Solarwinds removal for $cn" -Verbose
Remove-ITDSolarwindsNode -ComputerName $cn -Credential $Secret:ndgov_svcitdiaasauto -Verbose
}
@@ -0,0 +1,38 @@
Write-Verbose -Message "Prepare variables based on PSU server" -Verbose
switch($UAJob.ComputerName){
"ITDWINAUTOT1" {
$ServiceNowEnvironment = "Test"
}
"ITDWINAUTOP1" {
$ServiceNowEnvironment = "Production"
}
}
New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
<#
Write-Verbose -Message "Retrieve List of all Server Build Request request items from ServiceNow where closed_at is Yesterday and request_type is Change" -Verbose
$Filter = 'cat_item=c64e27af47244610b7853238436d435d^variables.3bf9fc3b47240a10b7853238436d430b=Change^closed_atONYesterday@javascript:gs.beginningOfYesterday()@javascript:gs.endOfYesterday()'
####### 'cat_item=c64e27af47244610b7853238436d435d^variables.3bf9fc3b47240a10b7853238436d430b=Change^closed_atONYesterday@javascript:gs.beginningOfYesterday()@javascript:gs.endOfYesterday()'
$CompletedRitms = Get-ITDServiceNowRecord -ItemType 'Request Item' -Filter $Filter
Write-Verbose -Message ("Found " + @($CompletedRitms).count + " completed Ritms.")
#>
$CompletedRitms = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number RITM0269022
ForEach($Ritm in $CompletedRITMs){
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number ($Ritm.number.value) -IncludeCustomVariable -IncludeVariableSet
# loop each VM row
ForEach($row in $Ritm.VariableSet){
# resolve sys_id to host name
$CmdbCi = Get-ITDServiceNowRecord -Table cmdb_ci -SysId $row.host_name_ref
Write-Verbose -Message ("Start " + $Ritm.number.value + " server " + $row.host_name_ref + ', ' + $CmdbCi.fqdn.display_value) -Verbose
# run solarwinds import
$Func = {
param ($c)
Write-Verbose -Message "Attempting to import $c to Solarwinds"
Import-SWDiscovery -ComputerName $c
}
Invoke-Command -ComputerName itdslrwnds.nd.gov -ScriptBlock $Func -ArgumentList $CmdbCi.fqdn.display_value -Credential $Secret:ndgov_svcitdiaasauto
}
}
@@ -0,0 +1,34 @@
Param(
[string]
$Name,
[ValidateSet(
'Infra-ActiveDirectory.Object',
'Infra-Azure.VirtualMachine',
'Infra-Monitoring-Solarwinds',
'Infra-VMware.Administration',
'Infra-VMware.VirtualMachine',
'Infra-VMware.Snapshot',
'ITD-WindowsServer.FileManagement',
'ITD-WindowsServer.General',
'ITD-WindowsServer.Lifecycle',
'Shared-Powerschool'
)]
[string]
$Path
)
switch ($Path){
<# example switch condition and actions
{ $_ -like "App-XXXXX"} {$TagNamesEnforced = @('Shared-XXXXX_Modify)}
#>
{ $_ -eq "Infra-ActiveDirectory.Object" } { $TagNamesEnforced = @('ITD-WindowsServer_Modify') }
{ $_ -like "Infra-Azure.*"} {$TagNamesEnforced = @('Infra-VMware_Modify')}
{ $_ -like "Infra-Monitoring-Solarwinds*" } { $TagNamesEnforced = @('ITD-WindowsServer_Modify') }
{ $_ -like "Infra-VMware*" } { $TagNamesEnforced = @('Infra-VMware_Modify') }
{ $_ -like "ITD-WindowsServer*" } { $TagNamesEnforced = @('ITD-WindowsServer_Modify') }
{ $_ -like "Shared-PowerSchool*" } { $TagNamesEnforced = @('Shared-PowerSchool_Modify') }
}
New-PSUScript -Name $Name -Path "$Path\$Name" -Tag @($TagNamesEnforced) -ScriptBlock {# It all starts with a single line of powershell code.
}
@@ -0,0 +1,42 @@
#######
Write-Verbose -Message "Determine if ITD_PwshGallery is registered" -Verbose
If(Get-PSRepository -Name ITD_PwshGallery -ErrorAction SilentlyContinue){
Write-Verbose -Message "ITD_PwshGallery found." -Verbose
} Else {
$RegisterPSRepositoryParams = @{
Name = 'ITD_PwshGallery';
InstallationPolicy = 'Trusted';
SourceLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
PublishLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
ScriptSourceLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
ScriptPublishLocation = 'https://powershell.nd.gov/ITD_PwshGallery/nuget/';
}
Register-PSRepository @RegisterPSRepositoryParams
}
Write-Verbose -Message "Retrieve list of all available modules and versions"
$ITDModules = Find-Module -Name "ITD.*" -Repository ITD_PwshGallery
Write-Verbose -Message "Compare local module versions to repository versions, and update if needed"
ForEach($ITDModule in $ITDModules){
$VersionsAvailable = $null
$MostRecentVersion = $null
$RepoVersion = $null
$VersionsAvailable = Get-Module -Name $ITDModule.name -ListAvailable
$MostRecentVersion = $VersionsAvailable | Sort-Object Version -Descending | Select -First 1
$RepoVersion = $ITDModule.Version
If($null -eq $MostRecentVersion) {
Write-Verbose -Message ($ITDModule.Name + " was not found locally, installing module now.") -Verbose
Install-Module -Name $ITDModule.Name -Scope AllUsers -Repository ITD_PwshGallery
} Else {
Write-Verbose -Message ($ITDModule.Name + " was found locally, comparing versions and updating if needed..") -Verbose
Write-Host -Message ($ITDModule.Name)
Write-Host -Message ("Local version is " + $MostRecentVersion.Version)
Write-Host -Message ("The Repo version is " + $RepoVersion)
Write-Host -Message ("")
Update-Module -Name $ITDModule.Name -Scope AllUsers -Verbose
}
}
@@ -0,0 +1 @@
# It all starts with a single line of powershell code.
@@ -0,0 +1,131 @@
<#
.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
#>
<# Scheduled Task metadata
General
Get IPs for PA
run as ndgov\!itdvcenterppa
run whether user is logged on or not
Triggers
Daily, 11am
Daily, 11pm
Actions
old-C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noninteractive -file "C:\itdscript\GetIPs.ps1"
new-"C:\Program Files\PowerShell\7\pwsh.exe" -noninteractive -file "F:\GetVMwareVMGuestIPsForPA\GetVMwareVMGuestIPsForPA.ps1"
Settings
allow task to be run on demand
stop the task if it runs longer than 1 hour -eq $true
if the running task does not end when requested, force it to stop
#>
$TimeStamp = Get-Date -UFormat "%Y%m%d%H%M%S"
#Connect
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmvcauto
##Windows
#Output File
$OutFileWin = "c:\inetpub\wwwroot\Win.txt"
#$Date = Get-Date -UFormat "%Y%m%d%H%M%S"
Get-Item -Path $OutFileWin | Copy-Item -Destination "F:\GetVMwareVMGuestIPsForPA\Backup\Win\$Timestamp-Win.txt"
Remove-Item $OutFileWin
Start-Sleep -Seconds 5
#Get Powered On VM's
$vmwin = get-VM | Where-Object { $_.PowerState -eq "PoweredOn" `
-and ($_.GuestID -eq "windows7Guest" `
-or $_.GuestID -eq "windows7_64Guest" `
-or $_.GuestID -eq "windows7Server64Guest" `
-or $_.GuestID -eq "windows8_64Guest" `
-or $_.GuestID -eq "windows8Server64Guest" `
-or $_.GuestID -eq "windows9Server64Guest" `
-or $_.GuestID -eq "winLonghorn64Guest" `
-or $_.GuestID -eq "winLonghornGuest" `
-or $_.GuestID -eq "winNetStandardGuest" `
-or $_.GuestID -eq "winNetEnterpriseGuest" `
-or $_.GuestID -eq "windows9_64Guest" `
-or $_.GuestID -eq "windows2019srv_64Guest" `
-or $_.GuestID -eq "windows2019srvNext_64Guest") }
$vmviewwin = $vmwin | Get-View
$Outputwin = ""
#Loop through VM's, NIC's, and IP addresses.
Foreach ($v in $vmviewwin) {
Foreach ($nic in $v.Guest.Net) {
Foreach ($IP in $nic.IPAddress) {
If ($IP -notlike "fe80*" -and $IP -notlike "192.168.*" -and $IP -notlike "172.16*") {
$OutputWin += $IP + "`n"
}
}
}
}
#If ($Outputwin -ne "") {$OutputWin | Out-File $OutFileWin -Encoding utf8 -NoNewline}
If ($Outputwin -ne "") { $OutputWin | Out-File $OutFileWin -Encoding ASCII -NoNewline }
##Linux
#Output File
$OutFileLin = "c:\inetpub\wwwroot\Lin.txt"
$Date = Get-Date -UFormat "%Y%m%d%H%M%S"
Get-Item -Path $OutFileLin | Copy-Item -Destination "F:\GetVMwareVMGuestIPsForPA\Backup\Lin\$Timestamp-Lin.txt"
Remove-Item $OutFileLin
Start-Sleep -Seconds 5
#Get Powered On VM's
$vmLin = get-VM | Where-Object { $_.PowerState -eq "PoweredOn" `
-and ($_.GuestID -eq "centos6_64Guest" `
-or $_.GuestID -eq "centos64Guest" `
-or $_.GuestID -eq "centos7_64Guest" `
-or $_.GuestID -eq "oracleLinux64Guest" `
-or $_.GuestID -eq "oracleLinux7_64Guest" `
-or $_.GuestID -eq "rhel4Guest" `
-or $_.GuestID -eq "rhel5Guest" `
-or $_.GuestID -eq "rhel5_64Guest" `
-or $_.GuestID -eq "rhel6Guest" `
-or $_.GuestID -eq "rhel6_64Guest" `
-or $_.GuestID -eq "rhel7_64Guest" `
-or $_.GuestID -eq "rhel8_64Guest" `
-or $_.GuestID -eq "rhel9_64Guest" `
-or $_.GuestID -eq "sles11_64Guest" `
-or $_.GuestID -eq "sles12_64Guest" `
-or $_.GuestID -eq "ubuntu64Guest") }
$vmviewlin = $vmLin | Get-View
$OutputLin = ""
#Loop through VM's, NIC's, and IP addresses.
Foreach ($v in $vmviewlin) {
Foreach ($nic in $v.Guest.Net) {
Foreach ($IP in $nic.IPAddress) {
If ($IP -notlike "fe80*" -and $IP -notlike "192.168.*" -and $IP -notlike "172.16*") {
$OutputLin += $IP + "`n"
}
}
}
}
#If ($OutputLin -ne "") {$OutputLin | Out-File $OutFileLin -Encoding utf8 -NoNewline}
If ($OutputLin -ne "") { $OutputLin | Out-File $OutFileLin -Encoding ASCII -NoNewline }
Disconnect-ITDvCenter
@@ -0,0 +1,67 @@
<# This is how VMware data is sent to Billing
Scheduled Task metadata
General
Old-VMware Billing
run as ndgov\!itdvcenterscript (required for SQL Database access)
run whether user is logged on or not
Triggers
Daily, 5am
Actions
old-C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noninteractive -file "C:\itdscript\vmconfig.ps1"
new-"C:\Program Files\PowerShell\7\pwsh.exe" -noninteractive -file "F:\SyncVMwareVMsToSql\SyncVMwareVMsToSql.ps1"
"C:\Program Files\PowerShell\7\pwsh.exe" -noninteractive -file "F:\SyncVMwareVMsToSql\SyncVMwareVMsToSql.ps1"
newV3 - PSUniversal script and schedule
Settings
allow task to be run on demand
stop the task if it runs longer than 1 hour -eq $true
if the running task does not end when requested, force it to stop
SQL Query to check for most recent 2500 records
SELECT TOP (2500) [ServerName]
,[SnapshotDate]
,[VMName]
,[Memory_MB]
,[Num_VCPU]
,[Disk_MB]
,[ESXHostName]
FROM [ITD-SRS-Billing].[dbo].[VMWare_VCenter_VMs]
ORDER BY SnapshotDate DESC, VMName ASC
#>
$TimeStamp = Get-Date -UFormat "%Y%m%d%H%M%S"
#Start-Transcript F:\SyncVMwareVMsToSql\Logs\SyncVMwareVMsToSql-$Timestamp.log
Write-Verbose -Message "Connect to vCenter" -Verbose
Set-PowerCLIConfiguration -DefaultVIServerMode multiple -Scope Session -Confirm:$false
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmvcauto
Write-Verbose -Message "Get current virtual machines, minus filters"
$Datacenters = Get-Datacenter | Where-Object {$_.Name -notlike "*Normandy*" -and $_.Name -notlike "*Vantis*"}
$VMs = $Datacenters | Get-VM | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" -and $_.Name -notlike "itdzmtest*"} | Select Name, NumCPU, @{label="MemoryMB"; expression={$_.MemoryGB * 1024}}, @{label="HardDiskSizeGB"; expression={(Get-HardDisk -VM $_ | Measure-Object -Sum CapacityGB).Sum * 1024}}, VMHost | Sort-Object Name
Write-Verbose "Prep SQL connection" -Verbose
$SqlServer = "itdsql22p1.nd.gov\SQL22P1"
$Database = "ITD-SRS-Billing"
$Date = "'" + (Get-Date).ToString('yyyy/MM/dd') + "'"
Write-Verbose -Message "Remove today's entries from SQL if already there"
$SqlQuery = "delete from [VMware_VCenter_VMs] where snapshotdate = $Date;"
Invoke-SQLCmd -ServerInstance $SqlServer -Database $Database -Query $SqlQuery
Write-Verbose -Message "Start loop to create new record for each VM found" -Verbose
foreach($VM in $VMs) {
Write-Verbose -Message ("Begin " + $VM.Name)
$VMName = "'" + $VM.Name + "'"
$VMMemoryMB = $VM.MemoryMB
$VMNumCPU = $VM.NumCPU
$VMHardDiskSizeGB = $VM.HardDiskSizeGB
$VMHost = "'" + $VM.VMHost + "'"
$SqlQuery ="INSERT INTO [VMware_VCenter_VMs] (ServerName, SnapshotDate, VMName, Memory_MB, Num_VCPU, Disk_MB, ESXHostName) Values ('None', $Date, $VMName, $VMMemoryMB, $VMNumCPU, $VMHardDiskSizeGB, $VMHost);"
Invoke-SQLCmd -ServerInstance $SqlServer -Database $Database -Query $SqlQuery
}
#Stop-Transcript
Disconnect-ITDvCenter
@@ -0,0 +1,133 @@
<#
.SYNOPSIS
Creates a vCenter scheduled task that will create a virtual machine snapshot.
.DESCRIPTION
Creates a vCenter scheduled task that will create a virtual machine snapshot.
.NOTES
.LINK
https://northdakota.service-now.com/nav_to.do?uri=kb_knowledge.do?sysparm_query=number=KB0017146
#>
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
HelpMessage = "The VMware virtual machine name. This is most commonly the FQDN. You can verify the virtual machine name by logging into vCenter. Multiple entries can be submitted if the field loses focus, and you go back to it. For example, after each entry hit Tab, then Shift-Tab back."
)]
[string[]]
$VMName,
[Parameter(Mandatory = $true,
HelpMessage = "The DateTime you want the snapshot to occur.")]
[datetime]
$DateTime = (Get-Date),
[Parameter(Mandatory = $true,
HelpMessage = "How many hours the snapshot will exist. The snapshot will be automatically deleted after the duration. Maximum value is 72 hours.")]
[ValidateRange(1, 72)]
[int]
$DurationHours = 4,
[Parameter(HelpMessage = "Email address that you want vCenter to notify when the snapshot is taken. Multiple entries can be submitted if the field loses focus, and you go back to it. For example, after each entry hit Tab, then Shift-Tab back.")]
[string[]]
$Email
)
Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose
$RequestedBy = $UAJob.Identity.Name # user that started the job
$PSUJobId = $UAJob.Id
$StartDateTime = $DateTime
$EndDateTime = $StartDateTime.AddHours($DurationHours)
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch($UAJob.ComputerName){
"ITDWINAUTOT1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_NPD"
}
"ITDWINAUTOP1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_PRD"
}
}
$StartDateTimeSql = $StartDateTime.ToString('yyyy/MM/dd HH:mm:ss')
$EndDateTimeSql = $EndDateTime.ToString('yyyy/MM/dd HH:mm:ss')
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmsnapmgr
Write-Verbose -Message "After Connect vCenter" -Verbose
ForEach ($name in $VMName) {
Write-Verbose -Message ("Add record to SQL") -Verbose
$SqlQuery = "INSERT INTO [$SnapshotTable] (VMName, DateTime, RequestedBy, DurationHours,Status,ExpireDateTime,NotifyEmail,PSUJobIdRequest) Values ('$Name', '$StartDateTimeSql', '$RequestedBy', $DurationHours, 'Requested', '$EndDateTimeSql','$Email','$PSUJobId');SELECT SCOPE_IDENTITY();"
Write-Verbose -Message $SqlQuery -Verbose
$SnapshotId = (Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose).Column1
Write-Verbose -Message ("Snapshot ID is $SnapshotId") -Verbose
Write-Verbose -Message "Get SQL record" -Verbose
$SqlQuery = "SELECT [ID],[VMName],[DateTime],[RequestedBy],[DurationHours],[Status],[NotifyEmail],[TakenDateTime],[ExpireDateTime],[DeleteDateTime] FROM [ITD-Systems-Automation].[dbo].[$SnapshotTable] WHERE ID='$SnapshotId'"
Write-Verbose -Message $SqlQuery -Verbose
$SqlRecord = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
Write-Verbose -Message $SqlRecord -Verbose
Write-Verbose -Message ("Determine description metadata") -Verbose
$MetadataObj = @{
Id = [int]$SnapshotId;
Taken = $StartDateTime;
Expire = $EndDateTime;
RequestedBy = $RequestedBy;
DurationHours = $DurationHours;
PSUJobIdRequest = $PSUJobId;
}
Write-Verbose -Message ("Create VM Scheduled Task for Snapshot " + $SnapshotId) -Verbose
$NewITDVMwareVMSnapshotTaskParams = @{
VMName = $name;
Name = ("AutoSnap_" + $SnapshotId)
Description = $MetadataObj | ConvertTo-Json
DateTime = $StartDateTime;
}
switch ($PSBoundParameters.Keys) {
Email {
$NewITDVMwareVMSnapshotTaskParams.Email = $Email
}
}
try {
New-ITDVMwareVMSnapshotTaskV3 @NewITDVMwareVMSnapshotTaskParams -Verbose -ErrorAction Stop
Write-Verbose -Message ("Setting SQL status to Scheduled") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Scheduled' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
Write-Verbose -Message ($NewITDVMwareVMSnapshotTaskParams.Name + " has been scheduled.") -Verbose
}
catch {
Write-Verbose -Message "ObjectNotFound Error" -Verbose
switch ($Error[0].Exception.ErrorCategory) {
'ObjectNotFound' {
# update SQL with error
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " has failed, ObjectNotFound.") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Failed-VMNotFound' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
'Default' {
# update SQL with error
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " has failed.") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Failed-GenericError' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
}
Write-Error -Message $Error[0]
}
}
Disconnect-ITDvCenter
# Write-Verbose -Message ("If scheduled task is created successfully, create SNow CHG for this, using scheduled StartDateTime... work TBD") -Verbose
@@ -0,0 +1,59 @@
## TO-DO: update SQL status to Expired-Alerted when a ticket is created, so duplicate tickets are not generated
[CmdletBinding()]
param (
[string]
$VMName,
[int]
$Id, # ??
[switch]
$WhatIf
)
Write-Verbose -Message "Connect to vCenter and ServiceNow"
New-ITDServiceNowSession -Environment Production -Credential $Secret:SnowVMCred
Connect-ITDvCenter -Credential $Secret:svcitdiaasauto
# find all VMs, with VMName if entered
If ($PSBoundParameters.ContainsKey('VMName')) {
Write-Verbose -Message "VMname parameter found $VMName" -Verbose
$VMs = Get-VM -Name $VMName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
Else {
Write-Verbose -Message "VMname parameter not found" -Verbose
$VMs = Get-VM | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
# find expired snapshots of the VMs
If ($PSBoundParameters.ContainsKey('Id')) {
Write-Verbose -Message "ID parameter found $Id" -Verbose
$AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -Like "AutoSnap_$Id*"
}
Else {
Write-Verbose -Message "ID parameter not found" -Verbose
$AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -Like "AutoSnap_*"
}
ForEach ($Snapshot in $AllSnapshots) {
$SnapshotObj = $Snapshot.Description | ConvertFrom-Json
If ( $SnapshotObj.Expire -lt (Get-Date).AddHours(-24) ) {
$NewITDServiceNowIncidentParams = @{
CallerUsername = 'svcvmwareadm';
ShortDescription = ("VMware Snapshot #" + $SnapshotObj.Id + " cleanup failure.");
Description = ("VMware Snapshot #" + $SnapshotObj.ID + " cleanup failure. Snapshot expired more than 24 hours ago, but it still exists.");
Impact = 3;
Urgency = 3;
Category = 'Systems Platforms - Systems';
Subcategory = 'VMware';
AssignmentGroup = 'NDIT-Computer Systems Windows';
}
New-ITDServiceNowIncident @NewITDServiceNowIncidentParams
}
}
Disconnect-ITDvCenter
@@ -0,0 +1,133 @@
<#####
.SYNOPSIS
Creates a vCenter scheduled task that will create a virtual machine snapshot.
.DESCRIPTION
Creates a vCenter scheduled task that will create a virtual machine snapshot.
.NOTES
.LINK
https://northdakota.service-now.com/kb_view.do?sysparm_article=KB0017146
#>
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
HelpMessage = "The VMware virtual machine name. This is most commonly the FQDN. You can verify the virtual machine name by logging into vCenter. Multiple entries can be submitted if the field loses focus, and you go back to it. For example, after each entry hit Tab, then Shift-Tab back."
)]
[string[]]
$VMName = $null,
[Parameter(Mandatory = $true,
HelpMessage = "The DateTime you want the snapshot to occur.")]
[datetime]
$DateTime = (Get-Date),
[Parameter(Mandatory = $true,
HelpMessage = "How many hours the snapshot will exist. The snapshot will be automatically deleted after the duration. Maximum value is 72 hours.")]
[ValidateRange(1, 72)]
[int]
$DurationHours = 4,
[Parameter(HelpMessage = "Email address that you want vCenter to notify when the snapshot is taken. Multiple entries can be submitted if the field loses focus, and you go back to it. For example, after each entry hit Tab, then Shift-Tab back.")]
[string[]]
$Email = $null
)
Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose
$RequestedBy = $UAJob.Identity.Name # user that started the job
$PSUJobId = $UAJob.Id
$StartDateTime = $DateTime
$EndDateTime = $StartDateTime.AddHours($DurationHours)
Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
switch($UAJob.ComputerName){
"ITDWINAUTOT1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_NPD"
}
"ITDWINAUTOP1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_PRD"
}
}
$StartDateTimeSql = $StartDateTime.ToString('yyyy/MM/dd HH:mm:ss')
$EndDateTimeSql = $EndDateTime.ToString('yyyy/MM/dd HH:mm:ss')
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmsnapmgr
Write-Verbose -Message "After Connect vCenter" -Verbose
ForEach ($name in $VMName) {
Write-Verbose -Message ("Add record to SQL") -Verbose
$SqlQuery = "INSERT INTO [$SnapshotTable] (VMName, DateTime, RequestedBy, DurationHours,Status,ExpireDateTime,NotifyEmail,PSUJobIdRequest) Values ('$Name', '$StartDateTimeSql', '$RequestedBy', $DurationHours, 'Requested', '$EndDateTimeSql','$Email','$PSUJobId');SELECT SCOPE_IDENTITY();"
Write-Verbose -Message $SqlQuery -Verbose
$SnapshotId = (Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose).Column1
Write-Verbose -Message ("Snapshot ID is $SnapshotId") -Verbose
Write-Verbose -Message "Get SQL record" -Verbose
$SqlQuery = "SELECT [ID],[VMName],[DateTime],[RequestedBy],[DurationHours],[Status],[NotifyEmail],[TakenDateTime],[ExpireDateTime],[DeleteDateTime] FROM [ITD-Systems-Automation].[dbo].[$SnapshotTable] WHERE ID='$SnapshotId'"
Write-Verbose -Message $SqlQuery -Verbose
$SqlRecord = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
Write-Verbose -Message $SqlRecord -Verbose
Write-Verbose -Message ("Determine description metadata") -Verbose
$MetadataObj = @{
Id = [int]$SnapshotId;
Taken = $StartDateTime;
Expire = $EndDateTime;
RequestedBy = $RequestedBy;
DurationHours = $DurationHours;
PSUJobIdRequest = $PSUJobId;
}
Write-Verbose -Message ("Create VM Scheduled Task for Snapshot " + $SnapshotId) -Verbose
$NewITDVMwareVMSnapshotTaskParams = @{
VMName = $name;
Name = ("AutoSnap_" + $SnapshotId)
Description = $MetadataObj | ConvertTo-Json
DateTime = $StartDateTime;
}
switch ($PSBoundParameters.Keys) {
Email {
$NewITDVMwareVMSnapshotTaskParams.Email = $Email
}
}
try {
New-ITDVMwareVMSnapshotTaskV3 @NewITDVMwareVMSnapshotTaskParams -Verbose -ErrorAction Stop
Write-Verbose -Message ("Setting SQL status to Scheduled") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Scheduled' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
Write-Verbose -Message ($NewITDVMwareVMSnapshotTaskParams.Name + " has been scheduled.") -Verbose
}
catch {
Write-Verbose -Message "ObjectNotFound Error" -Verbose
switch ($Error[0].Exception.ErrorCategory) {
'ObjectNotFound' {
# update SQL with error
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " has failed, ObjectNotFound.") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Failed-VMNotFound' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
'Default' {
# update SQL with error
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " has failed.") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Failed-GenericError' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
}
Write-Error -Message $Error[0]
}
}
Disconnect-ITDvCenter
# Write-Verbose -Message ("If scheduled task is created successfully, create SNow CHG for this, using scheduled StartDateTime... work TBD") -Verbose
@@ -0,0 +1,99 @@
[CmdletBinding()]
param (
[string]
$VMName,
[int]
$Id,
[switch]
$WhatIf
)
$PSUJobId = $UAJob.Id
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmsnapmgr
Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose
switch($UAJob.ComputerName){
"ITDWINAUTOT1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_NPD"
}
"ITDWINAUTOP1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_PRD"
}
}
# find all VMs, with VMName if entered
If ($PSBoundParameters.ContainsKey('VMName')) {
Write-Verbose -Message "VMName parameter found $VMName" -Verbose
$VMs = Get-VM -Name $VMName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
Else {
$VMs = Get-VM | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
# find expired snapshots of the VMs
If ($PSBoundParameters.ContainsKey('Id')) {
Write-Verbose -Message "ID parameter found $Id" -Verbose
$AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -EQ "AutoSnap_$Id"
}
Else {
$AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -Like "AutoSnap_2*" ##### Remove the '2' after SharePoint snapshots are all deleted
}
ForEach ($Snapshot in $AllSnapshots) {
Write-Verbose -Message ("Start Snapshot " + $Snapshot.Description) -Verbose
$SnapshotObj = $null
$SnapshotObj = $Snapshot.Description | ConvertFrom-Json
If ($null -ne $SnapshotObj -and $SnapshotObj.Expire -lt (Get-Date)) {
# remove snapshot if expired
If ($WhatIf) {
Write-Verbose -Message ("What if: Performing the operation Remove-Snapshot on Snapshot " + $Snapshot.Name) -Verbose
}
Else {
Write-Verbose -Message ("VMName: " + $Snapshot.VM.Name + " / Snapshot ID: " + $SnapshotObj.Id + " -- attempting removal") -Verbose
# update SQL status to "Delete-Attempted"
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Delete-AutoAttempt', PSUJobIdDelete = '$PSUJobId' WHERE ID = " + $Snapshot.Name.split('_')[1])
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
# Remove Snapshot
$Snapshot | Remove-Snapshot -Confirm:$false -Verbose
# confirm snapshot is truly gone, then update sql with results
If (Get-VM -Name $Snapshot.VM.Name | Get-Snapshot -Id $SnapshotObj.Id -ErrorAction SilentlyContinue) {
$RemoveStatus = $false
}
Else {
# snapshot does not exist
$RemoveStatus = $true
}
# update SQL
switch ($RemoveStatus) {
$true {
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Deleted-AutoSuccess' WHERE ID = " + $Snapshot.Name.split('_')[1])
}
$false {
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Deleted-AutoFailure' WHERE ID = " + $Snapshot.Name.split('_')[1])
}
}
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
}
Else {
# do nothing
Write-Verbose -Message ("VMName: " + $Snapshot.VM.Name + " / Snapshot ID: " + $SnapshotObj.Id + " has not expired.") -Verbose
}
}
Disconnect-ITDvCenter
@@ -0,0 +1,3 @@
## To-do: Remove vCenter scheduled tasks for snapshots that are more than 30 days old.
# still need to do this
@@ -0,0 +1,8 @@
# It all starts with a single line of powershell code. TEST TEST TEST moar TEST
Write-Verbose -Message "Start Test-vCenterConnection.ps1" -Verbose
Write-Host $Secret:svcitdiaasauto.username
Connect-ITDvCenter -Credential $Secret:svcitdiaasauto
Get-Datacenter
Disconnect-ITDvCenter
Write-Verbose -Message "End Test-vCenterConnection.ps1" -Verbose
#
@@ -0,0 +1,203 @@
[CmdletBinding()]
param (
[int]
$Id
)
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmsnapmgr
Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose
switch($UAJob.ComputerName){
"ITDWINAUTOT1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_NPD"
}
"ITDWINAUTOP1" {
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_PRD"
}
}
# get list of All vCenter Scheduled Tasks
$si = Get-View ServiceInstance
$scheduledTaskManager = Get-View $Si.Content.ScheduledTaskManager
Write-Verbose -Message ("Gathering all scheduled tasks with AutoSnap in the task name, this will take some time")
$AllScheduledTasks = Get-View -Id $scheduledTaskManager.ScheduledTask | Where-Object { $_.Info.Name -like "AutoSnap*" }
Write-Verbose -Message "Get SQL records with status of Scheduled" -Verbose
# get list of Scheduled from database
$SqlQuery = "SELECT [ID],[VMName],[DateTime],[RequestedBy],[DurationHours],[Status],[NotifyEmail],[TakenDateTime],[ExpireDateTime],[DeleteDateTime] FROM [ITD-Systems-Automation].[dbo].[$SnapshotTable] WHERE Status = 'Scheduled'"
$SqlRecords = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
switch ($PSBoundParameters.Keys) {
Id {
Write-Verbose -Message "Narrowing results to Id parameter value of $Id" -Verbose
$SqlRecords = $SqlRecords | Where-Object Id -EQ "$Id"
}
}
Write-Verbose -Message ("Found " + @($SqlRecords).count + " snapshots with Scheduled status") -Verbose
Write-Verbose -Message "Start Scheduled > Taken Loops"
ForEach ($SqlRecord in @($SqlRecords) ) {
$Snapshot = $null
Write-Verbose -Message ("Start AutoSnap_" + $SqlRecord.Id) -Verbose
$Snapshot = Get-VM -Name $SqlRecord.VMName | Get-Snapshot -Name ("AutoSnap_" + $SqlRecord.ID) -ErrorAction SilentlyContinue
If ($Snapshot) {
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " found. Taken: " + ($Snapshot.Description | ConvertFrom-Json).Taken + ". Expire: " + ($Snapshot.Description | ConvertFrom-Json).Expire) -Verbose
Write-Verbose -Message ("Setting SQL status to Taken") -Verbose
# if status has changed from requested to taken, update database status field
$TakenDateTimeSql = ($Snapshot.Description | ConvertFrom-Json).Taken.ToString('yyyy/MM/dd HH:mm:ss')
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Taken', TakenDateTime = '" + $TakenDateTimeSql + "' WHERE ID = " + $Snapshot.Name.split('_')[1])
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
Else {
Write-Verbose -Message ("AutoSnap_" + $SqlRecord.Id + " not found.") -Verbose
If ($SqlRecord.DateTime -lt (Get-Date)) {
Write-Error -Message ("AutoSnap_" + $SqlRecord.Id + " not found, and its requested datetime has passed") -Verbose
# Update SQL record to status Failed-ScheduledNotTaken
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Failed-ScheduledNotTaken' WHERE ID = " + $SqlRecord.Id)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
}
Write-Verbose -Message ("End AutoSnap_" + $SqlRecord.Id) -Verbose
}
Write-Verbose -Message "End Scheduled > Taken Loops"
$SqlRecord = $null
$SqlRecords = $null
$SqlQueryUpdate = $null
# get list of taken from database
Write-Verbose -Message "Start Taken > Expire Loops"
Write-Verbose -Message "Get SQL records with status of Taken" -Verbose
$SqlQuery = "SELECT [ID],[VMName],[DateTime],[RequestedBy],[DurationHours],[Status],[NotifyEmail],[TakenDateTime],[ExpireDateTime],[DeleteDateTime] FROM [ITD-Systems-Automation].[dbo].[$SnapshotTable] WHERE Status = 'Taken'"
$SqlRecords = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
switch ($PSBoundParameters.Keys) {
Id {
Write-Verbose -Message "Narrowing results to Id parameter value of $Id" -Verbose
$SqlRecords = $SqlRecords | Where-Object Id -EQ "$Id"
}
}
# check status of all Taken SQLRecords
Write-Verbose -Message ("Found " + @($SqlRecords).count + " snapshots with Taken status") -Verbose
ForEach ($SqlRecord in @($SqlRecords) ) {
$Snapshot = $null
Write-Verbose -Message ("Start AutoSnap_" + $SqlRecord.Id) -Verbose
$Snapshot = Get-VM -Name $SqlRecord.VMName | Get-Snapshot -Name ("AutoSnap_" + $SqlRecord.ID) -ErrorAction SilentlyContinue
If ($Snapshot) {
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " found. Taken: " + ($Snapshot.Description | ConvertFrom-Json).Taken + ". Expire: " + ($Snapshot.Description | ConvertFrom-Json).Expire) -Verbose
# if expired datetime is in the past, set status to expired
If ( ($Snapshot.Description | ConvertFrom-Json).Expire -lt (Get-Date)) {
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " has expired.") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Expired' WHERE ID = " + $Snapshot.Name.split('_')[1])
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
}
Else {
Write-Verbose -Message ("AutoSnap_" + $SqlRecord.Id + " not found.") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Deleted-Manual' WHERE ID = " + $SqlRecord.Id)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
Write-Verbose -Message ("End AutoSnap_" + $SqlRecord.Id) -Verbose
$SqlRecord = $null
$SqlRecords = $null
$SqlQueryUpdate = $null
}
# get list of Expired from SQL database
Write-Verbose -Message "Start Expired > Removed Loops"
Write-Verbose -Message "Get SQL records with status of Expired" -Verbose
$SqlQuery = "SELECT [ID],[VMName],[DateTime],[RequestedBy],[DurationHours],[Status],[NotifyEmail],[TakenDateTime],[ExpireDateTime],[DeleteDateTime] FROM [ITD-Systems-Automation].[dbo].[$SnapshotTable] WHERE Status = 'Expired'"
$SqlRecords = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
switch ($PSBoundParameters.Keys) {
Id {
Write-Verbose -Message "Narrowing results to Id parameter value of $Id" -Verbose
$SqlRecords = $SqlRecords | Where-Object Id -EQ "$Id"
}
}
# check status of all Expired SQLRecords
Write-Verbose -Message ("Found " + @($SqlRecords).count + " snapshots with Expired status") -Verbose
ForEach ($SqlRecord in @($SqlRecords) ) {
$Snapshot = $null
Write-Verbose -Message ("Start AutoSnap_" + $SqlRecord.Id) -Verbose
$Snapshot = Get-VM -Name $SqlRecord.VMName | Get-Snapshot -Name ("AutoSnap_" + $SqlRecord.ID) -ErrorAction SilentlyContinue
If ($Snapshot) {
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " found. Taken: " + ($Snapshot.Description | ConvertFrom-Json).Taken + ". Expire: " + ($Snapshot.Description | ConvertFrom-Json).Expire) -Verbose
# if expired datetime is in the past, set status to expired
If ( ($Snapshot.Description | ConvertFrom-Json).Expire -lt (Get-Date)) {
Write-Verbose -Message ("Snapshot " + $Snapshot.Name + " is expired. Will be removed at next Removal run") -Verbose
#$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Expired' WHERE ID = " + $Snapshot.Name.split('_')[1])
#Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
}
Else {
Write-Verbose -Message ("AutoSnap_" + $SqlRecord.Id + " not found.") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Deleted-Manual' WHERE ID = " + $SqlRecord.Id)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
Write-Verbose -Message ("End AutoSnap_" + $SqlRecord.Id) -Verbose
$SqlRecord = $null
$SqlRecords = $null
$SqlQueryUpdate = $null
}
# get list of requested from SQL database
Write-Verbose -Message "Start Requested > Scheduled Loops"
Write-Verbose -Message "Get SQL records with status of Requested" -Verbose
$SqlQuery = "SELECT [ID],[VMName],[DateTime],[RequestedBy],[DurationHours],[Status],[NotifyEmail],[TakenDateTime],[ExpireDateTime],[DeleteDateTime] FROM [ITD-Systems-Automation].[dbo].[$SnapshotTable] WHERE Status = 'Requested'"
$SqlRecords = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
switch ($PSBoundParameters.Keys) {
Id {
Write-Verbose -Message "Narrowing results to Id parameter value of $Id" -Verbose
$SqlRecords = $SqlRecords | Where-Object Id -EQ "$Id"
}
}
# check status of all Requested SQLRecords
Write-Verbose -Message ("Found " + @($SqlRecords).count + " snapshots with Requested status") -Verbose
ForEach ($SqlRecord in @($SqlRecords) ) {
# does the scheduled tasks exist?
If ($AllScheduledTasks | Where-Object { $_.Info.Name -eq ("AutoSnap_" + $SqlRecord.Id + '_' + $SqlRecord.VMName) }) {
# yes - update SQL status to Scheduled
Write-Verbose -Message ("AutoSnap_" + $SqlRecord.Id + " vCenter scheduled task exists.") -Verbose
Write-Verbose -Message ("Setting SQL status to Scheduled") -Verbose
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Scheduled' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
Else {
# no
# has date/time passed? (10 minute buffer)
If ($SqlRecord.DateTime -lt (Get-Date).AddMinutes(-10)) {
# yes - set SQL status to Failed-RequestedNotScheduled
Write-Warning -Message ("AutoSnap_" + $SqlRecord.Id + " was not scheduled before its datetime.")
$SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Failed-RequestedNotScheduled' WHERE ID = " + $SqlRecord.ID)
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
}
Else {
# no ???
}
Write-Error -Message ("AutoSnap_" + $SqlRecord.Id + " scheduled task does not exist.")
}
}
Write-Verbose -Message "End Requested > Scheduled Loops"
$SqlRecord = $null
$SqlRecords = $null
$SqlQueryUpdate = $null
Disconnect-ITDvCenter
@@ -0,0 +1,90 @@
Param(
[string]
$Ritm,
[string]
$ComputerName
)
# $cat_item_sys_id = 'c64e27af47244610b7853238436d435d'
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
Write-Verbose -Message "Prep variable and SQL connection" -Verbose
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$Table = "ServiceNow_RitmDump_ServerBuildRequestV1"
$AllRitms = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $Ritm -IncludeCustomVariable -IncludeVariableSet
ForEach ($Ritm in $AllRitms) {
Write-Verbose ("Start " + $Ritm.number) -Verbose
# get all variable set rows
$VariableSet = (Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $Ritm.number.value -IncludeVariableSet).VariableSet
ForEach ($VSet in $VariableSet) {
Write-Verbose -Message ("Start " + $VSet.host_name + ' *** ' + $VSet.host_name_ref)
# figure out values
$RitmNum = $Ritm.number.value
$RitmSysId = $Ritm.sys_id.value
$opened_at = $Ritm.opened_at.display_value
$requested_for = $Ritm.requested_for.display_value
$request_type = $Ritm.CustomVariable.request_type.value
$environment = $Ritm.CustomVariable.environment.value
$host_name_ref = $VSet.host_name_ref
$host_name = If ($VSet.host_name_ref) {
(Get-ITDServiceNowRecord -Table cmdb_ci -SysId $VSet.host_name_ref).Name.display_value
}
Else {
$VSet.host_name
}
$server_type = $VSet.server_type
$operating_system = $VSet.operating_system
$target_os_version_linux = $VSet.target_os_version_linux
$target_os_version_windows = $VSet.target_os_version_windows
$target_platform = $VSet.target_platform
$processors = $VSet.processors
$memory_gb = $VSet.memory_gb
$cidr_block_sys_id = $VSet.cidr_block
$cidr_block = (Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId $cidr_block_sys_id).subnet.display_value
$vlan_id = $VSet.vlan_id
$data_center = $VSet.data_center
$licensing_restrictions = $VSet.licensing_restrictions
$application_info_sys_id = $VSet.application_info
$application_info = (Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId $application_info_sys_id).name.display_value
$support_hours = $VSet.support_hours
$dr_protection = $VSet.dr_protection
$startup_priority = $VSet.startup_priority
$disk_1_os = $VSet.disk_1_os
$disk_2_swap_disk = $VSet.disk_2_swap_disk
$disk_3 = $VSet.disk_3
$disk_4 = $VSet.disk_4
$disk_5 = $VSet.disk_5
$disk_6 = $VSet.disk_6
$disk_7 = $VSet.disk_7
$disk_8 = $VSet.disk_8
$disk_9 = $VSet.disk_9
$disk_10 = $VSet.disk_10
$disk_11 = $VSet.disk_11
$disk_12 = $VSet.disk_12
$disk_13 = $VSet.disk_13
$disk_14 = $VSet.disk_14
$disk_15 = $VSet.disk_15
$disk_16 = $VSet.disk_16
$special_instructions = $Ritm.CustomVariable.special_instructions.value
$customer_request = $Ritm.CustomVariable.customer_request.value
$additional_comments = $Ritm.CustomVariable.additional_comments.value
If ($host_name -eq $ComputerName) {
Write-Verbose -Message ("Add to SQL " + $VSet.host_name + ' *** ' + $VSet.host_name_ref)
# add record to SQL
$SqlQuery = "INSERT INTO [$Table] (
RitmNum, RitmSysId, opened_at,requested_for,request_type,environment,host_name_ref,host_name,server_type,operating_system,target_os_version_linux,target_os_version_windows,target_platform,processors,memory_gb,cidr_block_sys_id,cidr_block,vlan_id,data_center,licensing_restrictions,application_info_sys_id,application_info,support_hours,dr_protection,startup_priority,disk_1_os,disk_2_swap_disk,disk_3,disk_4,disk_5,disk_6,disk_7,disk_8,disk_9,disk_10,disk_11,disk_12,disk_13,disk_14,disk_15,disk_16,special_instructions,customer_request,additional_comments) Values (
'$RitmNum','$RitmSysId','$opened_at','$requested_for','$request_type','$environment','$host_name_ref','$host_name','$server_type','$operating_system','$target_os_version_linux','$target_os_version_windows','$target_platform','$processors','$memory_gb','$cidr_block_sys_id','$cidr_block','$vlan_id','$data_center','$licensing_restrictions','$application_info_sys_id','$application_info','$support_hours','$dr_protection','$startup_priority','$disk_1_os','$disk_2_swap_disk','$disk_3','$disk_4','$disk_5','$disk_6','$disk_7','$disk_8','$disk_9','$disk_10','$disk_11','$disk_12','$disk_13','$disk_14','$disk_15','$disk_16','$special_instructions','$customer_request','$additional_comments'
)
"
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
Write-Verbose -Message $SqlQuery -Verbose
}
Write-Verbose -Message ("End " + $VSet.host_name + ' *** ' + $VSet.host_name_ref)
}
Write-Verbose ("End " + $Ritm.number) -Verbose
}
@@ -0,0 +1,85 @@
Param(
[string]
$SCTaskNum
)
New-ServiceNowSession -Url 'northdakota.service-now.com' -Credential $Secret:SNowVMCred
Connect-ITDvCenter -Credential $Secret:svcitdvmvcauto
$Filter = @('assignment_group', '-like', 'NDIT-Server Build Automation'), '-and', @('short_description', '-like', 'Windows Guest OS complete. Hardware team review.'), '-and', @('state', '-eq', '2') # 2 = 'work in progress'
$OpenTasks = Get-ServiceNowRecord -Table 'Catalog Task' -Filter $Filter | Sort-Object Number
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum"
$OpenTasks = $OpenTasks | Where-Object Number -EQ $SCTaskNum
}
Write-Verbose -Message ("OpenTasks found: " + $OpenTasks.count) -Verbose
ForEach ($OpenTask in $OpenTasks) {
Write-Verbose -Message $OpenTasks.Number -Verbose
}
ForEach ($OpenTask in $OpenTasks) {
$Ci = $null
$BuildComplete = $null
# get SCTask, Ritm
$SCTaskNum = $OpenTask.number
Write-Verbose -Message "Start $SCTasknum" -Verbose
$SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
$shortdescription = $SCTask.short_description
$RitmNum = $SCTask.request_item.display_value
$Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable -WarningAction SilentlyContinue
switch (($Ritm.CustomVariable | Where-Object Name -EQ target_platform).Value) {
'azure' { $target_platform = "Azure" }
'vmware' { $target_platform = "VMware" }
}
$FormFQDN = ($RITM.CustomVariable | Where-Object Name -EQ "host_name").value
$FormHostName = $FormFQDN.split('.')[0]
$Ci = Get-ServiceNowRecord -Table cmdb_ci -Filter @('name', '-eq', $FormHostName)
If ($Ci) {
Write-Verbose -Message ("Ci found, sys_id = " + $Ci.sys_id + ", name = " + $Ci.name + ", fqdn = " + $Ci.fqdn) -Verbose
}
switch ($target_platform) {
{ $_ -like "*VMware*" } {
Connect-ITDvCenter -Credential $Secret:svcitdvmvcauto
Write-Verbose -Message ("$FormFQDN is a VMware VM. Determine if SRM was requested.") -Verbose
$hardware_platform = "VMware";
$hardware_type = 'Virtual Machine'
If ( ($Ritm.CustomVariable | Where-Object Name -EQ 'dr_protection').Value -eq 'No DR') {
Write-Verbose -Message ("$FormFQDN dr_protection equals 'No DR'") -Verbose
Approve-ITDVMNewBuild -SCTaskNum $SCTaskNum -CloseTask -Verbose
}
Else {
Write-Verbose -Message ("$FormFQDN dr_protection is requested") -Verbose
Write-Warning -Message ("SRM is requested, task will not auto close. -- ZM") -Verbose
Approve-ITDVMNewBuild -SCTaskNum $SCTaskNum
}
Disconnect-ITDvCenter
}
{ $_ -like "*Microsoft Virtual Machine*" } {
Write-Verbose -Message ("$FormFQDN is an Azure VM. DR is not an option, proceed.") -Verbose
$hardware_platform = "Azure";
$hardware_type = 'Virtual Machine'
Write-Warning -Message ("Final close task is commented out until testing can occur. -- ZM") -Verbose
#Approve-ITDVMNewBuild -SCTaskNum $SCTaskNum
}
{ $_ -like "*HP*" } {
Write-Verbose -Message ("$FormFQDN is an HPE device.") -Verbose
$hardware_platform = 'HPE';
$hardware_type = 'Physical'
Write-Warning -Message ("Final close task is commented out until testing can occur. -- ZM") -Verbose
}
default {
$hardware_platform = 'Other'
Write-Warning -Message ("Ci found, but unavailable to determine hardware platform.")
}
}
}
Disconnect-ITDvCenter
@@ -0,0 +1,46 @@
Param(
[Parameter(Mandatory = $true, ParameterSetName = 'VMName')]
[string[]]
$VMName,
[Parameter(Mandatory = $true, ParameterSetName = 'NewBuilds')]
[switch]
$NewBuilds,
[Parameter(Mandatory = $true, ParameterSetName = 'All')]
[switch]
$All
)
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmvcauto
switch ($PSCmdlet.ParameterSetName) {
'VMName' {
Write-Verbose -Message "Parameter Set VMName" -Verbose
$VMs = Get-VM -Name $VMName
}
'NewBuilds' {
Write-Verbose -Message "Parameter Set NewBuilds" -Verbose
$VMs = Get-Folder -Name "_New Builds" | Get-VM
}
'All' {
Write-Verbose -Message "Parameter Set All" -Verbose
$VMs = Get-VM | Where-Object CreateDate -lt ((Get-Date).AddDays(-2))
}
}
ForEach($VM in $VMs){
try{
Write-Verbose -Message ("Start " + $VM.Name) -Verbose
Get-VM -Name $VM.Name | Select Uid
Move-ITDVMwareVMToAppNameFolder -VMName $VM.Name -ErrorAction Stop -Verbose
}
catch {
$error[0]
}
}
Write-Verbose -Message "Disconnect from vCenter" -Verbose
Disconnect-ITDvCenter
@@ -0,0 +1,28 @@
Param (
[string]
$Fqdn,
[string]
$RitmNum
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $RitmNum -IncludeVariableSet -IncludeCustomVariable
$Row = $Ritm.VariableSet | Where-Object host_name -eq $Fqdn
$NewITDVMwareSharePointVMRecordParams = @{
HostName = $Fqdn;
LicensingRestrictions = $Row.licensing_restrictions;
DataCenter = $Row.data_center;
Environment = $Ritm.CustomVariable.environment.value;
StartupPriority = $Row.startup_priority;
OperatingSystem = $Row.operating_system;
DR_Protection = $Row.dr_protection;
CPU = $Row.processors;
MemoryGB = $Row.memory_gb;
Disk1 = $Row.disk_1_os;
Disk2 = $Row.disk_2_swap_disk;
Disk3 = $Row.disk_3;
}
New-ITDVMwareSharePointVMRecord @NewITDVMwareSharePointVMRecordParams
@@ -0,0 +1,58 @@
Param(
[Parameter(Mandatory = $true, ParameterSetName = 'VMName')]
[string[]]
$VMName,
[Parameter(Mandatory = $true, ParameterSetName = 'NewBuilds')]
[switch]
$NewBuilds,
[Parameter(Mandatory = $true, ParameterSetName = 'All')]
[switch]
$All
)
Write-Verbose -Message "Connect to ServiceNow" -Verbose
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmvcauto
<#switch ($PSBoundParameters.ContainsKey('VMName')) {
$true {
$VMs = Get-VM -Name $VMName
}
$false {
Write-Verbose -Message "VMName parameter not provided, working on new builds only" -Verbose
$VMs = Get-Folder -Name "_New Builds" | Get-VM | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
}#>
switch ($PSCmdlet.ParameterSetName) {
'VMName' {
Write-Verbose -Message "Parameter Set VMName" -Verbose
$VMs = Get-VM -Name $VMName
}
'NewBuilds' {
Write-Verbose -Message "Parameter Set NewBuilds" -Verbose
$VMs = Get-Folder -Name "_New Builds" | Get-VM
}
'All' {
Write-Verbose -Message "Parameter Set All" -Verbose
$VMs = Get-VM
}
}
ForEach($VM in $VMs){
try{
Write-Verbose -Message ("Start " + $VM.Name) -Verbose
Set-ITDVMwareVMTagFromCmdb -VMName $VM.Name -ErrorAction Stop -Verbose
}
catch {
$error[0]
}
}
Write-Verbose -Message "Disconnect from vCenter" -Verbose
Disconnect-ITDvCenter
@@ -0,0 +1,158 @@
# loop through them, create sql record
# $cat_item_sys_id = 'c64e27af47244610b7853238436d435d'
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
Write-Verbose -Message "Prep variable and SQL connection" -Verbose
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$Table = "ServiceNow_RitmDump_ServerBuildRequestV1"
# get most recent RITM from SQL, get the opened_at value
$SqlQuery = "SELECT [RitmNum],[RitmSysId],[opened_at] FROM [$Database].[dbo].[$Table]"
$SqlExistingRecords = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
$NewestRecord = ($SqlExistingRecords | Sort-Object -Descending opened_at) | select -First 1
$DateYMDFilter = ($NewestRecord.opened_at | Get-Date -UFormat "%Y-%m-%d")
$DateHMSFilter = ($NewestRecord.opened_at | Get-Date -UFormat "%H:%M:%S")
#$Filter = "cat_item=c64e27af47244610b7853238436d435d^opened_at>javascript:gs.dateGenerate('2024-07-30','23:59:59')"
#$Filter = "cat_item=c64e27af47244610b7853238436d435d"
$Filter = "cat_item=c64e27af47244610b7853238436d435d^opened_at>javascript:gs.dateGenerate('$DateYMDFilter','$DateHMSFilter')"
Write-Verbose -Message ("Filter is " + $Filter) -Verbose
# retrieve list of RITMs created since $opened_at (>opened_at)
Write-Verbose -Message "Retrieve list of RITMs created since last update" -Verbose
#$AllRitms = Get-ITDServiceNowRecord -ItemType 'Request Item' -Filter $Filter -IncludeTotalCount -IncludeCustomVariable | Sort-Object Number
$AllRitms = Get-ITDServiceNowRecord -ItemType 'Request Item' -Filter $Filter -IncludeTotalCount -IncludeCustomVariable | Sort-Object Number
#$AllRitms = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number 'RITM0262097' -IncludeCustomVariable
Write-Verbose -Message ("RITMs found: " + @($AllRitms).count) -Verbose
ForEach ($Ritm in $AllRitms) {
Write-Verbose ("Start " + $Ritm.number) -Verbose
# get all variable set rows
$VariableSet = (Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $Ritm.number.value -IncludeVariableSet).VariableSet
ForEach ($VSet in $VariableSet) {
Write-Verbose -Message ("Start " + $VSet.host_name + ' *** ' + $VSet.host_name_ref)
# figure out values
$RitmNum = $Ritm.number.value
$RitmSysId = $Ritm.sys_id.value
$opened_at = $Ritm.opened_at.display_value
$requested_for = $Ritm.requested_for.display_value
$request_type = $Ritm.CustomVariable.request_type.value
$environment = $Ritm.CustomVariable.environment.value
$host_name_ref = $VSet.host_name_ref
$host_name = If ($VSet.host_name_ref) {
(Get-ITDServiceNowRecord -Table cmdb_ci -SysId $VSet.host_name_ref).Name.display_value
}
Else {
$VSet.host_name
}
$server_type = $VSet.server_type
$operating_system = $VSet.operating_system
$target_os_version_linux = $VSet.target_os_version_linux
$target_os_version_windows = $VSet.target_os_version_windows
$target_platform = $VSet.target_platform
$processors = $VSet.processors
$memory_gb = $VSet.memory_gb
$cidr_block_sys_id = $VSet.cidr_block
$cidr_block = (Get-ITDServiceNowRecord -Table 'cmdb_ci_ip_network' -SysId $cidr_block_sys_id).subnet.display_value
$vlan_id = $VSet.vlan_id
$data_center = $VSet.data_center
$licensing_restrictions = $VSet.licensing_restrictions
$application_info_sys_id = $VSet.application_info
$application_info = (Get-ITDServiceNowRecord -Table 'cmdb_ci_service' -SysId $application_info_sys_id).name.display_value
$support_hours = $VSet.support_hours
$dr_protection = $VSet.dr_protection
$startup_priority = $VSet.startup_priority
$disk_1_os = $VSet.disk_1_os
$disk_2_swap_disk = $VSet.disk_2_swap_disk
$disk_3 = $VSet.disk_3
$disk_4 = $VSet.disk_4
$disk_5 = $VSet.disk_5
$disk_6 = $VSet.disk_6
$disk_7 = $VSet.disk_7
$disk_8 = $VSet.disk_8
$disk_9 = $VSet.disk_9
$disk_10 = $VSet.disk_10
$disk_11 = $VSet.disk_11
$disk_12 = $VSet.disk_12
$disk_13 = $VSet.disk_13
$disk_14 = $VSet.disk_14
$disk_15 = $VSet.disk_15
$disk_16 = $VSet.disk_16
$special_instructions = $Ritm.CustomVariable.special_instructions.value
$customer_request = $Ritm.CustomVariable.customer_request.value
$additional_comments = $Ritm.CustomVariable.additional_comments.value
Write-Verbose -Message ("Add to SQL " + $VSet.host_name + ' *** ' + $VSet.host_name_ref)
# add record to SQL
$SqlQuery = "INSERT INTO [$Table] (
RitmNum, RitmSysId, opened_at,requested_for,request_type,environment,host_name_ref,host_name,server_type,operating_system,target_os_version_linux,target_os_version_windows,target_platform,processors,memory_gb,cidr_block_sys_id,cidr_block,vlan_id,data_center,licensing_restrictions,application_info_sys_id,application_info,support_hours,dr_protection,startup_priority,disk_1_os,disk_2_swap_disk,disk_3,disk_4,disk_5,disk_6,disk_7,disk_8,disk_9,disk_10,disk_11,disk_12,disk_13,disk_14,disk_15,disk_16,special_instructions,customer_request,additional_comments) Values (
'$RitmNum','$RitmSysId','$opened_at','$requested_for','$request_type','$environment','$host_name_ref','$host_name','$server_type','$operating_system','$target_os_version_linux','$target_os_version_windows','$target_platform','$processors','$memory_gb','$cidr_block_sys_id','$cidr_block','$vlan_id','$data_center','$licensing_restrictions','$application_info_sys_id','$application_info','$support_hours','$dr_protection','$startup_priority','$disk_1_os','$disk_2_swap_disk','$disk_3','$disk_4','$disk_5','$disk_6','$disk_7','$disk_8','$disk_9','$disk_10','$disk_11','$disk_12','$disk_13','$disk_14','$disk_15','$disk_16','$special_instructions','$customer_request','$additional_comments'
)
"
Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
Write-Verbose -Message ("End " + $VSet.host_name + ' *** ' + $VSet.host_name_ref)
}
Write-Verbose ("End " + $Ritm.number) -Verbose
}
<# scratch
Write-Verbose -Message ("Add record to SQL") -Verbose
$SqlQuery = "INSERT INTO [$SnapshotTable] (VMName, DateTime, RequestedBy, DurationHours,Status,ExpireDateTime,NotifyEmail,PSUJobIdRequest) Values ('$Name', '$StartDateTimeSql', '$RequestedBy', $DurationHours, 'Requested', '$EndDateTimeSql','$Email','$PSUJobId');SELECT SCOPE_IDENTITY();"
#Write-Verbose -Message $SqlQuery -Verbose
$SnapshotId = (Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:itdpsu1 -Verbose).Column1
select TOP (1000) [RitmNum]
, [RitmSysId]
, [opened_at]
, [requested_for]
, [request_type]
, [environment]
, [host_name_ref]
, [host_name]
, [server_type]
, [operating_system]
, [target_os_version_linux]
, [target_os_version_windows]
, [target_platform]
, [processors]
, [memory_gb]
, [cidr_block_sys_id]
, [cidr_block]
, [vlan_id]
, [data_center]
, [licensing_restrictions]
, [application_info_sys_id]
, [application_info]
, [support_hours]
, [dr_protection]
, [startup_priority]
, [disk_1_os]
, [disk_2_swap_disk]
, [disk_3]
, [disk_4]
, [disk_5]
, [disk_6]
, [disk_7]
, [disk_8]
, [disk_9]
, [disk_10]
, [disk_11]
, [disk_12]
, [disk_13]
, [disk_14]
, [disk_15]
, [disk_16]
, [special_instructions]
, [customer_request]
, [additional_comments]
FROM [ITD-Systems-Automation].[dbo].[ServiceNow_RitmDump_ServerBuildRequestV1]
#>
@@ -0,0 +1,25 @@
Param(
[string]
$VMName,
[switch]
$SRMImplemented
)
Write-Verbose "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmvcro
Write-Verbose "Start Sync" -Verbose
switch ($PSBoundParameters.Keys){
'VMName' { $SyncITDVMwareVMMetadataToSharePointParams += @{VMName = $VMName} }
'SRMImplemented' { $SyncITDVMwareVMMetadataToSharePointParams += @{SRMImplemented = $SRMImplemented} }
}
Write-Host $SyncITDVMwareVMMetadataToSharePointParams
Sync-ITDVMwareVMMetadataToSharePoint @SyncITDVMwareVMMetadataToSharePointParams -Verbose
#Write-Output $VMName
Write-Verbose "End Sync"
Write-Verbose "Disconnect vCenter"
Disconnect-ITDvCenter
@@ -0,0 +1,15 @@
Param(
[string]
$VMName
)
Write-Verbose "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmvcro
Write-Verbose "Start Sync" -Verbose
Sync-ITDVMwareVMMetadataToSharePoint -VMName $VMName
#Write-Output $VMName
Write-Verbose "End Sync"
Write-Verbose "Disconnect vCenter"
Disconnect-ITDvCenter
@@ -0,0 +1,10 @@
Write-Verbose -Message "Connect to ServiceNow" -Verbose
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmvcauto
Write-Verbose -Message "Execute Sync-ITDVMareVMTagsFromCmdb" -Verbose
Sync-ITDVMwareVMTagsFromCmdb -Verbose
Disconnect-ITDvCenter
@@ -0,0 +1,2 @@
New-ITDServiceNowSession -Environment Production -Credential $Secret:SNowVMCred
Update-ITDSNowVMTaskDescription -Verbose
@@ -0,0 +1,2 @@
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
Update-ITDSNowVMTaskDescription -Verbose
@@ -0,0 +1,6 @@
Param(
[string]
$SCTaskNum = "World"
)
Write-Host "Hello, $WorldName!"
@@ -0,0 +1,4 @@
# It all starts with a single line of powershell code.
$DateTime = Get-Date -UFormat "%Y%m%d%H%M%S"
New-Item -Name "Dummy$DateTime" -Path "C:\ITD\DummyFiles\"
Start-Sleep -Seconds 360
@@ -0,0 +1,152 @@
<#
.SYNOPSIS
Processes automated server build tasks for Windows machines in ServiceNow, triggered via PowerShell Universal.
.DESCRIPTION
This script connects to the ServiceNow API, retrieves open catalog tasks that match a specific filter for automated server build tasks,
and processes them. This script is designed to run as a scheduled task. It can optionally filter tasks by a specific SCTask number.
.PARAMETER SCTaskNum
The ServiceNow task number to filter the tasks. If not provided, all tasks matching the filter will be processed.
.EXAMPLE
.\New-ITDWindowsVmBuildTask_Auto.ps1
This example runs the script and processes all open tasks that match the filter for automated server build tasks.
.EXAMPLE
.\New-ITDWindowsVmBuildTask_Auto.ps1 -SCTaskNum 'SCTASK0012345'
This example runs the script and processes only the task with the specified SCTask number.
.NOTES
Ensure that the ServiceNow instance URL and credentials are correctly configured in the New-ITDServiceNowSession function.
This script is not supported in Linux.
#>
<#
Param(
[string]
$SCTaskNum
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
$Filter = 'active=true^short_descriptionSTARTSWITHAutomated Server Build Task for Windows Machine'
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter | Sort-Object Number | Select-Object -First 3
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum" -Verbose
$OpenTasks = $OpenTasks | Where-Object { $_.number.value -EQ $SCTaskNum }
}
$AllRitms = [System.Collections.ArrayList]@()
Write-Verbose -Message ("OpenTasks found: " + @($OpenTasks).Count) -Verbose
ForEach ($OpenTask in $OpenTasks) {
$PSUJob = $null
$SCTask = $null
$shortdescription = $null
$shortdescription_hostname = $null
$WorkNotesMsg = $null
$SCTaskNum = $OpenTask.number.Value
Write-Verbose -Message "Start $SCTaskNum" -Verbose
try {
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$shortdescription = $SCTask.short_description.display_value
$shortdescription_hostname = $shortdescription.split(' ')[7]
If ($AllRitms | Where-Object { $_.number.display_value -EQ $SCTask.request_item.display_value }) {
Write-Verbose -Message ("Ritm already in memory") -Verbose
$Ritm = $AllRitms | Where-Object sys_id -EQ $SCTask.request_item.display_value
}
Else {
Write-Verbose -Message "Ritm is not in memory, retrieve it" -Verbose
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
$null = $AllRitms.Add($Ritm)
}
# check for step messages in SCTask work_notes and determine next step
switch ($SCTask.work_notes.display_value) {
{ $_ -match "human review" } {
Write-Verbose -Message "Human review required, skipping" -Verbose
Break
}
{ $_ -match "build step 2 complete" } {
# execute Step 3
Write-Verbose -Message "Step 2 already complete, starting step 3" -Verbose
$PSUJob = Invoke-PSUScript -Script "Get-HelloWorld.ps1" -SCTaskNum $SCTaskNum
#$WorkNotesMsg = ("VMware build Step 3 started.`nPSU Job Id #" + $PSUJob.Id)
Break
}
{ $_ -match "build Step 2 started"} {
Write-Verbose -Message "Step 2 already started, skipping" -Verbose
Break
}
{ $_ -match "build step 1 complete" } {
# execute Step 2
Write-Verbose -Message "Step 1 already complete, starting Step 2" -Verbose
# Determine if VMware or Azure and run appropriate build Step 2 function
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' {
$target_platform = "Azure"
Write-Verbose "Invoking PSUScript for Azure Step 2" -Verbose
#Invoke-PSUScript -Script "New-ITDWindowsVmAzure_Step2.ps1" -SCTaskNum $SCTaskNum
}
'vmware' {
$target_platform = "VMware"
Write-Verbose "Invoking PSUScript for VMware Step 2" -Verbose
$PSUJob = Invoke-PSUScript -Script "Get-HelloWorld.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("VMware build Step 2 started.`nPSU Job Id #" + $PSUJob.Id)
}
}
Break
}
{ $_ -match "build Step 1 started"} {
Write-Verbose -Message "Step 1 already started, skipping" -Verbose
Break
}
Default {
# execute Step 1
Write-Verbose -Message "No step messages found, starting Step 1" -Verbose
# Determine if VMware or Azure and run appropriate build function
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' {
$target_platform = "Azure"
Write-Verbose "Invoking PSUScript for Azure Step 1" -Verbose
$PSUJob = Invoke-PSUScript -Script "Get-HelloWorld.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("Azure build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
}
'vmware' {
$target_platform = "VMware"
Write-Verbose "Invoking PSUScript for VMware Step 1" -Verbose
$PSUJob = Invoke-PSUScript -Script "Get-HelloWorld.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("VMware build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
}
}
Break
}
}
}
catch {
Write-Error -Message $error[0]
}
If($null -eq $WorkNotesMsg){
# do nothing
} Else {
Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{work_notes = $WorkNotesMsg }
}
}
#>
#Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot02.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot03.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot04.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot05.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot06.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot07.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot08.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot09.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot10.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot11.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot12.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot13.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot14.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
Invoke-PSUScript -Name New-ITDWindowsVmAzure_Step1.ps1 -FQDN itdcopilot15.testnd.gov -DiskOsGB 128 -Subnet 10.21.29.96/27 -OS "Windows 11 24H2" -VMEnvironment 'Test' -AppName ITD-POC-Copilot -LicensingRestrictions "No Licensing Restrictions" -DiskDataGB 0 -VMSizeOverride "Standard_D4ds_v5"
@@ -0,0 +1,10 @@
param(
[String]
$VMName
)
$string = (Get-Date -UFormat "%Y%m%d%H%M%S") + " Hello World! $VMName"
Write-Output $string
Write-Output $User
@@ -0,0 +1,77 @@
Param(
[string]
$SCTaskNum
)
New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
$Filter = 'active=true^short_descriptionSTARTSWITHAutomated Server Build Task for Windows Machine'
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter | Sort-Object Number
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum" -Verbose
$OpenTasks = $OpenTasks | Where-Object { $_.number.value -EQ $SCTaskNum }
}
$AllRitms = [System.Collections.ArrayList]@()
Write-Verbose -Message ("OpenTasks found: " + @($OpenTasks).Count) -Verbose
ForEach ($OpenTask in $OpenTasks) {
$PSUJob = $null
$SCTask = $null
$shortdescription = $null
$shortdescription_hostname = $null
$WorkNotesMsg = $null
$SCTaskNum = $OpenTask.number.Value
Write-Verbose -Message "Start $SCTaskNum" -Verbose
try {
$SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
$shortdescription = $SCTask.short_description.display_value
$shortdescription_hostname = $shortdescription.split(' ')[7]
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
<#
If ($AllRitms | Where-Object { $_.number.display_value -EQ $SCTask.request_item.display_value }) {
Write-Verbose -Message ("Ritm already in memory") -Verbose
$Ritm = $AllRitms | Where-Object sys_id -EQ $SCTask.request_item.display_value
}
Else {
Write-Verbose -Message "Ritm is not in memory, retrieve it" -Verbose
$Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
$null = $AllRitms.Add($Ritm)
}
#>
# check for step messages in SCTask work_notes and determine next step
switch ($SCTask.work_notes.display_value) {
Default {
# execute Step 1
Write-Verbose -Message "No step messages found, starting Step 1" -Verbose
# Determine if VMware or Azure and run appropriate build function
switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
'azure' {
$target_platform = "Azure"
Write-Verbose "Invoking PSUScript for Azure Step 1" -Verbose
#$PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmAzure_Step1.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("Azure build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
}
'vmware' {
$target_platform = "VMware"
Write-Verbose "Invoking PSUScript for VMware Step 1" -Verbose
$PSUJob = Invoke-PSUScript -Script "Get-HelloWorld.ps1" -SCTaskNum $SCTaskNum
$WorkNotesMsg = ("VMware build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
}
}
Break
}
}
}
catch {
Write-Error -Message $error[0]
}
Write-Verbose -Message "End $SCTaskNum" -Verbose
}
@@ -0,0 +1,5 @@
$x=Invoke-PSUScript -Name Get-HelloWorld.ps1 -WorldName "zm"
Write-Warning $x.Id
$x=Invoke-PSUScript -Name Get-HelloWorld.ps1 -WorldName "zo"
Write-Warning $x.Id
@@ -0,0 +1,2 @@
# It all starts with a single line of powershell code.
Write-Verbose -Message $Secret:ndgov_svcitdpsuwin.username -Verbose
@@ -0,0 +1,12 @@
New-ServiceNowSession -Url 'northdakota.service-now.com' -Credential $Secret:SNowVMCred -Verbose
$OpenTasks = Get-ServiceNowRecord -Table 'Incident'
Write-Host $OpenTasks
New-ServiceNowSession -Url 'northdakotatest.service-now.com' -Credential $Secret:SNowVMCred -Verbose
$OpenTasks = Get-ServiceNowRecord -Table 'Incident'
Write-Host $OpenTasks
@@ -0,0 +1,2 @@
###
Write-Warning -Message "Hello World!"
@@ -0,0 +1,18 @@
switch ($env:computername) {
"ITDWINAUTOT1" {
New-UDTypography -Text 'NPD'
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$Table = "Infra_WindowsServer_FileManagement_RemoveITDExpiredFiles_PRD"
}
"ITDWINAUTOP1" {
New-UDTypography -Text 'PRD'
$ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
$Database = "ITD-Systems-Automation"
$Table = "Infra_WindowsServer_FileManagement_RemoveITDExpiredFiles_PRD"
}
}
$SqlQuery = "SELECT [PSUJobId],[DateTime],[ComputerName],[Status],[FullName] FROM [$Database].[dbo].[$Table]"
$SqlRecords = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQuery -Credential $Secret:sql_itdpsu1 -Verbose
@@ -0,0 +1,3 @@
New-UDApp -Title 'PowerShell Universal' -Pages @(
Get-UDPage -Name 'home'
)

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