Invoke Item - PowerShell


Overview

Invoke-Item is a versatile PowerShell command that enables the execution of various actions on specified items. It offers a convenient way to interact with files, folders, scripts, and other objects directly within the PowerShell console.

Syntax

Invoke-Item [-Path] <string[]> [-Credential <PSCredential>] [-AsJob]
[-PipelineVariable <string>] [-LiteralPath] [-Command <string>] [-ArgumentList <object[]>]
[-RedirectStandardInput <string>] [-RedirectStandardOutput <string>] [-RedirectStandardError <string>]

Options/Flags

  • -Path: Specifies the path of the item to invoke. Supports wildcards and multiple paths.

  • -Credential: Provides credentials to access the item if necessary. Defaults to the current user’s credentials.

  • -AsJob: Creates the invocation as a background job, allowing the command to run asynchronously.

  • -PipelineVariable: Sets the variable name for items passed through the pipeline. Defaults to “Item”.

  • -LiteralPath: Treats the value of -Path as a literal path instead of interpreting path variables.

  • -Command: Specifies a custom command to execute on the item. Overrides the item’s default action.

  • -ArgumentList: Passes additional arguments to the command specified by -Command.

  • -RedirectStandardInput: Redirects the input stream of the invoked item.

  • -RedirectStandardOutput: Redirects the output stream of the invoked item.

  • -RedirectStandardError: Redirects the error stream of the invoked item.

Examples

Open a file:

Invoke-Item c:\path\to\file.txt

Run a PowerShell script:

Invoke-Item -Path .\script.ps1

Execute a command on a file:

Invoke-Item -Path c:\path\to\file.txt -Command "notepad"

Invoke an item with custom arguments:

Invoke-Item -Path .\script.ps1 -ArgumentList "-param1", "value1"

Run an item as a background job:

Invoke-Item -Path c:\path\to\file.txt -AsJob

Common Issues

  • Access Denied: Ensure the specified user has sufficient permissions to access the item.
  • Invalid Path: Verify that the path to the item is correct.
  • Unsupported Item: Not all items can be opened or executed within PowerShell.

Integration

Pipe Output to Other Commands:

Get-ChildItem | Invoke-Item -AsJob | Wait-Job

Use with Custom Scripts:

$script = { Get-ChildItem -Recurse | Invoke-Item }
Invoke-Command -ScriptBlock $script
  • Get-Item: Retrieves information about an item without executing it.
  • Set-Item: Sets properties or values of an item.
  • New-Item: Creates a new item in the specified location.