Please note javascript is required for full website functionality.

Blog

Power Query: Find the Folder

6 March 2019

Welcome to our Power Query blog.  This week, I look at an example which uses some of the M functionality for dealing with files and folders.  

Last week, I created blank queries and used M code to extract data from a folder in Power Query.  In Power Query: One Folder, One Query, I created a query that contained similar data from a folder, which I could then combine.  This time, I am going to use a similar method and take a different path through the options so that I can view the subfolders in a folder.

I begin by creating a new query ‘From Folder’ by choosing this option from the ‘From File’ dropdown in the ‘New Query’ section of the ‘Get & Transform’ functionality on the ‘Data’ tab.

Power Query prompts me for the location of the folder and I choose to browse:

I find the folder which contains my ‘PQ Blogs’ folder.

In the preview, I can see a list of documents and workbooks, but no folders. Unlike the aim in Power Query: One Folder, One Query, this time I want to see all file types in the folder. I don’t want to combine the data; I want to edit it so that I can look for specific data in the folder.

Now I have chosen to edit the data, I can see the M code behind the query. 

= Folder.Files("C:\Users\kathr\OneDrive\Documents\PQ_StandardExpenses")

This is the same code used in last week’s blog.  In this case, I want to use Folder.Contents() instead of Folder.Files(), because I want to see the subfolders, and not just the files in the subfolders. 

The first row shows me the ‘PQ Blog’ folder. The Content column indicates that this is a table, and I can see the contents of that table (the files) by clicking on ‘Table’:

I want to just show Content which contains a table, which will allow me to only view folders.

However, I can’t do this via a filter since ‘Table’ is an entity and not a value – instead I need some M code to create a new column which does contain values.

The M code I have used is 

let

    Source = Folder.Contents("C:\Users\kathr\OneDrive\Documents\PQ_StandardExpenses"),

    FileType =Table.AddColumn(Source,"Folder",each Value.Is([Content],type table))

in

FileType  

This creates a Boolean – a column which is TRUE or FALSE – in this case, it is TRUE if Content contains a table.  I will look at the function Value.Is() in more detail in next week’s blog.

I can then filter on Folder:

and I am left with my filtered result, viz.

Come back next time for more ways to use Power Query!

Newsletter