1

Can someone help me with this powershell script? I can't get it to work.

$drives = Get-WmiObject -class win32_logicaldisk |
    Where-Object { $_.DriveType -eq 3 }

$drives | ForEach-Object { Enable-ComputerRestore $_.Name }

Moreover the following works like expected!

$drives = Get-WmiObject -class win32_logicaldisk |
    Where-Object { $_.DriveType -eq 3 }

$drives | ForEach-Object { Write-Host $_.Name }

Thanks in advance.

2 Answers2

1

Enable-ComputerRestore seems to have two unusual requirements:

  • The (positionally implied) -Drive argument(s) must end in \ (backslash), e.g, C:\

  • In order to target a drive other than the system drive, the system drive must also be specified, alongside the non-system drive or System Restore must already be turned on for the system drive.

Since your code enumerates all local disks (.DriveType -eq 3), the system drive is by definition among them, so the simplest solution is to pass all local drives at once to Enable-ComputerRestore, as an array:

$driveSpecs = 
  Get-CimInstance -Class Win32_LogicalDisk |
    Where-Object { $_.DriveType -eq 3 } | 
      ForEach-Object { $_.Name + '\' }

Enable-ComputerRestore $driveSpecs

As an aside:

  • I've replaced Get-WmiObject with Get-CimInstance, because the CIM cmdlets superseded the WMI cmdlets in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell Core (version 6 and above), where all future effort will go, doesn't even have them anymore. For more information, see this answer.

  • A more concise and more efficient way to filter the Get-CimInstance output is to use a -Filter argument in lieu of a separate Where-Object call:
    Get-CimInstance -Class Win32_LogicalDisk -Filter 'DriveType = 3'

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Ms docs on this cmdlet is a bit poorly written, it's also weird it doesn't accept any pipeline input. – Santiago Squarzon Jun 29 '21 at 01:08
  • 1
    Agreed, @SantiagoSquarzon, though it _is_ possible to pass an _array_ of arguments to `-Drive`. – mklement0 Jun 29 '21 at 01:22
  • @SimoneChifari, I see: I missed another requirement - please see my update, which is a simpler and more efficient alternative to your approach. In the future, please include error message as part of your question (and please translate them to English, if necessary). – mklement0 Jun 29 '21 at 11:31
0

Found the solution by my self. Posting for others.

$OSDriveLetter = (Get-ComputerInfo | Select-Object -Property "OsSystemDrive").OsSystemDrive

Get-CimInstance -class win32_logicaldisk |
  Where-Object { $_.DriveType -eq 3 } |
    ForEach-Object { Enable-ComputerRestore "$($_.Name + '\')", "$($OSDriveLetter + '\')" }