‘PowerCLI and the Tagging Service apis’

Really good stuff !

https://blogs.vmware.com/performance/2019/06/writing-performant-tagging-code-tips-and-tricks-for-powercli.html

 

Advertisements

Matching physical disk in Dell R720 with vSan disk using naa and perccli

Really short:

check you naa in vsphere/vsan you are looking for, then using perccli installed in your esxi use:

./perccli /c0 show all | grep -i -B6 ‘WWN = 58cf32ee203db4d4’

Drive /c0/e15/s4 device attributes :
==================================
Manufacturer Id = TOSHIBA
Model Number = PX05SMB080Y
NAND Vendor = NA
SN = 6820A0FGTEFE
WWN = 58cf32ee203db4d4

Where, s4 is your slot where the disk resides, and you can also double check via idrac if s/n matches the drive in slot.

Baseline groups with powercli

Ok, i have no idea how EXACTLY that works, nobody could explain this to me, including my vmware TAM. But this it what i came up with. It’s only useful i suppose when you are dealing with a lot of update managers/baselines groups.

$JSESSION is something that comes up in your cookie after you have logged in to your webclient. You can install an addon into your chrome/firefox/etc… that shows you your cookies . I could not figure out how to obtain JSESSION variable automatically.  I used HTML5 webclient + fiddler in order to check how the calls were made and tried to reproduce them. Everything works as expected .

code:

 


function get-VUMnodeid($VC,$JSESSION){
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
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
$JSESSION= $JSESSION -replace ";"
$uri = 'https://'+$VC+'/ui/vum-ui/rest/vcenters'
$cookie = New-Object System.Net.Cookie
$cookie.Name='JSESSIONID'
$cookie.Value=$JSESSION
$cookie.Domain = 'cookie.domain.something.com'
$session = New-object Microsoft.PowerShell.Commands.WebRequestSession
$session.Cookies.Add($Cookie)
#Invoke-WebRequest -uri $uri -WebSession:$session
$request = ((Invoke-WebRequest -uri $uri -WebSession:$session).Content |convertfrom-Json).GetEnumerator() | ?{$_.name -eq $VC}
return $request.nodeid
}
function get-baselinegroup($VC,$JSESSION){
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
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
$JSESSION= $JSESSION -replace ";"
$vumid = get-VUMnodeid -vc $VC
$uri = 'https://'+$VC+'/ui/vum-ui/rest/nodes/'+$vumid+'/baselineGroups/'
$session = New-object Microsoft.PowerShell.Commands.WebRequestSession
#$cookiestr = 'Cookie: JSESSIONID=C164315B4958845216338B7C3F568090;'
#$cookiestr = 'Cookie: JSESSIONID=AE57E580958B38E21D2B892840BC8A6D; JSESSIONID=60F391E14417C6D581A34BBF01E03DF0; VSPHERE-UI-XSRF-TOKEN=7fff48d9-54fc-4244-98ba-4a7513858476; VSPHERE-USERNAME=gregk%40management.is; VSPHERE-CLIENT-SESSION-INDEX=_ea276e26b355abc989243d26ecbd4958; _pk_id.1.da8d=65733ab98c5fe089.1548769895.4.1549275686.1549271755..a6c285c80359fd81a3dbc83835bbca941eae248ec84b999da3d8fe12190ebb39'
#$cookiestrarray = $cookiestr.split()|?{$_ -match 'JSESSION'} |% {$_ -replace ";"}|%{$_.split('=')[1]}
$cookie = New-Object System.Net.Cookie
$cookie.Name='JSESSIONID'
$cookie.Value=$JSESSION
$cookie.Domain = $VC
$session.Cookies.Add($Cookie)

$session.headers.Add('Accept-Language',' en-US,en')
$session.headers.Add('Accept-Encoding','application/json')
#Invoke-WebRequest -uri $uri -WebSession:$session
write-host $uri
$request = ((Invoke-WebRequest -uri $uri -WebSession:$session).Content |convertfrom-Json).GetEnumerator()
return $request
}

 
function Get-BaselinegroupBaselines($VC,$BGid,$JSESSION){
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
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
#cookiestr the JSESSIONID has to be the right one
$vumid = get-VUMnodeid -vc $VC
$uri = 'https://'+$VC+'/ui/vum-ui/rest/nodes/'+$vumid+'/baselineGroups/'+$BGid
$session = New-object Microsoft.PowerShell.Commands.WebRequestSession
#$cookiestr = 'JSESSIONID=C164315B4958845216338B7C3F568090;'

$JSESSION= $JSESSION -replace ";"
$cookie = New-Object System.Net.Cookie
$cookie.Name='JSESSIONID'
$cookie.Value=$JSESSION
$cookie.Domain = $VC
$session.Cookies.Add($Cookie)

$session.headers.Add('Accept-Language',' en-US,en')
$session.headers.Add('Accept-Encoding','application/json')

$parentBG = (Get-Baselinegroup -jsession $JSESSION -vc $vc|?{$_.id -eq $bgId}).Name
$request = ((Invoke-WebRequest -uri $uri -WebSession:$session).Content |convertfrom-Json).Updates | select -unique -property baselineName| select *, @{n='parentBG';e={$parentBG}}
return $request
}

$VC should be your virtualcenter at which VUM is registered, your VC can be in linked mode as well. When you will open fiddler you will see that you can translate even creating baselinegroups , add something to baseline groups etc etc.. All we have to have is that JSESSION cookie with us. Heh.. before that i automated even Internet Explorer to get this cookie automatically but i failed at it ,as i could not get THAT PARTICULAR JSESSION cookie, i saw other cookies but not jsession so i gave up, and if i have to do now work at a lot of baselinegroups i just catch that JSESSION from cookie in browser addon.

cross vmotion between virtual center in different sso

https://blogs.vmware.com/PowerCLI/2017/01/spotlight-move-vm-cmdlet.html

http://www.virtuallyghetto.com/2015/02/did-you-know-of-an-additional-cool-vmotion-capability-in-vsphere-6-0.html

http://www.virtuallyghetto.com/2016/05/automating-cross-vcenter-vmotion-xvc-vmotion-between-the-same-different-sso-domain.html

 

monitoring path of exile prices

I know this has nothing to do with VMware, or powershell … i wrote this to check some price on path of exile, and get notification … (beep), when item is affordable. Script does not need explanation i guess since it’s just few lines. Link are the poe.trade link you would get after creating a search criteria for item.

Not the best way, but it does the job.


While (0 -ne 1 ) {
$links = @(
'http://poe.trade/search/yugakakekutusa',
'other link',
)

foreach ($link in $links){
$data = (Invoke-WebRequest -Uri $link)
$items = $data.ParsedHtml.getElementsByTagName('tbody') |? {$_.outerHTML -match "id=item-container"}
foreach ($item in $items)
{
$res = ([regex]::Matches((($item.outerHTML[0..350] -join '') -split '>')[0],'data-(name|buyout|ign)="[^"]*"')).value
''| select @{n='Item';e={$res[0].split('=')[1]}}, @{n='price';e={$res[2].split('=')[1]}}, @{n='seller';e={$res[1].split('=')[1]}}, @{n='Link';e={$link}}
if($res) {[console]::Beep(500,200)}
}
Start-Sleep -Seconds 1
}
Start-Sleep -Seconds 30
write-host "next run"
}

Get-DeepLtranslation translating straight from your powershell

tt
I was doing my dutch course homework today, and i found it a bit tedious to use browser for translation. This + the fact that i want to write myself some dutch-polish quiz, so i can memorize words better led me to write this tiny function.

The DeepL translator website can be found here https://www.deepl.com/translator

This is a tiny function that would just use the ‘word/1 sentence’ mode. It worked today, not sure if it will be working in later months/years. This was made in really quick/dirty way, as i still need to write my homework today 😉 I wrote it in 15 minutes, so don’t expect fireworks, it does what it does, it translates 😉 You can use different languages using variables fromLang and toLang.

function get-DeepLtranslation ($sentence, $fromLang, $toLang)
{
#Languages available: PL,EN,NL,ES,IT,FR
$url = "https://www.deepl.com/jsonrpc"
$call = '{"jsonrpc":"2.0","method":"LMT_handle_jobs","params":{"jobs":[{"kind":"default","raw_en_sentence":"'+$sentence+'"}],"lang":{"user_preferred_langs":["EN","PL","NL"],"source_lang_user_selected":"'+$fromLang+'","target_lang":"'+$toLang+'"},"priority":-1},"id":15}'
$bytes = [System.Text.Encoding]::ASCII.GetBytes($call)
$web = [System.Net.WebRequest]::Create($url)
$web.Method = "POST"
$web.ContentLength = $bytes.Length
$web.ContentType = "application/x-www-form-urlencoded"
$stream = $web.GetRequestStream()
$stream.Write($bytes,0,$bytes.Length)
$stream.close()
$reader = New-Object System.IO.Streamreader -ArgumentList $web.GetResponse().GetResponseStream()
$answer = ($reader.ReadToEnd()|ConvertFrom-Json).result.translations.beams | select -ExpandProperty 'postprocessed_sentence'
$reader.Close()
return $answer
}

I am not sure why it does not work with the polish single word. IT does translate it though on the website(blue)

2t

When put in sentence that will work.

3t

What i also saw, is that sometimes calls to dict.deepl.com are being made.

I don’t have time right now to dig into this, but for some words you can utilize those:

https://dict.deepl.com/polish-english/search?ajax=1&query=jab%C5%82ko&source=polish&onlyDictEntries=1&translator=dnsof7h3k2lgh3gda&delay=300&jsStatus=0&kind=full&eventkind=keyup&forleftside=true

calls. Behind it’s this :

https://dict.deepl.com/english-polish/search?source=auto&query=%C5%82%C3%B3d%C5%BA

So you can get the translation like this:

(Invoke-WebRequest -Uri ‘https://dict.deepl.com/polish-english/search?ajax=1&query=jab%C5%82ko&source
=polish&onlyDictEntries=1&translator=dnsof7h3k2lgh3gda&delay=300&jsStatus=0&kind=full&eventkind=keyup&forleftside=true’).links[0].outerText
jabłko

That would have to be still converted to proper polish.

I think that something is going wrong when trying to translate words that have polish ‘ogonki’, and char encoding has something to do with it.

Sample send receive Lync / Skype for business messages using powershell

Before you start you need to obtain the Lync SDK package (https://download.microsoft.com/download/0/5/6/056013D5-98F8-4B79-88EF-D221E519C37F/lyncsdk.exe)

I had hard time to have it working with listening what ‘other’ people are writing in the conversation. Thanks to this post(‘John O’ reply) i was able to properly hook the event(to the right participant).
The ‘what*’, was aimed at message: “What is 2+4” or “what is 10*3” for example.
In response you should get the reply with the result.

If you want to test it with ‘somebody’.

cd "C:\Program Files (x86)\Microsoft Office\Office15\lyncsdk\Assemblies\Desktop"
Import-Module .\Microsoft.Lync.Model.dll
$Client = [Microsoft.Lync.Model.LyncClient]::GetClient()
$Conversation = $client.ConversationManager.AddConversation()
$person=$client.ContactManager.GetContactByUri('person@domain.com')
$conversation.AddParticipant($person)


Get-EventSubscriber|Unregister-Event
  # For each participant in the conversation
  $conversation.Participants | Where { !$_.IsSelf } | foreach {
    Register-ObjectEvent -InputObject $_.Modalities[1] -EventName "InstantMessageReceived" -SourceIdentifier "person $i" -action { 
    $global:conv = $event
    $msg = $conv.SourceEventArgs.Text.trim()
    write-host $msg
    switch -Wildcard ($msg) {
     "What*" {$Conversation.Modalities['InstantMessage'].BeginSendMessage((Invoke-Expression $msg.split()[-1]), {}, 0)}
     "Hello" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Hello human", {}, 0)}
     "stupid robot" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Humanity is overrated", {}, 0)}
    }
    }
    $i++
   }

Or if you don’t have friends and want to test it against yourself (2nd client running).

cd "C:\Program Files (x86)\Microsoft Office\Office15\lyncsdk\Assemblies\Desktop"
Import-Module .\Microsoft.Lync.Model.dll
$Client = [Microsoft.Lync.Model.LyncClient]::GetClient()
$Conversation = $client.ConversationManager.AddConversation()
$conversation.AddParticipant($client.Self.Contact)

Get-EventSubscriber|Unregister-Event
  $conversation.Participants[0]| foreach {
    Register-ObjectEvent -InputObject $_.Modalities[1] -EventName "InstantMessageReceived" -SourceIdentifier "person $i" -action { 
    $global:conv = $event
    $msg = $conv.SourceEventArgs.Text.trim()
    write-host $msg
    #if ($msg -like 'What*') {$Conversation.Modalities['InstantMessage'].BeginSendMessage((Invoke-Expression $msg.split()[-1]), {}, 0)}
    switch -Wildcard ($msg) {
     "What*" {$Conversation.Modalities['InstantMessage'].BeginSendMessage((Invoke-Expression $msg.split()[-1]), {}, 0)}
     "Hello" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Hello human", {}, 0)}
     "stupid robot" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Humanity is overrated", {}, 0)}
    }
    }
    $i++
   }

You can send message using the PS session anytime then:
$Conversation.Modalities[‘InstantMessage’].BeginSendMessage(‘text’, {}, 0)}
Some useful links:
https://msdn.microsoft.com/en-us/library/office/jj937273.aspx
https://msdn.microsoft.com/en-us/library/office/hh243705(v=office.14).aspx
https://msdn.microsoft.com/en-us/library/office/jj933215.aspx
https://msdn.microsoft.com/en-us/library/office/jj937298.aspx
https://msdn.microsoft.com/en-us/library/office/jj933248.aspx
https://blogs.technet.microsoft.com/heyscriptingguy/2011/06/16/use-asynchronous-event-handling-in-powershell/