3 команды, которые нужно знать 👈

  • Searches an entire directory for a specific file

  • Uses the file path from Get-ChildItem as a variable for Get-FileHash “-Path”

  • Lists the file’s FullName, Attributes, LastWriteTime, CreationTime, LastAccessTime, $Hash ($Hash = output of Get-FileHash)

What I’ve created so far (that doesn’t work):

$ErrorActionPreference = "SilentlyContinue"; $Path = Get-ChildItem -Recurse -Path C:\ -Force -Filter screenshot_37.png | Select-Object FullName; Get-ChildItem -Recurse -Path C:\ -Force -Filter screenshot_37.png |Select-Object FullName, Attributes, LastWriteTime, CreationTime, LastAccessTime, @{Name='Hash';Expression = { $_ |Get-FileHash $Path -Alogorithm MD5 |ForEach-Object Hash }}

Works As Is:

$ErrorActionPreference = "SilentlyContinue"; Get-ChildItem -Recurse -Path C:\ -Force -Filter screenshot_37.png |Select-Object FullName, Attributes, LastWriteTime, CreationTime, LastAccessTime, @{Name='Hash';Expression = { $_ |Get-FileHash -Alogorithm MD5 |ForEach-Object Hash }}

Attributes : Hidden, Archive

LastWriteTime : 10/24/2023 9:32:34 AM

CreationTime : 10/24/2023 9:32:34 AM

LastAccessTime : 10/26/2023 10:37:31 AM

Hash :

Can someone help me in understanding and creating a working command for what’s desired?

Recently, while working with an automation script in PowerShell, I got a requirement to get the path of a file in PowerShell. There are various methods to get the path of a file in PowerShell.

1. Using Get-ChildItem

The Get-ChildItem cmdlet in PowerShell is a very useful command that can be used to list items in one or more specified locations. If you want to retrieve the full path of all files within a specific directory, you can use Get-ChildItem combined with other cmdlets.

Get-ChildItem -Path "C:\MyFolder\" -Recurse | Select-Object -ExpandProperty FullName

The -Recurse parameter is used to get items in all child directories of the specified path. The Select-Object cmdlet with the -ExpandProperty parameter is then used to extract the full path information.

I executed the code using VS code, and you can see the output in the screenshot below:

Get the Path of a File in PowerShell

2. Using Resolve-Path

You can use the cmdlet if you have a relative path and need to resolve it to a full path. This cmdlet is particularly useful when you’re working with paths that may include wildcards or aliases.

Resolve-Path -Path "Relative\Path\To\Your\File.txt"

This will output the fully resolved path to the file.

3. Get the Path of the Currently Executing Script

Sometimes, you may need to find the path of the script that is currently running. You can achieve this by using the built-in $PSScriptRoot variable, which automatically contains the full path to the directory from which the script is being run.

$ScriptPath = $PSScriptRoot
Write-Host "The script is located in: $ScriptPath"

This is a straightforward way to retrieve the execution path without additional cmdlets.

You can see the screenshot below for the output:

How to Get the Path of a File in PowerShell

4. Using Split-Path

The Split-Path cmdlet is another tool you can use to handle path strings in PowerShell. If you have a full path to a file and you want to extract just the directory part, Split-Path is the cmdlet to use.

$FilePath = "C:\MyFolder\File.txt"
$DirectoryPath = Split-Path -Path $FilePath
Write-Host "The file is located in: $DirectoryPath"

This will display the directory part of the file path, excluding the file name.

You can see the output in the screenshot below:

PowerShell Get the Path of a File

5. Combining Get-ChildItem and Split-Path

For a more complex example, you can combine Get-ChildItem and Split-Path to list all files within a directory and then output their respective directory paths.

Get-ChildItem -Path "C:\Your\Target\Directory" -Recurse | ForEach-Object { $DirectoryPath = Split-Path -Path $_.FullName Write-Host "File: $($_.Name) is in directory: $DirectoryPath"
}

This script lists each file found in the target directory and its subdirectories, along with the full path of the directory in which each file resides.

6. Using Get-Location

If you simply want to know the current directory you’re working in, Get-Location will provide that information. This cmdlet returns the current working directory path.

$CurrentDirectory = Get-Location
Write-Host "The current directory is: $CurrentDirectory"

7. Using Custom Functions

function Get-FilePaths { param( [string]$Directory, [string]$Filter = "*.*" ) Get-ChildItem -Path $Directory -Filter $Filter -Recurse | ForEach-Object { $_.FullName }
}
# Usage
Get-FilePaths -Directory "C:\Your\Target\Directory" -Filter "*.txt"

This custom function Get-FilePaths allows you to specify a directory and a filter for the file types you’re interested in. It then lists the full paths of all files that match the filter.

Conclusion

PowerShell provides multiple ways to retrieve file paths, each suited to different scenarios. Whether you’re looking for a simple way to get the current directory, need to resolve a relative path, or require a list of all files in a directory with their full paths, PowerShell has different methods to achieve this.

In this PowerShell tutorial, I have explained how to get the file path in PowerShell using different methods.

You may also like:


By using the FullName property, we are able to get the full path of each file.

= ""

3 команды, которые нужно знать 👈

Notice that these file names don’t contain the full path.

PowerShell Get-ChildItem get full path

Notice that the full path of each file in the folder is now shown:

3 команды, которые нужно знать 👈

We can then navigate to where this text file is located on our computer to view it:

:/>  Две винды при загрузке

3 команды, которые нужно знать 👈

We can see that the text file contains the full path of each file in the folder.

PowerShell: How to Use Get-ChildItem with Filter
PowerShell: How to Create Array from CSV File
PowerShell: How to Compare Two Files

powershell get-childitem

Do you need to get a listing of all the files and folders in a directory with PowerShell? The Get-ChildItem PowerShell cmdlet, or gci for short (other aliases: Dir, LS), One of the most useful commands in PowerShell, is your go-to command for obtaining the contents of directories. Similar to the dir command in the Windows Command Prompt, you can quickly list the contents of a directory, attributes of files and folders, and much more.

In this comprehensive guide, I will take you through everything you need to know about using PowerShell Get-ChildItem to its full potential. Let’s explore how to use Get-ChildItem to list files and folders, search through directories, and filter results in PowerShell.

Key Takeaways

Some key things to know about Get-ChildItem:

  • It can be used to get items from any PowerShell provider path, including the file system, registry hive, certificate stores, etc. In most cases, it is used for file system paths.
  • By default, it gets only the top-level child items from the specified path. You can use the -Recursive switch to get items from the entire tree.
  • It returns objects representing each child item, including properties like name, PSIsContainer (folder vs. file), LastWriteTime, Length, etc.
  • The objects can be piped to other commands for filtering, sorting, formatting, and more.
  • Key parameters of Get-ChildItem include -Path, -Filter, -Include, -Exclude, -Recurse, -Depth, etc.

In summary, Get-ChildItem is invaluable for inspecting and interacting with child items in various provider paths. Understanding it well unlocks many possibilities.

Introduction to PowerShell Get-ChildItem

Get-ChildItem in PowerShell

PowerShell Get-ChildItem is a command that retrieves a list of child items (files and folders) in a specified location, typically from a file system directory. It can be used to search for files and folders, display their properties, and perform actions on them. Common uses include listing files for processing, checking for the existence of files, and gathering information about items in a directory.

Get-ChildItem cmdlet Syntax and Parameters

Get-ChildItem
[[-Path] <string[]>]
[[-Filter] <string>]
[-Include <string[]>]
[-Exclude <string[]>]
[-Recurse]
[-Depth <uint32>]
[-Force] [-Name]
[-UseTransaction]
[-Attributes <FileAttributes[]>]
[-Directory]
[-File]
[-Hidden]
[-ReadOnly]
[-System]
[<CommonParameters>]

The most commonly used parameters are:

ParameterDescription
PathThe path parameter specifies the path of one or more locations to search. Defaults to current location if not specified.
FilterApplies a specific pattern to filter results.
RecurseInstructs the Windows PowerShell, on whether subfolders should be included in the search.
ReadOnlyIncludes ‘Read Only’ files and folders in the results.
HiddenUse this parameter to get files and folders in the results.
SystemIncludes ‘System’ files and folders in the results.
IncludeThe Include parameter specifies a list of file extensions to include in the results.
ExcludeExcludes specific items from results based on their names or patterns.
NameIf specified, the Name parameter Returns only the names of the items, rather than their full details.
ForceForces the retrieval of items (including hidden and system items) that aren’t usually displayed by default.
DepthLimits how many levels of child directories are retrieved (Number of levels to recurse)

Get-ChildItem Cmdlet Usage

Get-ChildItem "C:\Documents"

This will return a list of all the files and folders in the “C:\Documents” folder, and display information like Mode, LastWriteTime, file size (Length), and name.

Get-ChildItem PowerShell

Using Include and Exclude Parameters

The -Include and -Exclude parameters provide another way to target specific child items. Here is an example of using the parameters together:

Get-ChildItem -Path "C:\Logs\*" -Filter "*.log" -File -Include "*test*" -Exclude "*old*"

This will return a list of all .log files in the “C:\Logs” folder, that have “test” in the name, excluding any files with “old” in their names. Here is another example:

Get-ChildItem C:\Temp\* -Include *.txt,*.csv -Exclude *2020*

This will return text and CSV files, excluding any files with 2020 in the name.

Recursive Retrieval

Get-ChildItem -Path "C:\Documents" -Recurse

This command will retrieve all files and folders from the “C:\Documents” directory and its subdirectories.

Filtering with Get-ChildItem – Including the Use of Wildcards

Filtering with Get-ChildItem allows you to narrow down your search results to only the files or folders you need. The most common way to filter with Get-ChildItem command is by using wildcards. Wildcards are characters that represent one or more characters in a file or folder name. The most commonly used wildcards are:

  • * (asterisk): represents any number of characters.
  • ? (question mark): represents a single character.

Here is an example of using wildcards with Get-ChildItem:

Get-ChildItem -Path "C:\Documents" -Filter *report*

This will return a list of all the files and folders in the “C:\Documents” folder that contain the word “report” in their name. You can also use wild card characters to filter, E.g., Filter by file type:

Get-ChildItem -Path "C:\Temp\*.txt"

Please note that the Filter parameter accepts only a single string. If you want to apply a filter for multiple criteria, use the “Include” or “Exclude” parameters.

Get-ChildItem -Path C:\Temp\* -Include ("*.csv","*.txt")

Filtering Files by Extension

Get-ChildItem provides various options for filtering data. You can use the -Filter parameter to specify the most efficient way to filter items. The -Include parameter can be used to get only specified items from the path, and it can be used with wildcards. The -Exclude parameter can be used to exclude specified items from the path.

Get-ChildItem -Path "C:\Documents" -Filter *.txt

This command will retrieve all txt files with the extension .txt from the “C:\Documents” folder using wildcard characters. You can exclude specific file types using the “Exclude” parameter:

Get-ChildItem -Path C:\Temp\* -Exclude ("*.log","*.txt")
Get-ChildItem in PowerShell

Excluding Specific Items

Get-ChildItem -Path "C:\Documents" -Exclude "*temp*"

This command will return all items in the specified directory, except for those with “temp” in their names.

:/>  Для чего нужен доступ к спец. возможностям? AllTracker - Knowledge Base

Get-ChildItem Examples

Here are several practical examples of how you can use Get-ChildItem in PowerShell:

Counting Files in a Folder with Get-ChildItem

You can use Get-ChildItem to count the number of files in a folder. To do this, use the Measure-Object cmdlet. Here is an example of counting the number of files in the Documents folder:

(Get-ChildItem -Path "C:\Documents" -File).count

This will return the number of files in the Documents folder. You can also use the Measure-Object cmdlet to get the number of files in a folder:

(Get-ChildItem C:\Temp -File -Recurse | Measure-Object).count

The Count property of the output contains the file count.

Pipe the Get-ChildItem cmdlet Output to Other cmdlets

You can send the output from the Get-ChildItem cmdlet to other cmdlets in PowerShell. E.g., let’s get all files that have been modified in the past 7 days:

Get-ChildItem -Path "C:\Temp" | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-7)}

Similarly, you can use Where-Object to filter files based on their size.

Get-ChildItem -Path "C:\Temp" | Where-Object {$_.Length -gt 1MB}

Displaying Full File Paths with Get-ChildItem

By default, Get-ChildItem only displays the file or folder name. If you want to display the full path of the file or folder, you can use the FullName property.

Here is an example of displaying the full path of all the files in the Documents folder:

Get-ChildItem -Path "C:\Documents" -File | Select-Object FullName

This will return a list of all the full file paths in the “C:\Documents” folder.

Retrieving Only Files (Excluding Directories) with Get-ChildItem

You can use Get-ChildItem to retrieve only files, excluding folders. To do this, use the -File parameter. Here is an example of retrieving only files in the Documents folder:

Get-ChildItem -Path C:\Documents -File

This will return a list of all the files in the C:\Documents folder.

Getting Full File Paths or just File Names

By default, Get-ChildItem returns child item names without full paths. To get the full path, select the FullName property:

Get-ChildItem C:\Temp | Select FullName

Similarly, to get the File or folder names, use the -Name parameter:

Get-ChildItem C:\Temp -Name
Get-ChildItem "C:\Temp" | Select-Object -ExpandProperty Name

How to Display Only Folders with Get-ChildItem?

The Directory parameter allows you to retrieve only directories, excluding files and other types of items from the result. This is useful if you want to work only with directories and filter out other types of items.

Here is an example of displaying only folders in the Documents folder:

Get-ChildItem -Path C:\Documents -Directory

This will return a list of all the folders in the Documents folder. Here is my related post on finding Empty directories using PowerShell: How to Check if a Folder is Empty in PowerShell?

Search for files in PowerShell

To search for a file using PowerShell, you can use the Get-ChildItem cmdlet. For example, let’s search for all text files in a given folder and all its sub-folders recursively:

Get-ChildItem -Path "C:\Temp" -Filter "*.txt" -Recurse
powershell search for file

Similarly, to search for a specific file, you can use:

Get-ChildItem -Path "C:\Temp" -Filter "AppLog.txt" -Recurse

Script to Get Files Created in the Past 7 Days

To find files created in the past 7 days using PowerShell, you can use the Get-ChildItem cmdlet along with a date filter. Here is a script to accomplish this:

# Define the path to search in
$searchPath = "C:\Logs"
# Calculate the date 7 days ago
$DateThreshold = (Get-Date).AddDays(-7)
# Search for files created in the past 7 days
$RecentFiles = Get-ChildItem -Path $searchPath -Recurse | Where-Object { $_.CreationTime -ge $DateThreshold }
# Output the found files
if ($RecentFiles) { Write-Output "Files created in the past 7 days:" $RecentFiles | ForEach-Object { $_.FullName }
} else { Write-Output "No files found that were created in the past 7 days."
}

Similarly, to get files modified within a specific date range, use:

Get-ChildItem -Filter {$_.LastWriteTime -gt (Get-Date).AddDays(-7)}

This gets files modified in the last 7 days.

:/>  Как выполнить сброс сетевых настроек в Windows 10

Advanced Options with Get-ChildItem

Get-ChildItem also supports advanced filtering options, such as sorting, grouping, and selecting specific properties.

Sorting Child Items

Get-ChildItem C:\Documents | Sort-Object -Property Name

Say: You want to sort the files and folders based on the last modified time stamp in descending order:

Get-ChildItem -Path C:\Documents | Sort-Object LastWriteTime -Descending

This will return a list of all the files in the “C:\Documents” folder by their LastWriteTime property in descending order.

Let’s find the top-10 largest files in a directory:

Get-ChildItem -Path "C:\Documents" -Recurse | Sort-Object Length -Descending | Select-Object -First 10

Limiting the Depth of Retrieval

Get-ChildItem -Path "C:\Documents" -Recurse -Depth 1

This command will retrieve all files and folders from the “C:\Documents” folder and its immediate subdirectories.

Retrieving Read Only / Hidden / System Files and Folders

Get-ChildItem -Path "C:\Documents" -Hidden

This command will retrieve all hidden files and folders from the “C:\Documents” folder. Similarly, use the “ReadOnly”, and “System” switches to get Read-Only items and system files and folders, respectively. We also have the Attributes parameter with values such as Archive, Encrypted, Compressed, Device, Temporary, etc., to filter based on specified attributes.

By default, Get-ChildItem does not retrieve hidden items. To include hidden items, use the -Force parameter. For example:

Get-ChildItem -Path "C:\Documents" -Force

You can also use the -Attributes parameter to filter files based on their attributes. For example, to list only read-only files, use:

Get-ChildItem -Attributes ReadOnly

Retrieving Data from the Registry

Get-ChildItem -Path HKCU:\Software\Microsoft\Office

Retrieving Data from the Certificate Store

Get-ChildItem -Path Cert:\CurrentUser\My
Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.NotAfter -lt (Get-Date).AddDays(30) }

The above command fetches certificates expiring in the next 30 days, guided by the ExpiringInDays parameter.

Tips and Tricks for Using Get-ChildItem Effectively

The Get-ChildItem cmdlet is an incredibly versatile tool in PowerShell. It allows you to list and filter files and directories, offering a high level of customization and control. Here are some useful tips and tricks to help you use Get-ChildItem effectively:

  1. Use wildcards to narrow down your search results.
  2. Use the -Recurse parameter to search subfolders.
  3. Use the -Filter parameter to apply a filter to your search results.
  4. Use the -File parameter to retrieve only files.
  5. Use the -Directory parameter to retrieve only folders.
  6. Use the -Exclude parameter to exclude certain file types from your search results.
  7. Use the -Include parameter to include only certain file types in your search results.
  8. Use the FullName property to display the full path of files and folders.
  9. Use the Measure-Object cmdlet to count the number of files in a folder.
  10. Use advanced filtering options to sort, group, and select specific properties.

Conclusion

The Get-ChildItem cmdlet retrieves data from various locations, including the file system, registry, and certificate store. It provides many options to search for files and folders, display their properties, and perform actions on them. In this comprehensive guide, we have covered the syntax, parameters, and real-world examples of Get-ChildItem. By using the different parameters and options provided by Get-ChildItem, you can easily filter, exclude, and recurse through items to meet your specific requirements.

What is the Get-ChildItem cmdlet in PowerShell?

The Get-ChildItem cmdlet in PowerShell is used to retrieve the items and child items in specified locations, such as files and folders in a file system drive, registry keys, and certificate store items.

How can I use Get-ChildItem to list all files in a directory?

To list all files in a directory, you can run Get-ChildItem -Path "C:\YourDirectory". This will display all files and folders in the specified directory.

What is the difference between Get-Item and Get-ChildItem in PowerShell?

In PowerShell, you use Get-Item to retrieve information about a specific item, like a file or directory. On the other hand, you use Get-ChildItem to retrieve a list of child items within a specified directory. So, while Get-Item focuses on a single item, Get-ChildItem provides a broader view of multiple items within a directory.

How do I Get hidden Files and system files in PowerShell?

How to get a directory size in PowerShell using Get-ChildItem?

How can I pipe the output of Get-ChildItem to another cmdlet for further processing?

How to get only folders with the Get-ChildItem cmdlet in PowerShell?

To get only folders using the Get-ChildItem cmdlet in PowerShell, you can use the “-Directory” parameter. This parameter filters the results only to include directories or folders. For example, to retrieve a list of folders in the current directory, you can use the command “Get-ChildItem -Directory.”

How can I use Get-ChildItem to list items in the registry?

To list items in the registry, specify the registry drive and path. For example, Get-ChildItem -Path HKCU:\Software.

Are there any limitations to the Get-ChildItem cmdlet?

Get-ChildItem may not display all items if the path is too long or if there are permission issues. Additionally, performance may be impacted when listing a large number of items or when using -Recurse on a directory with many subdirectories.

How do I list files in the current directory using Get-ChildItem?

To list files in the current directory, simply use Get-ChildItem without any parameters. It will display all files and directories in the current location.

How do I export the list of items to a CSV file?

How can I filter files based on their creation date?

How do I list only files in a given path?

You can use the -File switch to list only files: Get-ChildItem -Path "C:\Path" -File