Remove PSDrive - PowerShell


Overview

Remove-PSDrive removes a PowerShell drive from the current PowerShell session. It disconnects the drive from its specified location, freeing up resources and enabling the removal of files or folders associated with the drive.

Syntax

Remove-PSDrive [-Name] <String> [-Recurse] [-Force] [-ErrorAction <Action>] [-Confirm] [-ErrorVariable <Variable>] [-OutVariable <Variable>] [-OutBuffer <Object>]

Options/Flags

  • -Name: Specifies the name of the drive to remove.
  • -Recurse: Removes the drive and any sub-drives it contains.
  • -Force: Suppresses confirmation prompts and performs the removal without confirmation.
  • -ErrorAction: Specifies the action to take when an error occurs.
  • -Confirm: Prompts for confirmation before removing the drive.
  • -ErrorVariable: Stores the error message in a specified variable.
  • -OutVariable: Stores the drive object in a specified variable.
  • -OutBuffer: Stores the drive objects in an output buffer.

Examples

Simple Drive Removal:

Remove-PSDrive -Name MyDrive

Recursive Drive Removal:

Remove-PSDrive -Name MyDrive -Recurse

Forced Drive Removal Without Prompts:

Remove-PSDrive -Name MyDrive -Force

Common Issues

  • Drive Not Found: Ensure that the specified drive name exists before attempting to remove it.
  • Access Denied: Verify that you have sufficient permissions to remove the drive.
  • Locked Files: If the drive contains locked files, close or terminate the applications using them.

Integration

Combine Remove-PSDrive with New-PSDrive to create and remove drive mappings dynamically. For example:

$drive = New-PSDrive -Name MyDrive -Root 'C:\Temp'
...
Remove-PSDrive -Name MyDrive
  • Get-PSDrive: Retrieves information about existing drives.
  • New-PSDrive: Creates a new drive mapping.
  • Set-PSDrive: Modifies properties of a drive.
  • PSDrive: Class representing PowerShell drives.