I'm trying to script the removal of a XML node using PowerShell from a .xml file on a remote computer.
My Invoke-Command
scriptblock is:
$remoteResult = Invoke-Command -ComputerName myserver.com -ScriptBlock {
Param($FolderName)
$xmlFilePath = "c:\foo\Folders.xml"
$localLog="c:\foo\removefolder.txt"
[XML]$XMLContent = Get-Content $xmlFilePath -Encoding UTF8
Write-Output $FolderName | Out-File $localLog -Append
Write-Output "Entering loop" | Out-File $localLog -Append
foreach ($Folder in $XMLContent.Folders) {
$XMLFolderName = $Folder.SelectSingleNode("//Name[.='$FolderName']")
Write-Output "Folder = $folder" | Out-String | Out-File $localLog -Append
Write-Output "XMLUserName = $XMLFolderName" | Out-File $localLog -Append
if ($XMLFolderName.'#text' -eq $FolderName) {
$XMLUserName.'#text' | Out-File $localLog -Append
Write-Output "User entry found for $FolderName, removing." | Out-File $localLog -Append
$XMLFolderName.ParentNode.ParentNode.RemoveChild($XMLFolderName.ParentNode)
}
Write-Output "Folder entry not found?" | Out-File $localLog -Append
}
Write-Output "End loop" | Out-File $localLog -Append
$XMLContent.Save($xmlFilePath)
} -ArgumentList $remfolder *>&1
I've added a load of Out-File
statements to generate a log on the remote machine to see what the state of things are during the script execution. I can see the $FolderName
is being passed correctly, then I get:
Entering loop Folder = System.Xml.XmlElement XMLUserName = User entry not found? End loop
If I get it to Out-File
the Get-Content
line it successfully reads the file and saves it to the log, so the .xml file is being read successfully.
If I copy the above code to the remote server and run it directly from there without the Invoke-Command
statement, and manually pass the value of $FolderName
, it works fine and removes the XML node as expected.
So I'm not sure what is happening differently when it's run remotely.
Edit: As requested, here's an example of the XML format being accessed.
<?xml version="1.0"?>
<Folders>
<Folder>
<Name>Folder1</Name>
<Location>\\server.com\share$\folder\Folder1</Location>
<Limitations />
<Description>Folder One</Description>
<CustomField />
<UserPermissions />
<GroupPermissions>
<Permission>
<IdentityName>Folder One</IdentityName>
<ListRestriction>
<Type>Deny</Type>
<Extensions />
</ListRestriction>
</Permission>
</GroupPermissions>
</Folder>
<Folder>
<Name>Folder2</Name>
<Location>\\server.com\share$\folder\Folder2</Location>
<Limitations />
<Description>Folder Two</Description>
<CustomField />
<UserPermissions>
<Permission>
<IdentityName>Folder Two</IdentityName>
<ListRestriction>
<Type>Deny</Type>
<Extensions />
</ListRestriction>
</Permission>
</UserPermissions>
<GroupPermissions />
</Folder>
So for instance in the script I'm assigning $FolderName as "Folder2". When run locally it successfully removed that entire Folder node, remotely it doesn't.