Search code examples
powershellfiledirectoryhidden

Toggle "show hidden files and folders with Powershell


I have been trying to create a line item within a .bat or .ps script that toggles the "Show hidden files/folders" option ON. I am having no luck so far. I have tried using the get-childitem command in various flavors and it's not working for me. What am I missing? Is this even something that can be done?


Solution

  • Working from Ash's fine script,here's a slight enhancement. This allows a third option of no parameter which will just toggles the current setting.

    function Show-HiddenFiles {
     
       Param (
              [Parameter(Mandatory = $False,Position=0)]
                [String] $Setting
       )
    
       # Define the path to the registry key that contains the 
       # registry value/subkey
       $Path = "HKCU:\Software\Microsoft\Windows\CurrentVersion" +
               "\Explorer\Advanced"
    
       #No argument toggle setting..
       If ($Args.Count -eq 0) {
    
         $GIPArgs = @{Path = $Path
                      Name = "Hidden"}
    
         If ((Get-ItemProperty @GIPArgs ).Hidden -eq 1) {
           $Value = 2
         }
         Else {$Value = 1}   
       }
       Else {
       # Set a variable with the value we want to set on the 
       # registry value/subkey.
         If ($Setting -eq "On" ) { $Value = 1 }
         Else                    { $Value = 2 }
       }
       
       # Set the registry value/subkey.
       Set-ItemProperty -Path $Path -Name Hidden -Value $Value
    
       # Refresh open Explorer windows.
       # You will need to refresh the window if you have none 
       # currently open.
       # Create the Shell.Application ComObject
       $Shell = New-Object -ComObject Shell.Application
       # For each one of the open windows, refresh it.
        $Shell.Windows() | ForEach-Object { $_.Refresh() }
    }