Get Item - PowerShell


Overview

Get-Item is a powerful PowerShell command that allows users to retrieve file and folder objects from the local or remote file system. It’s widely used for managing files and folders, including retrieving metadata, copying, moving, and deleting items.

Syntax

Get-Item [[-Path] <String>] [-LiteralPath <String>] [-Exclude <String[]>] [-Force] [-Include <String[]>] [-Recurse] [-File] [-Directory] [-PipelineVariable <String>]

Options/Flags

  • -Path: Specifies the path to the item(s) to retrieve.
  • -LiteralPath: Allows the input path to be interpreted as a literal string, preventing PowerShell from expanding wildcards or environment variables.
  • -Exclude: Filters out items matching the specified string patterns.
  • -Force: Suppresses confirmation prompts when deleting files or directories.
  • -Include: Filters in items matching the specified string patterns.
  • -Recurse: Retrieves items in subdirectories.
  • -File: Retrieves only files.
  • -Directory: Retrieves only directories.
  • -PipelineVariable: Specifies the name of the variable containing the pipeline input instead of using the default $PSItem variable.

Examples

Retrieve a file’s metadata:

Get-Item -Path .\myfile.txt

Copy a file to a new location:

Get-Item -Path .\myfile.txt | Copy-Item -Destination .\newfolder

Delete a directory and its contents:

Get-Item -Path .\mydirectory -Recurse -Force | Remove-Item

Common Issues

Error: Could not find part of the path: Ensure the specified path exists and is accessible.

Error: Access denied: Verify that you have sufficient permissions to access the specified item(s).

Error: The specified path is not a valid Win32 file system path: Pass absolute paths beginning with a drive letter or UNC share.

Integration

Combine with Out-File:

Get-Item -Path .\*.txt | Out-File -FilePath .\textfiles.txt

Use with ForEach-Object:

Get-Item -Path .\*.txt | ForEach-Object { Copy-Item $_ .\backupfolder }
  • Copy-Item: Copies files and directories.
  • Remove-Item: Deletes files and directories.
  • Move-Item: Moves files and directories.