Jere's Techblog

Get reserved Memory of ESXi Host

With the command Get-VMHost you can read values ​​such as the current memory consumption or the total number memory of a host. But I didn’t find a way to read out the value of the allocated memory of the subobjects (the VMs).

Here is an example of how this can be done. The script outputs a list of all hosts. In the attribute “AllocatedVMMemoryGB” you can see how much memory has been over-provisioned or it shows how much memory you could still use.

#by J.Kühnis 20.08.2019

#Class
Class VMHost{
    [string]$Name
    [string]$ConnectionState
    [string]$PowerState
    [int]$NumCpu
    [int]$MemoryUsageGB
    [int]$AllocatedVMMemoryGB
    [int]$MemoryTotalGB
    [string]$ParentCluster
    [string]$Id
    [string]$ProcessorType
}

#Vars
$VmHostArray =@()

#MainScript
Foreach($server in Get-VMHost){
    $a = (($server | get-vm).MemoryGB | Measure-Object -sum).sum
    $server = Get-vmHost -name $server.name
    $a = ("{0:N0}" -f $server.MemoryTotalGB) - ("{0:N0}" -f $a);

    $vmhost = New-Object VMHost -Property @{Name=$server.name;ConnectionState=$server.ConnectionState;Powerstate=$server.ConnectionState;NumCpu=$server.NumCpu;MemoryUsageGB=$server.MemoryUsageGB;AllocatedVMMemoryGB=$a;MemoryTotalGB=$server.MemoryTotalGB;ParentCluster=$server.parent;ID=$server.Id;ProcessorType=$server.ProcessorType}
    
    $VmHostArray += $vmhost

    Clear-Variable -Name a,vmhost
}

#output
$VmHostArray | Format-Table

            
Continue reading...

Hyper-V Create Machine

I’d like to share a mini Script to create VirtualMachines with Hyper-V and Powershell. It is certainly not enterprise diveable. But it’s enough to create a VM for testing.

#by JKU 02.08.2019

#VM Base Information
$VMName = "TestVM2"
$DataPath = "C:\temp"
$DataVMPath = $DataPath + "\" + $VMName
$DiskDataPath = $DataPath + "\" + $VMName + "\" + $VMName + ".vhdx"
$Memory = 2GB
$Disk = 12GB
$CPUCores = 4
$VMGeneration = 2   #Options are "1","2"   -> If you don't have any idea, please let this at Value 2

#Options
$MountIso = "true"
$StartVMaftreCreation = "true"
$IsoPath = "C:\Cloud_JK\NextCloud\jere@nx2309.your-next.cloud\OS\win10\SW_DVD5_Win_Pro_10_64BIT_German_MLF_X20-25597.ISO"




#Script
IF(Get-VM -Name $VMName -ErrorAction SilentlyContinue){
    Write-Warning "$VMName : Machine already exists! Please verify your Values."
    return
}
IF(Test-Path $DataVMPath){
    Write-Warning "$DataVMPath : Folder already exists! Please verify your Values."
    return
}

Write-Host "Start to create VM $VMName" -foregroudcolor yellow
New-VM -Name $VMName -path $DataPath -MemoryStartupBytes $Memory -NewVHDSizeBytes $Disk -NewVHDPath $DiskDataPath -Generation $VMGeneration

$Vm = (Get-VM -Name $VMName)
Set-VM -VM $Vm -ProcessorCount $CPUCores


IF($MountIso -eq "true"){
    $DVD = Add-VMDvdDrive -VMName ($Vm).Name -Path $ISOPath -Passthru
    Set-VMFirmware -VM $VM -FirstBootDevice $DVD
}
IF($StartVMaftreCreation -eq "true"){
    Start-VM -Name $VMName
}

Write-Host "Script End"

Below are two links to similar topics.

To create a virtual machine from a specific template (Hyper V)

Continue reading...

Install Eclipse Plugins from command line

tested with:

Eclipse Java EE IDE for Web Developers – Version: Oxygen.1a Release (4.7.1a)

Eclipse Java EE IDE for Web Developers – Version: 2019-03 (4.11.0)

Basics

There is a nice detailed blog article which describes how to install the Eclipse plugins.
The description is for Linux, it works exactly the same on Windows.
The syntax is shown with an example and it is explained how to get to the repository information.

Here is an example for the Windows Commandline:

C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe -application org.eclipse.equinox.p2.director -repository http://download.eclipse.org/releases/oxygen -installIU org.eclipse.jgit.http.apache.feature.group

However, there are some problems with automation:

  • The plugins cannot be installed in parallel mode, at least this didn’t work for me.
  • Prerequisits will not be automaticly installed.

The automated solution:

First you have to manually try out the commands to get the order and dependencies/prerequsits right.

The loop in the script will sequentially process the installations…if a plugin installation takes more than 5min the Eclipse process will stop and the next plugin will be installed.

Don’t forget ro Run Powershell in elevated mode.

#09.04.2019 by J.Kühnis installation Eclipse Plugins

#Install Eclipse Addons from Web-repository
[array]$InstallArguments = @(
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository https://tools.hana.ondemand.com/oxygen/ -installIU com.sap.it.ide.adapter.sdk.feature.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository http://download.eclipse.org/releases/oxygen -installIU org.eclipse.jgit.http.apache.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository https://tools.hana.ondemand.com/oxygen/ -installIU com.sap.it.commons.command.http.apacheclient'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository https://tools.hana.ondemand.com/oxygen/ -installIU com.sap.it.op.cockpit.ui.feature.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository https://tools.hana.ondemand.com/oxygen/ -installIU com.sap.core.tools.eclipse.help.feature.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository http://download.eclipse.org/releases/oxygen -installIU org.eclipse.libra.facet'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository http://download.eclipse.org/releases/oxygen -installIU org.eclipse.libra.facet.feature.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository http://download.eclipse.org/releases/oxygen -installIU org.eclipse.jpt.jpadiagrameditor.feature.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository https://tools.hana.ondemand.com/oxygen/ -installIU com.sap.core.tools.eclipse.server.feature.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository https://tools.hana.ondemand.com/oxygen/ -installIU com.sap.jvm.profiling.feature.group'
'&"C:\Program Files\eclipse\jee-latest-released\eclipse\eclipse.exe" -application org.eclipse.equinox.p2.director -repository https://tools.hana.ondemand.com/oxygen/ -installIU com.sap.idm.dev-ui-feature.feature.group'
)
                                                                                                             
Foreach($argument in $InstallArguments){
    #Install Addins
    Write-Host $argument -ForegroundColor Yellow
    $argument | Invoke-Expression
    Start-Sleep 5

    #Check if Service is Running and wait | Exit after 300Seconds
    [int]$counter = 0
        
        Do {  
            $ProcessesFound = get-process -Name *eclipse*
            If (($ProcessesFound) -and ($counter -le "30")) {
                Start-Sleep 10
                $counter++
                Write-Host "Still running: $($ProcessesFound)  $counter"
            }Else{
                IF ($counter -gt "30"){
                    Write-Host "Try to kill running Process while Process is taking more than 5 Minutes" -ForegroundColor DarkYellow -BackgroundColor Black
                }Else{
                    Write-Host "Process ended by installer" -ForegroundColor Green
                }
                Get-Process *eclipse* | Stop-Process -Force
            }
        } Until (!$ProcessesFound)

        Clear-Variable -Name counter -Scope Global
        Start-Sleep 2
}
Continue reading...

Query big ADObject / Containers

The Powershell AD-Modules have certain restrictions when it comes to querying large objects, this can be bypassed by ADSI Query.

Here an example how to read them and how to iterate on users of a group:

#by J.Kühnis 13.03.2019
#example ADSI Query Powershell
$BigGroup = "someADGroupName"
$ADGroup1 = "someADGroup1"
$ADGroup2 = "someADGroup2"


$groupname = $BigGroup
$groupdsn = (Get-ADGroup $groupname).DistinguishedName
$group =[adsi]”LDAP://$groupdsn” 
$groupmemebrs = $group.psbase.invoke("Members") | % {$_.GetType().InvokeMember("SamAccountName",'GetProperty',$null,$_,$null)}

$groupmemebrs | foreach {
    
    $usradgroups = GET-ADUser -Identity $_ –Properties MemberOf | Select-Object -ExpandProperty MemberOf | Get-ADGroup -Properties name | Select-Object name
    IF ($usradgroups.name -notContains $ADGroup1 -and $usradgroups.name -notContains $ADGroup2) {

        #User is not a Member of ADGroup1 & ADGroup2

        }
        Else{
          #User is MemberOf ADGroup1 & ADGroup2
        }
}

Here also an example using a Class to just specify the object the way you like:

#by J.Kühnis 09.10.2019
#Set variables
$ADGROUP = "someAdGrp"

# Load AD-Module
IF (!(Get-Module -Name ActiveDirectory)) {
    Import-Module -Name ActiveDirectory
    IF (!(Get-Module -Name ActiveDirectory)) {
    start-sleep 10
    Write-Warning "No AD-Module Found"

        Exit
    }
}
$groupname = $ADGROUP
$groupdsn = (Get-ADGroup $groupname).DistinguishedName
$group =[adsi]”LDAP://$groupdsn” 
$groupmemebrs = $group.psbase.invoke("Members") | % {$_.GetType().InvokeMember("SamAccountName",'GetProperty',$null,$_,$null)}

class User{
[string]$Name
[string]$SamAccountName
[string]$UserPrincipalName
[string]$Mail
[string]$extensionAttribute7
[string]$extensionAttribute9
}


$Userlist = @()
$groupmemebrs | ForEach-Object {
    $usrATTR = GET-ADUser -Identity $_ –Properties Name,SamAccountName,UserPrincipalName,mail,extensionAttribute9, extensionAttribute7
    
    $User = [User]::new()
    $User.Name = $usrATTR.Name
    $User.SamAccountName = $usrATTR.SamAccountName
    $User.UserPrincipalName = $usrATTR.UserPrincipalName
    $User.Mail = $usrATTR.Mail
    $User.extensionAttribute1 = $usrATTR.extensionAttribute1
    $User.extensionAttribute2 = $usrATTR.extensionAttribute2

    $Userlist += $User
}
$Userlist | format-table
Continue reading...

Copy-Items with folder Structure and Filter in a Foreach-Parallel Workflow

#J.Kühnis 08.03.2019
$Sourcefolder= "\\localhost\C$\Temp\1"
$Targetfolder= "C:\Temp2\1"


$query = Get-ChildItem $Sourcefolder -Recurse | Where-Object {$_.LastWriteTime -gt [datetime]::Now.AddDays(-1)}


workflow CopyJob {
    param (
    [Object[]]$query,
    [String]$Sourcefolder,
    [String]$Targetfolder
    )
    
Foreach($item in $query){
    $dest = $Targetfolder + $item.FullName.SubString($Sourcefolder.Length)
    
    #Write-Host $dest -ForegroundColor Yellow
    Copy-Item $item.FullName -Destination $dest -Force
}
}

CopyJob -query $query -Sourcefolder $Sourcefolder -Targetfolder $Targetfolder
Continue reading...

Invoke Command on Specified MachineCatalog and DeliveryGroup

The nice thing about Powershell and the modules/API to other technologies is that you can do simple queries and have a big effect.

The following example starts a service for specified machines in a Citrix 7.x environment.

#by J.Kühnis 06.03.2019
Add-PSSnapin *
$machines = (Get-BrokerMachine * -AdminAddress my.broker.fqdn |
 where-object {($_.CatalogName -match "someMC*") -and ($_.DesktopGroupName -eq "someDG")}).DNSName

Foreach ($machine in $Machines)
 {Write-Host $machine -ForegroundColor Yellow
 invoke-command -ComputerName $machine -ScriptBlock {get-service -name cpsvc | Start-Service} }

Continue reading...

Reset User Profile FatClients

Just run the Script and have some fun while deleting local/remote Userprofiles 🙂

The parameters Username and ComputerName are mandatory.

The parameter -wildcard:$true allows to delete multiple profiles. For example all users with the profile name “John*“.

#by J.Kühnis 
#Code Elements of https://gallery.technet.microsoft.com/scriptcenter/Remove-UserProfileps1-871f57c4
#Run with elevated rights
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent( ) )
if ( -not ($currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) ) )
{
    Write-Host "This script must be executed in admin mode." -ForegroundColor Yellow
    Write-Error "This script must be executed in admin mode." -ErrorAction Stop
    Pause
}

Function Reset-LocalUserProfile {

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string]$Username,
        [Parameter(Mandatory = $true)][string]$ComputerName,
        [switch]$IncludeSpecialUsers = $False,
        [switch]$Force = $True,
        [bool]$Wildcard   
)

    IF ($Username -match '\*'){
        IF($Wildcard){
            Write-Warning "wildcard enabled, deletion for multiple users enabled"

        }Else{
            Write-Warning "Username must be unique without wildcard '*'. If you like to use wildcard, please use '-Widlcard `$true' parameter. "
        return
        

        }
    }
        
    
    $profileFounds = 0

    #Region Functions

    #https://www.petri.com/test-network-connectivity-powershell-test-connection-cmdlet
    Function Test-PSRemoting {
        [cmdletbinding()]
     
        Param(
            [Parameter(Position = 0, Mandatory, HelpMessage = "Enter a computername", ValueFromPipeline)]
            [ValidateNotNullorEmpty()]
            [string]$Computername,
            [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty
        )
     
        Begin {
            Write-Host -Message "Starting $($MyInvocation.Mycommand)"  
        } #begin
     
        Process {
            Write-Host -Message "Testing $computername"
            Try {
                $r = Test-WSMan -ComputerName $Computername -Credential $Credential -Authentication Default -ErrorAction Stop
                $True 
            }
            Catch {
                Write-Host $_.Exception.Message
                $False
     
            }
     
        } #Process
     
        End {
            Write-Host -Message "Ending $($MyInvocation.Mycommand)"
        } #end
     
    } #close function

    #Check IF WinRM is OK

    IF (!(Test-PSRemoting -Computername $ComputerName)) {    
        Write-Host -Message "PS Remoting Error, can't reach Connect with WinRM"
        return
        
    }
    

    Try {
        $profiles = Get-WmiObject -Class Win32_UserProfile -Computer $ComputerName -Filter "Special = '$IncludeSpecialUsers'" -EnableAllPrivileges
    }
    Catch {            
        Write-Warning "Failed to retreive user profiles on $ComputerName"
        return
    }

   
    ForEach ($profile in $profiles) {
        try {
            $sid = New-Object System.Security.Principal.SecurityIdentifier($profile.SID)               
            $account = $sid.Translate([System.Security.Principal.NTAccount])    
            $accountName = $account.value.split("\")[1]
            $profilePath = $profile.LocalPath
            $loaded = $profile.Loaded
            $special = $profile.Special
        }
        catch {
            continue
    
        }
            
        If ($accountName.ToLower() -Eq $UserName.ToLower() -Or ($UserName.Contains("*") -And $accountName.ToLower() -Like $UserName.ToLower())) {
      
            #If ($ExcludeUserName -ne [string]::Empty -And -Not $ExcludeUserName.Contains("*") -And ($accountName.ToLower() -eq $ExcludeUserName.ToLower())) {Continue}
            #If ($ExcludeUserName -ne [string]::Empty -And $ExcludeUserName.Contains("*") -And ($accountName.ToLower() -Like $ExcludeUserName.ToLower())) {Continue}

            $profileFounds ++

            If ($profileFounds -gt 1) {Write-Host "`n"}
            Write-Host "Start deleting profile ""$account"" on computer ""$ComputerName"" ..." -ForegroundColor Green
            Write-Host "Account SID: $sid"
            Write-Host "Special system service user: $special"
            Write-Host "Profile Path: $profilePath"
            Write-Host "Loaded : $loaded"
            If ($loaded) {
                Write-Warning "Cannot delete profile because is in use"
                Continue
            }

            If ($Force -Or $PSCmdlet.ShouldProcess($account)) {
                Try {
                    $profile.Delete()           
                    Write-Host "Profile deleted successfully" -ForegroundColor Green        
                }
                Catch {            
                    Write-Host "Error during delete the profile. Maybe the user with you executed the script has no rights or the script was not started with admin rights." -ForegroundColor Red
                }
            } 
        }
    }

    If ($profileFounds -eq 0) {
        Write-Warning "No profiles found on $ComputerName with Name $UserName"
    }
Write-Host '########## START SCRIPT ##########' -ForegroundColor yellow
Reset-LocalUserProfile
}

Reset-LocalUserProfile
Continue reading...

Get Data from Bluecat DNS Server with REST API

Here is an example how you can use the REST API on the BluecatDNSServer to query data via the workflow interface (alternatively you could use its API directly).
I am sure that you can use this concept for other web interfaces.

The script is a translation of a CURL request. It shows how to query the token and use this “BASIC Token” for further queries.

#BY J.Kühnis
#Invoke Webrequest/RestMethod to get IP Adress & Mac-Adress from Bluecat API
#translation of CURL Commands

############################
#   CURL sample
#
#Get TOKEN
#curl -k https://URL/rest_login -X POST -H "Content-Type: application/json" --data "{\"username\":\"your USERNAME\",\"password\":\"your USERNAME\"}"
#
#GET Request:
#curl -k https://URL/get_ip_infos/get_ip_infos_endpoint -X GET -H "auth: Basic ****SOME TOKEN****" -H "Content-Type: application/json" --data "{\"host\":\"SERVERNAME\"}"
#
#
#result:
#{
#  "ip": "some ip",
#  "mac": "some mac"
#}
############################




#Trust SelfSigned SSL/TLS Channel
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@ 
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy


#Generate Web Token (Basic Token)
Function Get-WebTokenBasic{

    [CmdletBinding()]
    Param(
    [Parameter(Mandatory = $true)][string]$Username,
    [Parameter(Mandatory = $true)][string]$Password
    )

$json=ConvertTo-Json (@{"username"="$Username";"password"="$Password";})
$token = (Invoke-WebRequest -Uri "https://URL/rest_login"  -Body $json -ContentType "application/json" -Method POST).content | Out-String | ConvertFrom-Json

$token = $token.access_token
$global:headers = @{auth="Basic $token"}

}

#Get IP or Mac from Servername
Function Get-DNSBluecatValues{
[CmdletBinding()]
Param(
    [Parameter(Mandatory = $true)][string]$ServerName
    
)

$json4= (@{"host"="$servername";}) | ConvertTo-Json

Try
{
    Get-WebTokenBasic
    $result = Invoke-WebRequest -Uri "https://URL/get_ip_infos/get_ip_infos_endpoint" -Headers $headers -Body $json4 -Method Post -ContentType "application/json"
    $global:result = $result | ConvertFrom-Json
    return $global:result
}
Catch
{
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    Write-Warning "Failed Authentication or Webrequest"
    Break
}


}
Continue reading...