Friday, January 27, 2017

Copying only directories in PowerShell

Suppose you wanted to copy only a directory structure, without the files inside. In PowerShell, you might try to use Get-ChildItem with the -Directory switch to get only directories, then pipe them into some script block that copies them. The trouble with that is that you need to compute the resulting path by replacing the source path component with the destination one, which is doable, but a little messy.

Unfortunately, Copy-Item has no -Directory switch. It does, however, have -Filter, which technically takes a string, but you can almost think of it as receiving a script block. In this case, -Filter {PSIsContainer -eq $true} solves the task, as does simply -Filter PSIsContainer. That variable is only true for containers: directories, in the case of file system objects.

No comments:

Post a Comment