Menu Close

Enabling and Disabling disk in command line

There are scenarios where you want to disable a disk from being visible in a Windows machine – after backup, securing disk from unnecessary access, ransomware not able to encrypt your backup disk, etc. 

Its possible to achieve this via command line so that you can schedule it in Scheduled Tasks.

Diskpart is your friend to achieve this, however diskpart doesn’t take command line parameters. 

To disable a disk:

Create a txt file (I call it disk1offline.txt) with below content.

select disk 1
offline disk
exit

From command line, run “diskpart /s disk1offline.txt“. This will take your disk 1 offline. You can see the disk in Disk Management console, but will not be able to access it using explorer. Now the disk is safe and secure.

This command can be used to schedule it as a task.

Now you want to enable the disk – to access the content, copy files into it, etc.

To enable a disk:

Create a txt file (I call it disk1online.txt) with below content.

select disk 1
online disk
attribute disk clear readonly
exit

From command line, run “diskpart /s disk1online.txt“. This will make your disk 1 online. You can see the disk in Disk Management console and access it using explorer. Now the disk and its content are visible. 

I used this to schedule automated backup via batch file.

  1. Enable disk using the command
  2. Run Robocopy to perform backup
  3. Delete backup older than xx days
  4. Disable disk using the command

Note: Underlined parameters need to be customized for your environment.

diskpart /s c:\disk1online.txtrobocopy sourcefolder destinationfolder /s /e /r:2 /w:2 /NP

forfiles /P destinationfolder /S /M *.* /D -xx /C “cmd /c del @path”diskpart /s c:\disk1offline.txt

This helps in doing the backup, while the disk is not accessible outside the backup window. Prevents accidental deletion, ransomware encryption, benefit of having the disk plugged into the server instead of manually removing it after backup and plugging it back before backup.

Leave a Reply

Your email address will not be published. Required fields are marked *