header image

W2KSG: Managing Folders

Posted by: | September 1, 2008 | No Comment |

The section in the scripting guide

Script Center Home > Microsoft Windows 2000 Scripting Guide > Scripting Concepts and Technologies for System Administration > Script Runtime Primer > FileSystemObject Managing Folders

Gives a number of examples of working with folders using the filsystemobject.  We can perform all of those actions very easily in PowerShell mainly using the *Item cmdlets

## Listing 4.6 – Test folder existence
Test-Path -Path "c:\temp"

## Listing 4.5 – Bind to folder
$folder = Get-Item -Path "c:\temp"

## Listing 4.7 – Create New Folder
New-Item -Path "C:\" -Name "NewFolder" -ItemType directory

## Listing 4.9 – Copy a folder
Copy-Item -Path "C:\NewFolder" -Destination "C:\New2Folder"

## Listing 4.10 Move Folder
#Move-Item -Path "C:\NewFolder" -Destination "F:\"  – won’t work

Copy-Item -Path "C:\NewFolder" -Destination "F:\NewFolder"
Remove-Item -Path "C:\NewFolder"

# Listing 4.11 Rename Folder
Rename-Item -Path "C:\New2Folder" -NewName "NewFolder"

## Listing 4.8 – Delete Folder
Remove-Item -Path "C:\NewFolder"
Remove-Item -Path "F:\NewFolder"

Testing for existence (4.6) is done with Test-Path which returns true if it exists and false if it doesn’t. Get-Item (4.5) allows us to work with the folder but no the files in the folder.  When creating a new folder (4.7) we have to give the type – directory here.  To create a file type is set to file.

Moving a folder is a bit awkward (4.10) – Move-Item doesn’t work across volumes so we need a copy and delete.  May be a safer option as you can verify the copy has worked before performing the delete.  The rename and delete work as you would expect.

These cmdlets also work on files.

Because of the provider functionality they will work in providers such as PSCX AD provider as well as the filesystem.  Move-Item is one of the easiest ways I know to move a user between OUs.

 

Share this post :

 

Technorati Tags: ,

under: PowerShell original