如何用PowerShell通过XPath向AppLocker策略XML添加子节点?
Hey there! Let's get that new exclusion path added to your AppLocker policy properly. The issue with your current code is how you're creating the new FilePathCondition node—you're accidentally nesting nodes by using InnerXml on an already created element. Here's the clean, standard way to do this:
Step-by-Step Solution
Load the XML file and target the Exceptions node
First, let's store your targetExceptionsnode in a variable to make the code cleaner and avoid repeating the XPath query:$xmldata = New-Object XML $xmldata.Load("applocker.xml") # Store the target Exceptions node in a variable $exceptionsNode = $xmldata.SelectSingleNode("/AppLockerPolicy/RuleCollection[@Type='Exe']/FilePathRule[@Name='All files located in the Program Files folder']/Exceptions")Create the new FilePathCondition node correctly
Instead of usingInnerXml(which would wrap anotherFilePathConditioninside your new element), directly set thePathattribute on the element you create:$newCondition = $xmldata.CreateElement("FilePathCondition") $newCondition.SetAttribute("Path", "%PROGRAMFILES%\folder3:*")Append the new node and save the XML
Now add the new condition to theExceptionsnode, and don't forget to save the changes back to the file—this is a common oversight!$exceptionsNode.AppendChild($newCondition) | Out-Null $xmldata.Save("applocker.xml")
Why Your Original Code Didn't Work
When you did $newnode.InnerXml = '<FilePathCondition Path="%PROGRAMFILES%\folder3:*" />', you were creating an invalid nested structure inside your Exceptions node:
<FilePathCondition> <FilePathCondition Path="%PROGRAMFILES%\folder3:*" /> </FilePathCondition>
AppLocker's schema expects direct FilePathCondition children under Exceptions, so this nested format would break the policy.
Full Working Code
Putting it all together, here's the complete, clean script:
# Load the XML file $xmldata = New-Object XML $xmldata.Load("applocker.xml") # Target the specific Exceptions node $exceptionsNode = $xmldata.SelectSingleNode("/AppLockerPolicy/RuleCollection[@Type='Exe']/FilePathRule[@Name='All files located in the Program Files folder']/Exceptions") # Create and configure the new exclusion condition $newCondition = $xmldata.CreateElement("FilePathCondition") $newCondition.SetAttribute("Path", "%PROGRAMFILES%\folder3:*") # Add the condition and save changes $exceptionsNode.AppendChild($newCondition) | Out-Null $xmldata.Save("applocker.xml")
This approach follows XML best practices, keeps your code readable, and ensures your AppLocker policy remains valid.
内容的提问来源于stack exchange,提问作者DanZi DanZi Rulez

