Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  Advanced Search 


August 01, 2007

PowerShell One-Liners for Managing the File System

Simple commands let you copy, move, rename, and delete files and folders
RSS
View this exclusive article with VIP access -- click here to join | See More Systems Administration Articles Here | Reprints
Or sign up for our VIP Monthly Pass!

Download the Code Here

Executive Summary:
Windows PowerShell can help ease your Windows operating system (OS) file management.
Windows PowerShell includes many built-in aliases for cmdlets to make writing code easier.
Simple Windows PowerShell "one-liners" can be used to retrieve files and folders, copy them, move them, and create or delete them.

If you’ve used the command prompt to manage files and folders on your Windows systems, you know how easy many file-management tasks can be. You’ll find you can perform many of these tasks just as easily by using Windows PowerShell. In fact, you can take advantage of the full scripting and pipelining capabilities of PowerShell to carry out your file-system operations.

Getting Started, Getting Help
As you move into PowerShell, you should familiarize yourself with the basic commands—the “one-liners”—that let you access and manipulate files and folders. The best place to begin is with one of the most basic file-system commands: retrieving the name of the current working directory. To do so, enter the following command at the PowerShell command prompt:

get-location

As Figure 1 shows, the get-location cmdlet retrieves the name of the working directory (C, in this example) and returns it to the PowerShell window.

You might want to access information about how a particular cmdlet works and the parameters it takes. You can use the get-help cmdlet to retrieve the Help file for any cmdlet. For example, to retrieve the Help file for the get-location cmdlet, enter

get-help get-location

Figure 2 shows the result of running this command. The get-help cmdlet comes in quite handy no matter how experienced you are with PowerShell. You can use the get-command cmdlet to retrieve a list of all available commands.

In addition to being able to determine the current working directory, you might want to change that directory. The following command changes the working directory to C:\Program Files\Microsoft Office :

set-location -path `
 "c:\program files\microsoft office"

The command uses the set-location cmdlet to set the directory and uses the -path parameter to specify the name of the new working directory. The back tick at the end of the first line lets PowerShell know that the command continues to a second line. On the second line, note that the -path parameter value is enclosed in quotes. Using quotes is necessary only if the value contains spaces. Also note that you don’t always need to include the name of the parameter; you can specify only the parameter value if that value is in the expected position. For example, the following command returns the same result as the preceding command:

set-location `
 "c:\program files\microsoft office"

Saving Time with Aliases
You might find that some of these cmdlet names are cumbersome to work with, especially when typing them repeatedly. Fortunately, PowerShell includes several built-in aliases that you can substitute for the cmdlet name. For example, you can use the following command to change the working directory back to the C root directory:

cd c:\

The cd keyword is a built-in alias for the set-location cmdlet. Many cmdlets have associated aliases. For example, you can use the help alias to refer to the get-help cmdlet or the pwd alias to refer to the get-location cmdlet. To see a complete list of aliases, enter

gal | select name, definition

The statement uses the gal alias to refer to the get-alias cmdlet, which retrieves a list of aliases. The results are sent down the pipeline, represented by the pipe character (|), to the second command. That command uses the select alias to refer to the select-object cmdlet and specifies the name and definition properties for each alias. As Figure 3 shows, the command returns only the values associated with those properties.

You can also view a list of aliases assigned to a specific cmdlet:

gal | select name, definition | where `
 {$_.definition -eq "set-location"}

This statement retrieves a list of aliases and pipes them to the select-object cmdlet, which then pipes its results to a where-object cmdlet (represented by the where alias). The where-object cmdlet includes an expression enclosed in curly brackets. The expression uses the $_ symbol to reference the current value in the pipeline. The definition property is specified by adding a period and the property name after $_. The expression then specifies that the property value must equal (-eq) the specified string (in this example, set-location). As Figure 4 shows, the statement returns only those aliases associated with the set-location cmdlet.

Basic File Manipulation
Now that you have an idea of how to use aliases, let’s look at how to retrieve a list of files in a folder. First, download and run the PS_OneLiners_FileSystem_Setup.ps1 script, which creates a folder named C:\ArchivedFiles, populates it with eight files, and creates an empty folder named C:\ArchivedFiles2006. (If you're uncertain of how to run a PowerShell script, see the "What Can I Do With Windows PowerShell?" Web page at http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/invoke-expression.mspx.) Then, enter the following command to return a list of the files in C:\ArchivedFiles:

dir c:\archivedfiles

The dir alias refers to the get-childitem cmdlet, which retrieves items in a collection. The collection in this case is the C:\ArchivedFiles folder. As Figure 5 shows, the folder contains eight text files.

You can also use wildcards to restrict which files are returned. For example, the following command returns only files whose name begins with “2007”:

dir c:\archivedfiles\2007*

The asterisk indicates that zero or more characters can follow "2007" in the file name. Figure 6 shows the result of running this command.

Because you can't include an asterisk in a filename, there’s no problem using the asterisk as a wildcard in your commands. However, you can use brackets in filenames and brackets can also be wildcards, so you must take a different approach when specifying a bracket that’s part of the filename. First, escape the bracket by preceding it with two back ticks (``), then enclose the entire pathname in single quotes, as in the following example:

dir 'c:\archivedfiles\2006archive``[01*'

As Figure 7 shows, this command retrieves any file that begins with “2006archive[01” in the filename.

You can also use PowerShell to copy files from one location to another. The following command copies the files whose name begins with "2006" from the C:\ArchivedFiles folder to the C:\ArchivedFiles2006 folder:

copy c:\archivedfiles\2006* `
 c:\archivedfiles2006

The copy alias refers to the copy-item cmdlet. The first parameter value specifies the source files and the second value specifies the destination. You can retrieve files from or copy files to a folder on a remote server:

copy c:\archivedfiles\2006* `
 \\server05\c\archivedfiles2006

The second argument contains the path to a folder on server05. You can also move files from one folder to another:

move c:\archivedfiles\2006* `
 \\server05\c\archivedfiles2006

The move alias refers to the move-item cmdlet. The above command moves all files that begin with “2006” to the ArchivedFiles2006 folder on server05.

PowerShell one-liners are handy for creating files and folders as well. For example, the following command creates a folder name ArchivedFiles on the C share of server05:

ni \\server05\c\ArchivedFiles `
 -type directory

The ni alias refers to the new-item cmdlet, and the -type parameter specifies that the new item will be a directory. Here's how to use the new-item cmdlet to create an empty file:

ni \\server05\c\archivedfiles\2006Archives.txt `
 -type file

This time the command creates a file (-type file) named 2006Archives.txt in the ArchivedFiles directory.

To rename a file, you can use a command such as

ren \\server05\c\archivedfiles\2006Archives.txt `
 2006Archives_complete.txt

The ren alias refers to the rename-item cmdlet. The first parameter specifies the full pathname of the original file, and the second parameter specifies the new filename.

To delete one or more files, you'd use a one-liner such as

del \\server05\c\archivedfiles\*.txt

The del alias refers to the remove-item cmdlet, and the parameter specifies the directory and filename. This cmdlet removes all files (as indicated by the asterisk wildcard) that have a .txt extension. To delete the folder itself, enter

del \\server05\c\archivedfiles

Retrieving and Adding Content to Files
That’s all there is to copying, moving, renaming, and deleting files and folders. But you can also use PowerShell to retrieve the content of files. The following command retrieves the content of the 2005archives.txt file:

gc \\server05\c\archivedfiles\2005archives.txt

The command uses the gc alias to refer to the get-content cmdlet, and the parameter specifies the path and name of the file. Figure 8 shows the content that this sample command returns.

You can use a wildcard to retrieve the contents of multiple files. The asterisk in the command

gc \\server05\c\archivedfiles\*.txt

specifies that the content of all text files should be returned. As Figure 9 shows, this command returns the complete content from each of three files.

It’s important to know how the get-content cmdlet returns data. By default, the cmdlet returns each line in a file as a string that's part of a collection. Consequently, you can use string methods to modify the returned data. To view the methods available to the collection of strings returned from the 2004archives.txt file, enter

gc \\server05\c\archivedfiles\2004archives.txt `
 | gm -memberType method

After the get-content cmdlet retrieves the content of the file, the results are piped to the get-member cmdlet (represented by the gm alias), which retrieves the object’s members. In this case, the get-member cmdlet uses the -memberType parameter to return only methods. Figure 10 shows the result of this command.

You can even add content to new or existing files. For example, the following command creates a file named 2004archives.txt and adds content to the file:

sc \\server05\c\archivedfiles\2004archives.txt `
 -value "This is the content for the 2004archives.txt file."

The sc alias refers to the set-content cmdlet. The first parameter specifies the path and name of the new file. The second parameter (-value) specifies the string value that's added to the file.

The set-content cmdlet also lets you replace the content in an existing file. For example, the command

sc \\server05\c\archivedfiles\2004archives.txt `
 -value "This is the new, updated content " `
 + "for the 2004archives.txt file."

replaces all text in the original file with the new text. Note the use of the plus sign (+) on the third line. When a string continues to a new line, you need to treat the parts as separate strings and use PowerShell's concatenation operator (+) to join them.

The Power of One-Liners
As these sample one-liners demonstrate, you can use PowerShell to perform numerous file- and folder-related tasks. As you become comfortable with these basic skills, you’ll be able to incorporate them into other, more complex tasks. And you’ll find that many of the PowerShell principles you learn here also apply to other areas, helping to make PowerShell a key resource in your administrative toolbox.

End of Article



Reader Comments
Where is the rest of the article?

Gary_Pietila@cable.comcast.com February 12, 2008 (Article Rating: )


great stuff for a beginner like me.

jason402 March 06, 2008 (Article Rating: )


If you liked this article, you might want to check out the other two articles in this series if you haven't already done so. Those articles are:
"PowerShell One-Liners for Accessing WMI" (InstantDoc ID 96666)
"PowerShell One-Liners for Managing Events" (InstantDoc ID 96875)

KBemowski March 07, 2008 (Article Rating: )


You must log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
The Memory-Optimization Hoax

Don't believe the hype. At best, RAM optimizers have no effect. At worst, they seriously degrade performance. ...

Managing Virtual Sprawl

As some wise person once said, nothing is ever truly free. Such is the case with VMs, which can quickly mutate from a cost-reducing Dr. Jekyll into a time-consuming, profligate nightmare that would do Mr. Hyde proud. ...

What service packs and fixes are available?

...


Related Articles The Trick to Installing Fonts with a VBScript or PowerShell Script

PowerShell Queries for Failed Services on Remote Machines

Making PowerShell's Out-Printer Cmdlet Easier to Use

Essential Windows PowerShell Commands

Related Events Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting Resources Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Critical Challenges of ESI & Email Retention
Are you storing too much electronic information? Get expert legal advice and better understanding of what you are required to do as an IT professional.

Become a fan of Windows IT Pro on Facebook!
Join us on Facebook and be a fan of Windows IT Pro!

Sustainable Compliance: Are You Having a Resource Crisis?
Read this white paper to examine trends in compliance and security management and review approaches to reducing the cost and operational burden of compliance.

Rev Up Your IT Know-How with Our Recharged Magazine!
The improved Windows IT Pro provides trusted IT content with an enhanced new look and functionality! Get comprehensive coverage of industry topics, expert advice, and real-world solutions—PLUS access to over 10,000 articles online. Order today!

Get It All with Windows IT Pro VIP
Stock your IT toolbox with every solution ever printed in Windows IT Pro and SQL Server Magazine plus bonus Web-exclusive content on hot topics. Subscribe to receive the VIP CD and a subscription to your choice of Windows IT Pro or SQL Server Magazine!



Order Your Fundamentals CD Today!
Gain an introduction to Exchange, learn server security requirements, and understand how unified communications can play a role in your messaging strategies with this free Exchange CD.
Windows IT Pro Home Register About Us Affiliates / Licensing Media Kit Contact Us/Customer Service  
SQL Connected Home IT Library SuperSite FAQ Wininfo News
Europe Edition Office & SharePoint Pro Windows Dev Pro Windows Excavator 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing