Get folder files recursively in Ruby, without empty folders

2017/03/09

I’ve used the code below to retrieve the files from a folder recursively when I needed to process only the files, but not the subfolders.
The files from subfolders are also included, but not the directories, I wanted especially to omit ” . ” and ” .. ” :

@files = ::Dir.glob(::File.join(source_folder, ‘**/*’), ::File::FNM_DOTMATCH).reject { |p| ::File.directory? p }

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.


Disable Skype ads

2017/03/06

Add to blocked sites the addresses apps.skype.com and g.msn.com.
This can be done through Control Panel settings or through the hosts file.

  • For the first method, go to Control Panel > Network and Internet > Internet Options > Security tab > Restricted Sites > open Sites and add the 2 websites to the list
  • For hosts file method, this file is generally found at C:\Windows\Systems32\drivers\etc ( unless you have a specific Windows folder, in which case try %WINDIR%\system32 ) ; it is usually a hidden folder, so you’ll have to display hidden files in Windows Explorer ( via View options -> Folder Options )
    Add to this file 2 lines with the 2 websites pointing to 0.0.0.0 or 127.0.0.1 (if in doubt, check the examples commented in the hosts file)

One more setting is needed:
Close Skype and then go to Users > [Your Windows Username] > AppData > Roaming > Skype > [Your Skype account name] > config.xml , open the file and search for AdvertPlaceholder , for which you’ll have to change the value of 1 to 0 .

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.


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.


Stub Chef guard_interpreter for ChefSpec test

2016/12/20

If you have a Chef cookbook with a resource containing a “guardian”, like, let’s say a PowerShell guard interpreter, you must stub the content of the Chef guard.
Here is an example of the resource using the guardian:

file “some_log_path” do
  guard_interpreter :powershell_script
  action :delete
  not_if “(ls -Dir ‘C:\temp’).Name.Contains(‘build’)”
end

Here’s how you have to construct your ChefSpec file:

describe ‘my_cookbook::my_recipe’ do
  let(:chef_run) do
    ChefSpec::ServerRunner.new do |node, server|
      stub_chef_server(node, server)
    end.converge(described_recipe)
  end

  before do
    stub_command(“(ls -Dir ‘C:\temp’).Name.Contains(‘build’)”).and_return(false)
  end

  it ‘does not raise an exception’ do
    expect { chef_run }.to_not raise_error
  end

  it ‘deletes the existing log file’ do
    expect(chef_run).to delete_file(‘C:\temp\releases\some_build\log.txt’)
  end
end


Verify if a Chocolatey package is installed

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

LWRP for deleting old builds

2016/12/07

In your cookbook, in libraries folder, create the following:

provider_cache_cleaner.rb

class BuildCacheCleaner
  # Provider for build_cache_cleaner
  class BuildCacheCleanerProvider < Chef::Provider::LWRPBase
    provides :build_cache_cleaner
    use_inline_resources
    action :delete do
      delete_count = 0
      if ::File.directory?(new_resource.cache_path)
        search_path = ::File.join(new_resource.cache_path.to_path, “#{new_resource.suffix}*\.#{new_resource.extension}”)
        cached_files = ::Dir.glob(search_path).sort_by { |f| ::File.ctime(f) }
        if cached_files.count > new_resource.keep_count
          delete_count = cached_files.count – new_resource.keep_count
        end
        files_to_delete = cached_files.first(delete_count)
        unless files_to_delete.empty?
          Chef::Log.info(“#{delete_count} cached builds will be deleted !”)
          files_to_delete.each do |file_name|
            Chef::Log.info(“Deleting file #{::File.basename(file_name)} …”)
            ::File.delete(file_name)
          end
        end
      end
      new_resource.updated_by_last_action(true) if delete_count > 0
    end
  end
end

resource_cache_cleaner.rb

class BuildCacheCleaner
  # Resource for build_cache_cleaner
  class BuildCacheCleanerResource < Chef::Resource::LWRPBase
    resource_name :build_cache_cleaner
    provides :build_cache_cleaner

    actions(:delete)
    default_action(:delete)

    attribute :keep_count, :kind_of => Integer, :required => false, :default => 5
    attribute :suffix, :kind_of => String, :required => false, :default => ‘Build’
    attribute :extension, :kind_of => String, :required => false, :default => ‘zip’
    attribute :cache_path, :kind_of => String, :required => false, :default => Chef::Config[:file_cache_path]
  end
end

string_util.rb

# String utility extension methods
class String
  def to_path(end_slash = false)
    “#{‘/’ if self[0] == ‘\\’}#{split(‘\\’).join(‘/’)}#{‘/’ if end_slash}”
  end
end

matchers.rb

# ChefSpec is a tool to unit test cookbooks in conjunction with rspec
# Learn more on the README or at https://github.com/sethvargo/chefspec.
if defined?(ChefSpec)
  def delete_build_cache_cleaner(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(:build_cache_cleaner, :delete, resource_name)
  end
end

In your recipe, use the resource as follow:

build_cache_cleaner ‘delete cached builds’ do
  keep_count 7
end

In your ChefSpec test, add the following:

it ‘deletes unused cached builds’ do
  expect(chef_run).to delete_build_cache_cleaner(‘delete cached builds’)
end

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).


Ping website with port using PowerShell

2016/12/07

Update
Thanks, jrlops ! There’s an embedded PowerShell way for doing this:

Test-NetConnection http:/mywebsite.mydomain -Port 1234

Using .Net object:

(New-Object System.Net.Sockets.TcpClient).Connect( `http://mywebsite.mydomain` , 1234 )

%d bloggers like this: