Windows PowerShell 1.0 File Handling

From Techotopia
Revision as of 15:55, 8 December 2008 by Neil (Talk | contribs) (New page: The previous chapter of Windows PowerShell 1.0 Essentials covered the basics of working with file systems using Windows PowerShell. This chapter is designed to provide information of h...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The previous chapter of Windows PowerShell 1.0 Essentials covered the basics of working with file systems using Windows PowerShell. This chapter is designed to provide information of how to create and manipulate individual files using the PowerShell environment.

Getting File Properties

Basic information about a particular file is available through the Get-Item and Get-ItemProperty cmdlets:

PS C:\tmp> get-item test.txt


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\tmp


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         12/5/2008  12:12 PM         34 test.txt

Both of the above commands return a FileInfo object, from which specific file attributes may subsequently be extracted. For example, to obtain just the last write time:

PS C:\tmp> $myfile.lastaccesstime

Monday, December 08, 2008 6:59:48 AM

In fact, the FileInfo object provides a vast number of methods and properties, a full listing of which can be viewed using the get-member cmdlet:

PS C:\tmp> get-item test.txt | get-member

Changing File Properties =

The properties of a file are changed in Windows PowerShell using the Set-ItemProperty cmdlet together with the appropriate .NET [System.IO.FileAttributes] static member. For example, to set the ReadOnly attribute on a file:

PS C:\tmp> set-itemproperty test.txt -name attributes -value ([System.IO.FileAttributes]::ReadOnly)

Multiple properties may be set in a single command, providing that all the properties are joined using bxor operations. In the following example, the Hidden and ReadOnly attributes are set in a single operation:

PS C:\tmp> set-itemproperty test.txt -name attributes -value ([System.IO.FileAttributes]::ReadOnly -bxor 
[System.IO.FileAttributes]::Hidden)

A full list of file attributes provided through [System.IO.FileAttributes] is outlined in the following table:

Member

Description

ReadOnly The file is read-only.
Hidden The file is hidden, and thus is not included in an ordinary directory listing.
System The file is a system file. The file is part of the operating system or is used exclusively by the operating system.
Archive The file's archive status. Applications use this attribute to mark files for backup or removal.
Normal The file is normal and has no other attributes set. This attribute is valid only if used alone.