Saturday, November 23, 2024

Toggle Controlled Folder Access in Programmatically in Powershell

function update-controlledfolderaccess { 
  param(
    [Parameter(Mandatory = $false, Position = 0)]
    [ValidateSet("toggle", "enable", "disable")]
    [String]$Action
  )

  $setCFAcmd = "Set-MpPreference -EnableControlledFolderAccess " 
  $setCFAaction = $null 
  $ctlfldracc_enabled = $false 

  if ($Action -eq "toggle") {  
    $Preferences = Get-MpPreference
    $ctlfldracc_enabled = $Preferences.EnableControlledFolderAccess
    if ($ctlfldracc_enabled) { $setCFAaction = "disable" } else { $setCFAaction = "enable" } 
  }
  else {
    $setCFAaction = $Action
  }

  $add2profile_process = Start-Process powershell -Verb RunAs "-Command", ($setCFAcmd += $setCFAaction) -wait -PassThru 
  
  if ($add2profile_process.ExitCode -eq 0) {
    Write-Host (">> Successfully {0}d EnableControlledFolderAccess <<" -f $setCFAaction) -ForegroundColor Green
  }
  else {
    throw ("Couldn't {0} EnableControlledFolderAccess .." -f $setCFAaction)
  }
}