Add xml object to xml file in PowerShell - powershell

I am trying to create an RDCMan file (.rdg xml file) using PowerShell. I have started by defining this template
$newFileTemplate = '<?xml version="1.0" encoding="utf-8"?>
<RDCMan programVersion="2.7" schemaVersion="3">
<file>
<properties>
<expanded>False</expanded>
<name>Office Servers</name>
</properties>
<displaySettings inherit="None">
<liveThumbnailUpdates>True</liveThumbnailUpdates>
<allowThumbnailSessionInteraction>False</allowThumbnailSessionInteraction>
<showDisconnectedThumbnails>True</showDisconnectedThumbnails>
<thumbnailScale>1</thumbnailScale>
<smartSizeDockedWindows>True</smartSizeDockedWindows>
<smartSizeUndockedWindows>False</smartSizeUndockedWindows>
</displaySettings>
</file>
</RDCMan>
'
before creating an xml object like so
$File = 'D:\Test.rdg'
Set-Content $File $newFileTemplate
[XML]$XMLFile = [XML](Get-Content $File)
I would then like to define a function for adding a group of servers
# This function adds a new group element
Function Add-NewGroup($GroupName,$RDCManFile) {
[xml]$GroupXML = #"
<group>
<properties>
<expanded>False</expanded>
<name>$GroupName</name>
</properties>
</group>
"#
$Child = $RDCManFile.ImportNode($GroupXML.group, $true)
$RDCManFile.Configuration.AppendChild($Child)
}
And call it by running
Add-NewGroup('DCs',$XMLFile)
This would allow me to populate the xml file with all of the OUs in AD.
Is anyone able to tell me where I am going wrong?
Thanks
Update: The error I am getting is
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:179 char:5
+ $Child = $RDCManFile.ImportNode($GroupXML.group, $true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:180 char:5
+ $RDCManFile.Configuration.AppendChild($Child)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
And I am trying to do what was suggested here https://stackoverflow.com/a/29693625/2165019

The property 'Configuration' cannot be found on this object. Verify that the property exists. error at $RDCManFile.Configuration.AppendChild($Child).
If I can accept a .rdg file format and structure as defined in the Script to create a Remote Desktop Connection Manager group from Active Directory Technet article then I'd use
$RDCManFile.RDCMan.file.AppendChild($Child)
Follow the Theo's answer about calling a function.
Pass parameters as positional
Add-NewGroup 'DCs' $XMLFile
or as named
Add-NewGroup -GroupName 'DCs' -RDCManFile $XMLFile

This error (and second) most likely means that $RDCManFile is null.
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:179 char:5
+ $Child = $RDCManFile.ImportNode($GroupXML.group, $true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Try adding $RDCManFile | Out-Host at the top of the Add-NewGroup function to check what's contained in that variable.

You need to change the way you are calling the function.
Because of the comma in between the parameters, PowerShell sees this as one array value, so only parameter $GroupName will receive something.
Furthermore, you should not use brackets around the params, call the function like this:
Add-NewGroup 'DCs' $XMLFile
or send the parameters using their names:
Add-NewGroup -GroupName 'DCs' -RDCManFile $XMLFile

Related

Concatenate network path + variable (name of the folder)

How can I concatenate this network path with this variable entered by the user (it will be a full network path)?
So the user type the new folder name, for example: Folder-123 (will be stored in the variable $pjname)
Copy-Item "\\SERVER\Work_3rd\R Drive Structure\Project No\MDCXXXX" -Destination "\\SERVER\Work_3rd" -Recurse
write-host "Folder has been created. Press any key to continue..."
[void][System.Console]::ReadKey($true)
Write-Host "Please enter the project name: "
$pjname = Read-Host
Write-Output "New Folder will be: $pjname"
Rename-Item -Path "\\SERVER\Work_3rd\MDCXXXX" -NewName $pjname
write-host "Folder has been renamed. Press any key to continue..."
[void][System.Console]::ReadKey($true)
$pathToTemplate = '\\SERVER\Work_3rd\R Drive Structure\Project No\MDCXXXX'
$rootPath2 = '\\SERVER\Work_3rd\'
$rootPath = -join ($rootPath2, $pjname) # this concatenates the new project
name on to the root folder path**
# $rootPath += $pjname # this concatenates the new project name on to the
root folder path
If(Test-Path $rootPath)
{
$CurrentACL = (Get-Item $pathToTemplate).GetAccessControl('Access')
$CurrentACL | Set-Acl -Path $rootPath
}
This new folder stored in $pjname should have a network path like \\\SERVER\Work-3rd\ + FOLDER NAME. For example \\\SERVER\Word-3rd\Folder-123
The PowerShell is not finding the final path of the new folder so the permission is not being applied on it.
I'm trying in a test area and getting this problem below:
Folder has been renamed. Press any key to continue...
Get-Acl : Cannot find path '\\SERVER\test-area\Test-123' because it does not exist.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV3.ps1:279 char:8
+ $acl = Get-Acl $NewNetworkPath
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId :
GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand
You cannot call a method on a null-valued expression.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV3.ps1:282 char:1
+ $acl.SetAccessRule($rule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Are you trying to create a new directory in that share path, or rename a directory? It looks like you're trying to rename a directory.
My guess it isn't working because you are missing the trailing "\" in your path. Here is some sample code that adds a user supplied variable to a network path:
$MyRootPath = "\\SomeServer\Dir1\Dir2\"
Write-Host "Enter Dir Name"
$myAnswer = Read-Host
I typed "hello" when prompted for new directory..
$finalAnswer = $myAnswer.Trim()
$NewNetworkPath = ("{0}{1}" -f $MyRootPath, $finalAnswer)
$NewNetworkPath
returns:
\\SomeServer\Dir1\Dir2\hello
Whenever you are concatenating paths, escpecially those supplied by end users, stick to a utility that can do most of the heavy lifting. Use the combine method as string concatenation has several pitfalls that have to be needlessly mitigated.
[io.path]::combine('\\server\share', 'newfolder')
The combine method will take the path parts, as an array, and build a proper path. Note this does not validate if the path exists. It can deal with trailing path separators well. These next commands yield the same result.
[io.path]::combine('\\server\share\', 'newfolder')
[io.path]::combine('\\server\share', 'newfolder')
Beware leading path separators though:
If the one of the subsequent paths is an absolute path, then the combine operation resets starting with that absolute path, discarding all previous combined paths.
Thanks Matt & oze4! A weird problem happened now. I used the solution of oze4 and sometimes it works and sometimes not. Would it be the string entered by the user?
When it worked the folder name was 'MDX1111 - XXXX Xxxxxxx Xxxxxxxxx' - 32 characters. I ran the code again using the folder name 'MDX1112 - Xxxxxx Xxxxxxx Xxxxxxxxxx' - 35 characters and got this error below:
Get-Acl : Cannot find path '\\SERVER\Work_Block_A\MDX1112 - Xxxxxx Xxxxxxx
Xxxxxxxxxx' because it does not
exist.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV1.ps1:125 char:8
+ $acl = Get-Acl $NewNetworkPath
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId :
GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand
You cannot call a method on a null-valued expression.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV1.ps1:128 char:1
+ $acl.SetAccessRule($rule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Any thoughts?
Thank you.

How to pass a custom enum to a function in powershell

When defining a function, how can you reference a custom enum?
Here's what I'm trying:
Add-Type -TypeDefinition #"
namespace JB
{
public enum InternetZones
{
Computer
,LocalIntranet
,TrustedSites
,Internet
,RestrictedSites
}
}
"# -Language CSharpVersion3
function Get-InternetZoneLogonMode
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[JB.InterfaceZones]$zone
)
[string]$regpath = ("HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\{0}" -f [int]$zone)
$regpath
#...
#Get-PropertyValue
}
Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
But this gives the error:
Get-ZoneLogonMode : Unable to find type [JB.InterfaceZones]. Make sure that the assembly that contains this type is loaded.
At line:29 char:1
+ Get-ZoneLogonMode -zone [JB.InternetZones]::TrustedSites
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (JB.InterfaceZones:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
NB: I'm aware I could use ValidateSet for similar functionality; however that has the disadvantage of only having a name value; as opposed to allowing me to program using friendly names which are then mapped to ints in the background (I could write code for that; but enum seems more appropriate if possible).
I'm using Powershell v4, but ideally I'd like a PowerShell v2 compatible solution as most users are on that version by default.
Update
I've corrected the typo (thanks PetSerAl; well spotted).
[JB.InterfaceZones]$zone now changed to [JB.InternetZones]$zone.
Now I'm seeing error:
Get-InternetZoneLogonMode : Cannot process argument transformation on parameter 'zone'. Cannot convert value "[JB.InternetZones]::TrustedSites" to type
"JB.InternetZones". Error: "Unable to match the identifier name [JB.InternetZones]::TrustedSites to a valid enumerator name. Specify one of the following
enumerator names and try again: Computer, LocalIntranet, TrustedSites, Internet, RestrictedSites"
At line:80 char:33
+ Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-InternetZoneLogonMode], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-InternetZoneLogonMode
The ISE gave this one away to me but your attempted syntax was not completely incorrect. I was able to do this and get it to work.
Get-InternetZoneLogonMode -Zone ([JB.InternetZones]::TrustedSites)
Again, If you look at the highlighting you will see how I came to that conclusion.
Per comments by PetSerAl & CB:
Corrected typo in function definition
from [JB.InterfaceZones]$zone
to [JB.InternetZones]$zone
Changed function call
from Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
to Get-InternetZoneLogonMode -zone TrustedSites

Accessing PrivateData during Import-Module

I want to load the contents of a config.xml file and store it in $PrivateData when my module loads. Here is the definition line in my PSD1
# Private data to pass to the module specified in ModuleToProcess
PrivateData = #{'Variables'=#{};'Config'=$null}
This creates a hashtable with two items. 1) Variables is a second hashtable I use to store private variables for my module. 2) Config which will contain the values of a config.xml file. Example XML:
<Config>
<Foo>Bar</Foo>
</Config>
I can load the xml with the following line:
$PrivateData = $MyInvocation.MyCommand.Module.PrivateData
$PrivateData.Config = ([xml](Get-Content $PSScriptRoot\Config.xml | Out-String)).Config
It does not appear that I can access it in my PSM1 file. I CAN wrap it in a Cmdlet like so:
Function Initialize-TestModule {
$PrivateData = $MyInvocation.MyCommand.Module.PrivateData
$PrivateData.Config #= ([xml](Get-Content $PSScriptRoot\Config.xml | Out-String)).Config
}
But then the user would have to make a call to Import-Module and then a second call to Initialize-TestModule which is what I am trying to avoid.
If I put the code in the PSM1 it generates this error when I call Import-Module
Property 'Config' cannot be found on this object; make sure it exists and is settable.
At C:\scripts\temp\TestModule\TestModule.psm1:7 char:2
+ $PrivateData.Config = ([xml](Get-Content $PSScriptRoot\Config.xml | Out-String) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
If I try to load in the PSD1 like this:
PrivateData = #{'Variables'=#{};'Config'=([xml](Get-Content $PSScriptRoot\Config.xml | Out-String)).Config}
I get these errors:
Import-Module : The module manifest 'C:\scripts\temp\TestModule\TestModule.psd1' could not be processed because it is
not a valid Windows PowerShell restricted language file. Please remove the elements that are not permitted by the
restricted language:
At C:\scripts\temp\TestModule\TestModule.psd1:88 char:26
+ PrivateData = #{'Config'=([xml](Get-Content $PSScriptRoot\Config.xml | Out-Strin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Property references are not allowed in restricted language mode or a Data section.
At C:\scripts\temp\TestModule\TestModule.psd1:88 char:27
+ PrivateData = #{'Config'=([xml](Get-Content $PSScriptRoot\Config.xml | Out-Strin ...
+ ~~~~~
The type xml is not allowed in restricted language mode or a Data section.
At C:\scripts\temp\TestModule\TestModule.psd1:88 char:33
+ PrivateData = #{'Config'=([xml](Get-Content $PSScriptRoot\Config.xml | Out-Strin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The command 'Get-Content' is not allowed in restricted language mode or a Data section.
At C:\scripts\temp\TestModule\TestModule.psd1:88 char:72
+ PrivateData = #{'Config'=([xml](Get-Content $PSScriptRoot\Config.xml | Out-Strin ...
+ ~~~~~~~~~
The command 'Out-String' is not allowed in restricted language mode or a Data section.
At line:1 char:1
+ Import-Module .\TestModule -force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (C:\scripts\temp...TestModule.psd1:String) [Import-Module], Missing
MemberException
+ FullyQualifiedErrorId : Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand
In my PSM1 have tried making a call to Initialize-TestModule using Invoke-Command and Start-Job both of which failed. So has anyone managed to access $PrivateData during Import-Module?
You will likely need to access the private data using the $MyInvocation variable. However, I've only gotten it to work by calling it from within a function. To load it to a variable in the PSM1 file I call the function from there. I found out about this from https://social.technet.microsoft.com/Forums/windowsserver/en-US/9620af9a-0323-460c-b3e8-68a73715f99d/module-scoped-variable?forum=winserverpowershell.
function Get-PD
{
[CmdletBinding()]
Param()
Begin{}
Process
{
$MyInvocation.MyCommand.Module.PrivateData
}
End{}
}
$MyPD = Get-PD

Method Invocation failed system.string error

Morning,
I'm trying to use a CSV file with a list of users and automate the process to set an AD users extensionAttribute15 back to the "notset" value.
I use a similar code to populate the attribute, the CSV file consists of just two things, the users LAN ID and the value for the attribute.
Populating the field is not the problem, changing the values back to "not set" has been.
Here is the code I am using.
Import-module ActiveDirectory
Import-CSV "code.csv" | % {
$User = $_.cn
$user.Put(“extensionAttribute15”, #())
$user.SetInfo()
}
and here are the errors.
Method invocation failed because [System.String] doesn't contain a method named 'Put'.
At attribute.ps1:4 char:10
+ $user.Put <<<< (“extensionAttribute15”, #())
+ CategoryInfo : InvalidOperation: (Put:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [System.String] doesn't contain a method named 'SetInfo'.
At attribute.ps1:5 char:14
+ $user.SetInfo <<<< ()
+ CategoryInfo : InvalidOperation: (SetInfo:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any ideas what the problem could be?
Thanks,
When you read in a CSV file, the resulting objects are just simple property bags. They don't support any special methods, they just hold flat data. There is nothing in these objects that isn't present in the text of the CSV file itself.
If you want to obtain a rich object which has Active Directory context and capabilities, you will need to obtain one from a cmdlet in the ActiveDirectory module.
Something like this is probably along the lines you need
Import-module ActiveDirectory
Import-CSV "code.csv" | % {
$user = Get-ADUser $_.cn # get a rich object from the AD module, by passing a string
$user.Put(“extensionAttribute15”, #())
$user.SetInfo()
}

Calling [ADSI] with external parameter

I am not very familiar with powershell scripting and I'm stuck on this problem -
I need to make some operations on object retrieved like this:
$object = [ADSI]'LDAP://CN=Test User,OU=Dept,OU=Users,DC=example,DC=org'
...
$object.Commit()
this works fine, but I have to use distinguished name stored in variable - my test script looks like this, but its not working:
$object = [ADSI]'LDAP://$variable'
...
$object.Commit()
the first call to [ADSI] itself doesn't cause error, but any following operation crashes with message:
The following exception occurred while retrieving member "commit": "The server is not operational.
"
At line:1 char:10
+ $object.commit <<<< ()
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember
I'm pretty sure, that the parameter is sent in some wrong way, but I don't know, how to fix it, can anybody help?
tahnks
Try:
$object = [ADSI]"LDAP://$variable"
Single quotes don't expand variables.