Error “Cannot unregister the machine” on Jenkins, ‘kitchen test’ command

2017/04/06

Ok, it’s a hack… so don’t use it unless you need it, and on your own risk.
For some reason, although the Windows vagrant box is updated using Matt Wrock’s packer templates from here https://github.com/mwrock/packer-templates, and everything goes well, and also on the first manual kitchen test on the Jenkins server everything goes ok, when run from Jenkin’s pipeline mechanism, the box is not destroyed.
Three VirtualBox processes remain hanged in the system.
It’s not a clean solution, but having this error over and over again:

STDERR: There was an error while executing `VBoxManage`, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below.
Command: [“unregistervm”, “some GUID here”, “–delete”]
Stderr: VBoxManage.exe: error: Cannot unregister the machine ‘kitchen-your_cookbook-default-windows2012r2_default_some_numbers’ while it is locked
VBoxManage.exe: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component MachineWrap, interface IMachine, callee IUnknown

it’s really annoying, so until the final solution will reveal itself, this might also be a way:

$cookbook = ‘your_cookbook_name’
gwmi -Query “select * from win32_process where name = ‘virtualbox.exe'” | `
? { $_.CommandLine.Contains(“kitchen-$cookbook”)} | `
Select CommandLine, Handle | `
% { Get-Process -Id $_.Handle } | `
Stop-Process -Force -ErrorAction Continue

You’ll need to execute it from Groovy with the bat command, something like

bat “powershell -File \”../killVBoxes.ps1\” ${cookbookName}”

For the path of the PowerShell script you’ll need to provide the correct path.

Note: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.

Advertisements

Download OReilly free books with PowerShell through PasteBin

2017/01/10
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)] [string]$DestinationFolder,
    [Parameter(Mandatory=$false)] [string]$OReillyPasteBinRawUrl = ‘http://pastebin.com/raw/nyFtp2EG‘,
    [Parameter(Mandatory=$false)] [bool]$SimulateSleepBetweenDownloads = $true
)

Import-Module BitsTransfer

function Download-File
{
    param([string] $UrlSource, [string] $Destination)
    $random = Get-Random -Minimum 1 -Maximum 5
    Write-Output “Downloading $filename”
    Start-BitsTransfer -Source $UrlSource -Destination $Destination
    if ($SimulateSleepBetweenDownloads) {
        Write-Output ”    Sleeping $(4 + $random) seconds”
        Start-Sleep -s (4 + $random)
    }
}

$tmpFile = New-TemporaryFile
Set-Content -Path ($tmpFile.FullName) -Value ((Invoke-WebRequest -Uri $OReillyPasteBinRawUrl).Content)

$reader = [System.IO.File]::OpenText($tmpFile.FullName)
while($null -ne ($url = $reader.ReadLine())) {
    $filename = $URL.Substring($URL.LastIndexOf(“/”) + 1)
    $destPath = (Join-Path $DestinationFolder $filename)
    if (!(Test-Path $destPath)) {
        Download-File -UrlSource $url -Destination $destPath
    }
    else {
        if ((Get-Item $destPath).Length -le 0) {
            Download-File -UrlSource $url -Destination $destPath
        }
        else {
            Write-Output “Skipping $filename ; already downloaded”
        }
    }
}

After that, use the script like that:

.\downloadOreallyBooks.ps1 -DestinationFolder E:\temp\ -SimulateSleepBetweenDownloads $false

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Verify if a Chocolatey package is installed

2016/12/19
(choco list –lo | % { $_ -match “winmerge” }).contains($true)
(choco list –lo | % { $_ -match “sdfsdfds” }).contains($true)

Useful PowerShell profile code

2016/07/22

To check the location for your Powershell profile file, type $profile .
To reload your PowerShell profile, use & $profile .

Edit your PowerShell profile to set custom colors and console size as follow:

$host.UI.RawUI.BackgroundColor = ‘Gray’
$host.UI.RawUI.ForegroundColor = ‘Black’

$pshost = get-host
$pswindow = $pshost.ui.rawui

$newsize = $pswindow.buffersize
$newsize.height = 9000
$newsize.width = 140
$pswindow.buffersize = $newsize

$newsize = $pswindow.windowsize
$newsize.height = 65
$newsize.width = 140
$pswindow.windowsize = $newsize

# You’ll need a HOME variable defined as environment variable
cd $env:HOME

Clear-Host

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


PowerShell function for registry value test

2016/07/20

Below is a useful function for checking the existence and the value of a registry key.
Might need some rework, it’s not in a final version

function Test-RegistryValue
{
  param(
    [Parameter(Mandatory=$true)] [string]$Path,
    [Parameter(Mandatory=$true)] [string]$Name,
    [Parameter(Mandatory=$false)] $KeyValue
  )

  if( -not (Test-Path -Path $Path -PathType Container) ) {
    return $false
  }

  $properties = Get-ItemProperty -Path $Path
  if( -not $properties ) {
    return $false
  }
  else {
    $value = ($properties | Select-Object -ExpandProperty $Name)
    if ($value.ToString().ToLower() -eq $KeyValue.ToString().ToLower()) {
      return $true
    }
    else {
      return $false
    }
  }

  $member = Get-Member -InputObject $properties -Name $Name
  if( $member ) {
    return $true
  }
  else {
    return $false
  }
}

Note: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.


Upload a ZIP to Azure storage account in PowerShell

2016/06/23

This was tested under PowerShell 5, with Azure PowerShell module installed.

After you download your Azure publish settings file from https://manage.windowsazure.com/publishsettings/index?client=powershell&schemaVersion= you can use Get-AzureSubscription to choose a subscription for the upload (if you have several on your account)

if(-not (Get-Module Azure)) {
  Import-Module Azure
}

Import-AzurePublishSettingsFile “path/to/your/azure/publish/settings/file”

(Get-AzureSubscription).SubscriptionName # Choose subscription if several present

Select-AzureSubscription -SubscriptionName “YourSubscritionNameHere”
$storAcc = ‘companyartifacts’
$storCntr = ‘builds’
$blob = ‘Buildxyz.zip’
$key = (Get-AzureStorageKey -StorageAccountName $storAcc).Primary

$ctxt = New-AzureStorageContext -StorageAccountName $storAcc -StorageAccountKey $key

Write-Output “Uploading ZIP to Azure…”

Set-AzureStorageBlobContent -File “path\to\Buildxyz.zip” -Container $storCntr -Blob $blob -BlobType Block -Context $ctxt -Force

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Deleting folder SymLinks in PowerShell 4 without wiping folder content

2016/06/15

How ?
Use the old CMD for this:

cmd.exe /c rmdir “yourSymLinkFolder”

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.
Note 3: While I may have tested myself most of the bits of code posted here, please be aware that you’re trying the code/scripts at your own risk, and I take no responsibility for any damage that may occur on your system(s).


%d bloggers like this: