Click here to Skip to main content
15,882,464 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,
I am trying to add Folder Exclusion for Windows Defender using PowerShell through C#
This only works if the path is short, for example:
"C:\New folder"
If the path is a bit longer it doesn't work, for example:
"C:\New folder\New folder1"
What's the problem? Can someone help me please. Thank you.
Below is my code which works fine only if the folder path is short.

What I have tried:

C#
private void addFolderToExclusion()
         {
             try
             {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)              
                string path = openFileDialog1.FileName;
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = "powershell.exe";
                startInfo.Arguments = "-command \"Add-MpPreference -ExclusionPath " + path + "\"";
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();
             }
             catch
             {    
             }
         }
Posted
Updated 1-Jan-23 14:08pm
v2
Comments
PIEBALDconsult 10-Sep-22 12:00pm    
Same as here -- https://www.codeproject.com/Questions/5341739/Set-the-folder-path-in-the-registry-a-problem-Csha -- I expect.
Dave Kreskowiak 10-Sep-22 12:34pm    
If fails because you're path has spaces in it and you're not enclosing that path in quotes, "C:\New Folder\New Subfolder",

How many times do you have to be told: you need Admin rights to edit the LOCAL_MACHINE branch of the registry?

I told you that only three hours ago: Set the folder path in the registry - a problem ? C#[^] - and the situation hasn't changed in that time.

It doens't matter what app you try to use, you need UAC and admin permissions to do it.
 
Share this answer
 
You have to use 'path' if the folder has a space in its name.
Try this:

startInfo.Arguments = "-command \"Add-MpPreference -ExclusionPath '" + path + "'\"";

Added ' before and after the path
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900