Latest posts by Wolfgang Sommergut (see all)
- Create, sort and filter CSV files in PowerShell - Tue, Sep 5 2017
- PSEdit - Edit files remotely with PowerShell - Fri, Sep 1 2017
- No future for Windows PowerShell—change to PowerShell Core - Tue, Aug 29 2017
In principle, you can determine the required file names with Get-ChildItem to isolate the parts you need from the results. For file names, it is relatively simple because you can use the parameter name:
Get-ChildItem *.doc –name
The result is a string or an array of strings, respectively, whereas Get-ChildItem usually returns a FileInfo object. Those objects contain a few useful properties—among them the entire name including the path (FullName), the path alone (DirectoryName), and the file name (Name) without extension (BaseName):
Get-ChildItem *.doc |select Name, DirectoryName, BaseName, FullName
Split-Path offers more options ^
If you face the task of reading a list of file names to parse them, Get-ChildItem is not going to help. Split-Path closes this gap. It can determine the names and paths of file system, AD, or registry objects and you can use it to parse strings if they follow the syntax of file names.
For splitting file names, the following parameters are available:
- Qualifier (drive, the part before the colon, respectively)
- NoQualifier (absolute path without drive)
- Leaf (file name)
- Parent (parent directory as a relative or absolute path)
Split-Path also accepts wildcards. However, by default, PowerShell does not resolve them. Instead, they appear literally in the result—for instance, in the leaf. You can turn off this behavior with the help of the parameter Resolve.
Split-Path -Path .\texts -Resolve -NoQualifier
# Returns the absolute path without drive together with the name and the directory of texts.
Split-Path -Path .\texts -Resolve -Qualifier
# Determines the drive from the path of the texts directory.
Split-Path -Path .\texts -Qualifier
# Produces an error because a relative path without -Resolve can’t be resolved and it therefore doesn’t have a drive letter.
Split-Path -Path .\texts -Resolve –IsAbsolute
# True because -Resolve returns an absolute path.
Split-Path -Path .\texts\*.docx -Resolve -leaf
# Displays only the file names of all Word documents.
Split-Path -Path .\texts\*.docx -leaf
# Only returns "*.docx" without -Resolve.
Split-Path -Path .\texts\*.docx
#If you don’t specify a name component, -parent is preset. Thus, the result is .\texts.
Get-Content -Path .\file.lst | Split-Path –Leaf
# Reads the contents from file.lst and extracts the file name from each line.
Split-Path isn’t just restricted to the file system; it can also be applied to the registry and the AD (read Mount Active Directory as a drive in PowerShell).
For instance, if you are in AD:\DC=contoso,DC=com and you enter the following command, you will receive all OUs that are directly located below the domain as distinguished names:
split-path "ou=*" -Resolve –leaf