Working with File Systems in Windows PowerShell 1.0

From Techotopia
Revision as of 20:14, 27 October 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0"> " to "<table border="0" cellspacing="0" width="100%">")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
PreviousTable of ContentsNext
Windows PowerShell 1.0 FunctionsWindows PowerShell 1.0 File Handling


Purchase and download the full PDF version of this PowerShell eBook for only $8.99


Given that Windows PowerShell is primarily targeted at easing the job of system administrators there is a good chance that part of developing scripts is going to involve interacting with Windows files and file systems. This chapter will focus on working with file systems with Windows PowerShell, while the next chapter, entitled Windows PowerShell 1.0 File Handling, will cover working with the contents of individual files.


Contents


Windows PowerShell File System Cmdlets

Windows PowerShell provides a collection of cmdlets specifically for the purposes of interacting with file systems. Each command is accessible in a number of different ways:

  • Cmdlet name - The standard cmdlet name, such as Get-Location.
  • Alias - An preconfigured, abbreviated alias for the cmdlet name such as gl for Get-Location.
  • cmd.exe command - The cmd.exe equivalent command to help users familiar with the Windows Command Prompt migrate to PowerShell.
  • UNIX/Linux sh command The UNIX/Linux shell equivalent command to help user migrate skills to Windows PowerShell.

The following table lists the key file system related cmdlets together with the alias, cmd and UNIX shell alternatives: <google>ADSDAQBOX_FLOW</google>

Cmdlet Name

Alias

Cmd Command

UNIX sh Command

Description

Clear-Item cli N/A N/A Clears content of a file
Copy-Item cpi copy cp Copies file or folder
Get-Content gc type cat Gets the content of a file
Get-Location gl cd pwd Gets the current directory
Move-Item mi move mv Moves file or folder
New-Item ni, md N/A N/A Creates file or folder
Remove-Item ri del, rd rm, rmdir Deletes file or folder
Rename-Item rni, rn ren mv Renames file or folder
Set-Content sc N/A N/A Sets file content
Set-Item si N/A N/A Sets file content
Set-Location sl cd, chdir cd, chdir Sets current directory

Getting Disk Drive Information

A listing of drives may be obtained from within Windows PowerShell using either the Get-PSDrive cmdlet, the GetDrive() method of the .NET System.IO.DriveInfo class, or by accessing the Windows Management Instrumentation (WMI) Win32_LogicalDisk class:

PS C:\Users\Administrator> get-psdrive

Name       Provider      Root                                                       CurrentLocation
----       --------      ----                                                       ---------------
A          FileSystem    A:\
Alias      Alias
C          FileSystem    C:\                                                    Users\Administrator
cert       Certificate   \
D          FileSystem    D:\
Env        Environment
Function   Function
HKCU       Registry      HKEY_CURRENT_USER
HKLM       Registry      HKEY_LOCAL_MACHINE
Variable   Variable

Clearly, the Get-PSDrive lists all drives in addition to the physical drives on the system (including the virtual drives such as those used to store Windows PowerShell variables and functions). To restrict the listing to physical drives containing file systems, the search needs to be restricted to file system providers:

PS C:\Users\Administrator> Get-PSDrive -psprovider filesystem

Name       Provider      Root                                                       CurrentLocation
----       --------      ----                                                       ---------------
A          FileSystem    A:\
C          FileSystem    C:\                                                    Users\Administrator
D          FileSystem    D:\

Alternatively, the following example demonstrates the use of the .NET [System.IO.DriveInfo]::GetDrives() method:

PS C:\Users\Administrator> [System.IO.DriveInfo]::GetDrives()


Name               : A:\
DriveType          : Removable
DriveFormat        :
IsReady            : False
AvailableFreeSpace :
TotalFreeSpace     :
TotalSize          :
RootDirectory      : A:\
VolumeLabel        :

Name               : C:\
DriveType          : Fixed
DriveFormat        : NTFS
IsReady            : True
AvailableFreeSpace : 9110175744
TotalFreeSpace     : 9110175744
TotalSize          : 17177767936
RootDirectory      : C:\
VolumeLabel        :

Name               : D:\
DriveType          : CDRom
DriveFormat        : CDFS
IsReady            : True
AvailableFreeSpace : 0
TotalFreeSpace     : 0
TotalSize          : 4329725952
RootDirectory      : D:\
VolumeLabel        : Fedora-9-Live-i6

Finally, the WMI Win32_LogicalDisk object may be accessed through the use of the get-wmiobject cmdlet:

PS C:\Users\Administrator> get-wmiobject Win32_LogicalDisk


DeviceID     : A:
DriveType    : 2
ProviderName :
FreeSpace    :
Size         :
VolumeName   :

DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 9110175744
Size         : 17177767936
VolumeName   :

DeviceID     : D:
DriveType    : 5
ProviderName :
FreeSpace    : 0
Size         : 4329725952
VolumeName   : Fedora-9-Live-i6

Individual attributes, such as the amount of free space on a drive, may be obtained through the .NET System.IO.DriveInfo or WMI Win32_LogicalDisk classes:

PS C:\Users\Administrator> $mydrive = new-object System.IO.DriveInfo("C")
PS C:\Users\Administrator> $mydrive.TotalFreeSpace
9110175744

A full listing of the properties and methods available for a DriveInfo object may be obtained using the Get-Member cmdlet:

PS C:\Users\Administrator> new-object System.IO.DriveInfo("C") | get-member


   TypeName: System.IO.DriveInfo

Name                   MemberType Definition
----                   ---------- ----------
Equals                 Method     System.Boolean Equals(Object obj)
GetHashCode            Method     System.Int32 GetHashCode()
GetType                Method     System.Type GetType()
get_AvailableFreeSpace Method     System.Int64 get_AvailableFreeSpace()
get_DriveFormat        Method     System.String get_DriveFormat()
get_DriveType          Method     System.IO.DriveType get_DriveType()
get_IsReady            Method     System.Boolean get_IsReady()
get_Name               Method     System.String get_Name()
get_RootDirectory      Method     System.IO.DirectoryInfo get_RootDirectory()
get_TotalFreeSpace     Method     System.Int64 get_TotalFreeSpace()
get_TotalSize          Method     System.Int64 get_TotalSize()
get_VolumeLabel        Method     System.String get_VolumeLabel()
set_VolumeLabel        Method     System.Void set_VolumeLabel(String value)
ToString               Method     System.String ToString()
AvailableFreeSpace     Property   System.Int64 AvailableFreeSpace {get;}
DriveFormat            Property   System.String DriveFormat {get;}
DriveType              Property   System.IO.DriveType DriveType {get;}
IsReady                Property   System.Boolean IsReady {get;}
Name                   Property   System.String Name {get;}
RootDirectory          Property   System.IO.DirectoryInfo RootDirectory {get;}
TotalFreeSpace         Property   System.Int64 TotalFreeSpace {get;}
TotalSize              Property   System.Int64 TotalSize {get;}
VolumeLabel            Property   System.String VolumeLabel {get;set;}

For example, the drive format may be obtained either using the get_DriveFormat() method, or by reference to the DriveFormat property:

PS C:\Users\Administrator> $mydrive.get_driveformat()
NTFS

PS C:\Users\Administrator> $mydrive.DriveFormat
NTFS

Alternatively, the WMI Win32_LogicalDisk object may be accessed as follows:

$mydrive = Get-WmiObject Win32_logicaldisk -Filter "DeviceID = 'C:'"
PS C:\Users\Administrator> $mydrive.FreeSpace
9110175744

Once again, the full complement of properties and methods available may be obtained using the Get-Member cmdlet:

PS C:\Users\Administrator> Get-WmiObject Win32_logicaldisk -Filter "DeviceID = 'C:'" | get-member


   TypeName: System.Management.ManagementObject#root\cimv2\Win32_LogicalDisk

Name                         MemberType   Definition
----                         ----------   ----------
Chkdsk                       Method       System.Management.ManagementBaseObject Chkdsk(System.B...
Reset                        Method       System.Management.ManagementBaseObject Reset()
SetPowerState                Method       System.Management.ManagementBaseObject SetPowerState(S...
Access                       Property     System.UInt16 Access {get;set;}
Availability                 Property     System.UInt16 Availability {get;set;}
BlockSize                    Property     System.UInt64 BlockSize {get;set;}
Caption                      Property     System.String Caption {get;set;}
Compressed                   Property     System.Boolean Compressed {get;set;}
ConfigManagerErrorCode       Property     System.UInt32 ConfigManagerErrorCode {get;set;}
ConfigManagerUserConfig      Property     System.Boolean ConfigManagerUserConfig {get;set;}
CreationClassName            Property     System.String CreationClassName {get;set;}
Description                  Property     System.String Description {get;set;}
DeviceID                     Property     System.String DeviceID {get;set;}
DriveType                    Property     System.UInt32 DriveType {get;set;}
ErrorCleared                 Property     System.Boolean ErrorCleared {get;set;}
ErrorDescription             Property     System.String ErrorDescription {get;set;}
ErrorMethodology             Property     System.String ErrorMethodology {get;set;}
FileSystem                   Property     System.String FileSystem {get;set;}
FreeSpace                    Property     System.UInt64 FreeSpace {get;set;}
InstallDate                  Property     System.String InstallDate {get;set;}
LastErrorCode                Property     System.UInt32 LastErrorCode {get;set;}
MaximumComponentLength       Property     System.UInt32 MaximumComponentLength {get;set;}
MediaType                    Property     System.UInt32 MediaType {get;set;}
Name                         Property     System.String Name {get;set;}
NumberOfBlocks               Property     System.UInt64 NumberOfBlocks {get;set;}
PNPDeviceID                  Property     System.String PNPDeviceID {get;set;}
PowerManagementCapabilities  Property     System.UInt16[] PowerManagementCapabilities {get;set;}
PowerManagementSupported     Property     System.Boolean PowerManagementSupported {get;set;}
ProviderName                 Property     System.String ProviderName {get;set;}
Purpose                      Property     System.String Purpose {get;set;}
QuotasDisabled               Property     System.Boolean QuotasDisabled {get;set;}
QuotasIncomplete             Property     System.Boolean QuotasIncomplete {get;set;}
QuotasRebuilding             Property     System.Boolean QuotasRebuilding {get;set;}
Size                         Property     System.UInt64 Size {get;set;}
Status                       Property     System.String Status {get;set;}
StatusInfo                   Property     System.UInt16 StatusInfo {get;set;}
SupportsDiskQuotas           Property     System.Boolean SupportsDiskQuotas {get;set;}
SupportsFileBasedCompression Property     System.Boolean SupportsFileBasedCompression {get;set;}
SystemCreationClassName      Property     System.String SystemCreationClassName {get;set;}
SystemName                   Property     System.String SystemName {get;set;}
VolumeDirty                  Property     System.Boolean VolumeDirty {get;set;}
VolumeName                   Property     System.String VolumeName {get;set;}
VolumeSerialNumber           Property     System.String VolumeSerialNumber {get;set;}
__CLASS                      Property     System.String __CLASS {get;set;}
__DERIVATION                 Property     System.String[] __DERIVATION {get;set;}
__DYNASTY                    Property     System.String __DYNASTY {get;set;}
__GENUS                      Property     System.Int32 __GENUS {get;set;}
__NAMESPACE                  Property     System.String __NAMESPACE {get;set;}
__PATH                       Property     System.String __PATH {get;set;}
__PROPERTY_COUNT             Property     System.Int32 __PROPERTY_COUNT {get;set;}
__RELPATH                    Property     System.String __RELPATH {get;set;}
__SERVER                     Property     System.String __SERVER {get;set;}
__SUPERCLASS                 Property     System.String __SUPERCLASS {get;set;}
PSStatus                     PropertySet  PSStatus {Status, Availability, DeviceID, StatusInfo}
ConvertFromDateTime          ScriptMethod System.Object ConvertFromDateTime();
ConvertToDateTime            ScriptMethod System.Object ConvertToDateTime();
Delete                       ScriptMethod System.Object Delete();
GetType                      ScriptMethod System.Object GetType();
Put                          ScriptMethod System.Object Put();

Creating New Windows PowerShell Drives

In addition to providing access to system drives, Windows PowerShell provides the ability to create PowerShell Drives (PSDrives) which provide short cuts to directories on physical file systems. For example, it is possible to create a PSDrive which can be used to reference a particular directory on a file system. For the purposes of demonstrating this feature, we will create a temporary directory on the current file system called /tmp/myfiles:

PS C:\Users\Administrator> md /tmp/myfiles


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


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         12/5/2008  12:08 PM            myfiles

Now that the directory exists we can map it to a PSDrive using the name tmpfiles as follows:

PS C:\Users\Administrator> new-psdrive -name tmpfiles -psprovider filesystem -root (resolve-path /tmp/myfiles)

Now that the PSDrive is configured, it is possible to use it much as we would any other filesystem:

PS C:\Users\Administrator> "This is a test" > tmpfiles:/test.txt

PS C:\Users\Administrator> dir tmpfiles:/test.txt


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


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


PS C:\Users\Administrator> get-content tmpfiles:test.txt
This is a test

Getting Information about Network Drives in PowerShell

In addition to obtaining information about disk drives attached to the local system, it is also possible to get information about mapped network drives from within Windows PowerShell. This is achieved by accessing the WMI win32_mappedlogicaldisk object. As with most objects, this one provides a wealth of information so it is often best to select only those attributes that are specifically needed. The following command, for example, displays the device ID, the name of the remote server on which the disk is physically located and the amount of remaining free space on the particular drive:

PS C:\Users\Administrator> get-wmiobject win32_mappedlogicaldisk | select-object deviceid,providername,freespace

deviceid                          providername                                            freespace
--------                          ------------                                            ---------
Z:                                \\Winserver-2\c                                        9408192512 

Windows PowerShell File System Directory Listings

A listing of the files and sub-folders in a directory may be obtained using the Get-ChildItems cmdlet, or the dir alias with no parameters, the current directory is assumed. Alternatively, a path may be provided to the desired directory:

PS C:\Users\Administrator> get-childitem /tmp


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


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         12/5/2008  12:08 PM            myfiles

A recursive listing (which includes the contents of all sub-directories) is generated through the use of the -recurse option:

PS C:\Users\Administrator> get-childitem /tmp -recurse

In addition, the -filter option can be used to limit the listing to files and folders which match specified criteria:

PS C:\Users\Administrator> get-childitem /tmp -filter *.txt

The above example will list only files with a .txt filename extension. Similarly, multiple filtering criteria may be specified through the use of the -include option:

PS C:\Users\Administrator> get-childitem /tmp -include *.txt,*.doc

Copying, Remaining and Deleting Files and Directories

The Copy-Item cmdlet (also available via the cp and copy aliases) allows files to be copied, and takes the source and destinations as parameters. For example, the following command copies the file C:\tmp\myfiles\test.txt to C:\tmp\test2.txt:

PS C:\Users\Administrator> copy-item c:\tmp\myfiles\test.txt c:\tmp\test2.txt

Multiple copies may be made with a single command by using wildcards. For example, to copy the entire contents of one directory into another:

PS C:\Users\Administrator> copy-item c:\tmp\myfiles\*.* c:\tmp

The -recurse option performs a recursive copy whereby all sub-directories and folders are included in the copy operation:

PS C:\Users\Administrator> copy-item -recurse c:\tmp c:\tmp2

Files and directories are renamed and moved using the Rename-Item cmdlet, or the move or mv aliases:

move-item c:\tmp\test2.txt c:\tmp\test3.txt

Finally, files may be deleted using the Remove-Item cmdlet (also accessible as del and rm):

PS C:\Users\Administrator> remove-item c:\tmp\test3.txt

If the item to be removed is a directory containing files and/or subdirectories, the cmdlet will prompt for verification that all contents of the directory are to be recursively removed as follows:


PS C:\Users\Administrator> remove-item c:\tmp3

Confirm
The item at C:\tmp3 has children and the Recurse parameter was not specified. If you continue, all
children will be removed with the item. Are you sure you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

This prompt may be avoided by specifying the -recurse option:

PS C:\Users\Administrator> remove-item -recurse c:\tmp3


<google>BUY_WPS_BOTTOM</google>