Creating Directories Including Parents using Chef on Windows

I’ve recently been building some test environments on Microsoft Windows 2008 R2 using Chef. One thing that Chef misses is an easy way to create parent directories if needed when creating a directory.

The standard method of creating a directory will not work if D:\foo\bar doesn’t already exist:

directory "D:\\foo\\bar\\buzz" do
   action :create
end

You can create a parent directories by placing each element of a path into an array, then loop through the array creating each folder:

%w[ D:\\foo \\foo\\bar \\foo\\bar\\baz ].each do |path|
   directory path do
      action :create
   end
end

I already had my path declared in a variable for other uses. I didn’t want to store it twice and I didn’t want to create a block of Ruby to try and break the path up from the variable.

After some research I discovered that its easier to simply run the New-Item command in a PowerShell block:

# Location of the install and patch directory
install_directory="D:\\foo\\bar\\buzz"

# Create the directory, including parents
powershell_script "create_install_directoy_if_not_exists" do
   guard_interpreter :powershell_script
   code "New-Item -ItemType Directory -Path #{install_directory} -Force"
   not_if "Test-Path #{install_directory}"
end

This will create the directory, including parent directories if needed. On Windows this appears to be the easiest way of coping with missing parent directories.

Facebooktwittergoogle_plusredditmail

Leave a Reply