Managing File Systems - Windows PowerShell for Administration: The Personal Trainer (2015)

Windows PowerShell for Administration: The Personal Trainer (2015)

Chapter 4. Managing File Systems

In this chapter, you’ll learn techniques for managing file systems and security—and there’s a lot more flexibility to this than most people realize. You can create, copy, move, and delete individual directories and files. You can read and write files, and you also can append data to files and clear the contents of files. You can examine and set access control lists on directories and files, and you also can take ownership of directories and files. Moreover, because you are working with Windows PowerShell, it’s just as easy to manipulate multiple directories and files matching specific parameters you specify as it is to work with individual directories and files.

Working with PowerShell Drives, Directories, and Files

You can use PowerShell to manage drives, directories, and files. The core set of features for performing related procedures were discussed previously in Windows PowerShell: The Personal Trainer, and include the FileSystem provider, the cmdlets for working with data stores, and the cmdlets for working with provider drives.

Adding and Removing PowerShell Drives

Using the Get-PSDrive cmdlet, you can view the PowerShell drives that currently are available. As the following example and sample output shows, this includes actual drives and the resources PowerShell lets you work with as if they were drives:

get-psdrive


Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
Alias Alias
C 87.75 149.53 FileSystem C:\
Cert Certificate \
D .04 7.90 FileSystem D:\
E FileSystem E:\

Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan

NOTE To query multiple computers, use the Invoke-Command cmdlet as discussed in Windows PowerShell: The Personal Trainer. Here is an example:

invoke-command -computername Server43, Server27, Server82
-scriptblock { get-psdrive }

You can change the working location to any of these drives using Set-Location. Simply follow the cmdlet name with the desired drive or path relative to a drive, such as

set-location c:

or

set-location c:\logs

When you switch drives using only the drive designator, PowerShell remembers the working path, allowing you to return to the previous working path on a drive simply by referencing the drive designator.

You can use the New-PSDrive cmdlet to create a PowerShell drive that is mapped to a location in a data store, which can include a shared network folder, local directory, or registry key. The drive acts as a shortcut and is available only in the current PowerShell console. For example, if you frequently work with the C:\Data\Current\History\Files directory, you might want to create a new drive to quickly reference this location. When you create a drive, you specify the alias to the drive using the –Name parameter, the provider type using the –PSProvider parameter, and the root path using the –Root parameter, as shown in this example:

new-psdrive –name hfiles –psprovider filesystem –root c:\data\current\history\files

Here, you create a drive called hfiles as a FileSystem type to act as a shortcut to C:\Data\Current\History\Files. You can switch to this drive by typing set-location hfiles:. As long as you have the appropriate permissions to create drives, the creation process should be successful. A common error you might see occurs when a like-named drive already exists.

Because the drive exists only in the current PowerShell session, the drive ceases to exist when you exit the PowerShell console. You also can remove a drive using Remove-PSDrive. Although you can remove drives you added to the console, you cannot delete Windows drives or mapped network drives created by using other methods.

NOTE You can create a drive that maps to registry locations as well. If you do, the PSProvider type to reference is registry. Type get-psprovider to list all available provider types.

Creating and Managing Directories and Files

In PowerShell, you work with directories and files in much the same way. You view directories and files using Get-ChildItem as shown in many previous examples. To create directories and files, you use New-Item. The basic syntax is

new-item –type [Directory | File] –path Path

where you specify the type of item you are creating as either Directory or File and then use Path to specify where the directory or file should be created. When you create a directory or file, New-Item displays results that confirm the creation process. In the following example, you create a C:\Logs\Backup directory, and the resulting output confirms that the directory was successfully created:

new-item -type directory -path c:\logs\backup


Directory: C:\logs
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 7/18/2015 4:54 PM backup

NOTE To create directories and files on remote computers, use the Invoke-Command cmdlet as discussed in Windows PowerShell: The Personal Trainer. Here is an example:

invoke-command -computername Server43, Server27, Server82
-scriptblock { new-item -type directory -path c:\logs\backup }

As long as you have the appropriate permissions to create a directory or file in the specified location, the creation process should be successful. The New-Item cmdlet even creates any required subdirectories for you automatically. In this example, if the C:\Logs directory doesn’t exist, PowerShell creates this directory and then creates the Backup subdirectory. When you create a file, PowerShell creates an empty file with no contents.

Using similar procedures, you can copy, move, rename, and delete directories and files.

Copying Directories and Files

You can copy directories and files using Copy-Item. The basic syntax for directories and their contents is

copy-item SourcePath DestinationPath -recurse

where SourcePath is the path to the directory to copy, and DestinationPath is where you’d like to create a copy of the directory. In the following example, you copy the C:\Logs directory (and all its contents) to C:\Logs_Old:

copy-item c:\logs c:\logs_old -recurse

The command will create the Logs_Old directory if it does not already exist. The basic syntax for copying files is

copy-item PathToSourceFile DestinationPath

where PathToSourceFile is the path to the file or files to copy, and DestinationPath is where you’d like to create a copy of the file or files. In the following example, you copy all the .txt files in the C:\Logs directory to C:\Logs_Old:

copy-item c:\logs\*.txt c:\logs_old

As long as you have the appropriate permissions, you should be able to copy directories and files. You can use Copy-Item to copy resources across volumes as shown in the following example:

copy-item c:\logs d:\logs_old -recurse

Moving Directories and Files

You can move directories and files using Move-Item. The basic syntax is

move-item SourcePath DestinationPath

where SourcePath is the current path to the directory or file, and DestinationPath is the new path for the directory or file. When you move a directory or file, Move-Item displays an error that indicates failure but doesn’t display any output to indicate success. In the following example, you move the C:\Logs directory (and all its contents) to C:\Backup\Logs:

move-item c:\logs c:\backup\logs

The following command moves all the .txt files in the C:\Logs directory to C:\Backup\Logs:

move-item c:\logs\*.txt c:\backup\logs

As long as you have the appropriate permissions, you should be able to move directories and files. However, some caveats apply. Because you cannot use Move-Item to move resources across volumes, the source and destination path must have identical roots. If files in a directory are in use, a file is in use, or a directory is shared, you won’t be able to move the directory or file.

Renaming Directories and Files

To rename directories and files, you use the Rename-Item cmdlet. Rename-Item has the following syntax:

rename-item OriginalNamePath NewName

where OriginalNamePath is the full path to the directory or file, and NewName is the new name for the directory or file. In the following example, you rename Log1.txt in the C:\Logs directory as Log1_hist.txt:

rename-item c:\logs\log1.txt log1_hist.txt

As long as you have the appropriate permissions, you should be able to rename directories and files. However, if files in a directory are in use, a file is in use, or a directory is shared, you won’t be able to rename the directory or file.

Deleting Directories and Files

You can delete directories and files using the Remove-Item cmdlet. Remove-Item has the following syntax:

remove-item NamePath [-force]

where NamePath is the full path to the directory or file that you want to remove, and –Force is an optional parameter to force the removal of a directory or file. In the following example, you delete the D:\Logs_Old directory (and all its ­contents):

remove-item d:\logs_old

As long as you have the appropriate permissions, you should be able to remove directories and files. However, if files in a directory are in use, a file is in use, or a directory is shared, you won’t be able to remove the directory or file. Additionally, if a directory or file is marked Read-Only, Hidden, or System, you’ll have to use the –Force parameter to remove it.

Working with File Contents

Often when you are working with computers, you’ll want to create your own configuration and inventory records or logs to record your activities. PowerShell makes this easy by providing a simple set of commands for reading the contents of files and writing new contents to files.

Commands for Managing File Contents

Commands that help you access file resources include the following:

· Get-Content Displays the contents of files in a specified location. Use –Force to force access to a hidden, system, or read-only file. Use –TotalCount to specify the number of lines in each matching file to display. Use –Include to limit the matches to files meeting specific criteria. Use –Exclude to omit specified files. Both –Include and –Exclude accept wildcard characters.

Get-Content [-LiteralPath | -Path] FilePath {AddtlParams}

AddtlParams=
[–Credential Credential] [-Delimiter String] [-Encoding
Encoding] [-Exclude FilesToExclude] [-Force] [-Include
FilesToInclude] [-TotalCount Count]

REAL WORLD Many PowerShell cmdlets accept –Path and –LiteralPath parameters. Both parameters specify the path to an item. However, unlike –Path, the value of –LiteralPath is used exactly as it is typed. This means no characters are interpreted as wildcards. If a path includes actual escape characters, enclose them in single quotation marks because this tells PowerShell not to interpret any characters as escape sequences.

· Set-Content Overwrites the contents of files in a specified location. Use –Force to force access to a hidden, system, or read-only file. Specify the content to write using the –Value parameter or by pipelining input from another command. Use –Include to limit the matches to files meeting specific criteria. Use –Exclude to omit specified files. Both –Include and –Exclude accept wildcard characters.

Set-Content [-LiteralPath | -Path] FilePath [-Value Content] {AddtlParams}

AddtlParams=
[–Credential Credential] [-Encoding Encoding] [-Exclude
FilesToExclude] [-Force] [-Include FilesToInclude]

· Add-Content Adds contents to files in a specified location. Use –Force to force access to a hidden, system, or read-only file. Specify the content to write using the –Value parameter or by pipelining input from another command.

Add-Content [-LiteralPath | -Path] FilePath [-Value NewContent] {AddtlParams}

AddtlParams=
[–Credential Credential] [-Encoding Encoding] [-Exclude
FilesToExclude] [-Force] [-Include FilesToInclude]

· Clear-Content Clears the contents of files in a specified location. Use –Force to force access to a hidden, system, or read-only file. Use –Include to limit the matches to files meeting specific criteria.

Add-Content [-LiteralPath | -Path] FilePath {AddtlParams}

AddtlParams=
[–Credential Credential] [-Exclude FilesToExclude] [-Force]
[-Include FilesToInclude]

Reading and Writing File Content

By default, Get-Content searches the current directory for a file you specify by name or by partial name using wildcards and then displays its contents as text. This means you can quickly display the contents of any text-based file at the prompt simply by typing Get-Content followed by the name of a file in the current directory. The following example gets the log1.txt file in the current directory:

get-content log1.txt

To display the contents of a file in a specified path, type the full path to the file. The following example gets the log1.txt file in the C:\Logs directory:

get-content c:\logs\log1.txt

If you use wildcards, you can display the contents of any files that match the wildcard criteria. The following example displays the contents of any file in the C:\Logs directory that begins with “log”:

get-content c:\logs\log*

To restrict wildcard matches to specific types of files, use the –Include parameter. To exclude specific files or types of files, use the –Exclude parameter. For example, to match only files with the .txt and .log extension, you can enter

get-content –include *.txt, *.log –path c:\logs\log*

Alternatively, to exclude .xml files and match all other files beginning with “log”, you can enter

get-content –exclude *.xml –path c:\logs\log*

Additionally, if you want to see only the first few lines of matching files, use –TotalCount to specify the number of lines in each matching file to display. The following example displays the first 10 lines of each matching file:

get-content –totalcount 10 –path c:\logs\log*

Other cmdlets for working with the contents of files include Set-Content, Add-Content, and Clear-Content. Set-Content overwrites the contents of one or more files in a specified location with content you specify. Add-Content adds content you specify to the end of one or more files in a specified location. Clear-Content removes the contents of files in a specified location. Because Clear-Content does not delete the files, this results in files with no contents (empty files).