I am trying to use Set-Content to create an xml document with a variable being passed. I am able to run the following command from my own desktop (windows 10) without issue. But running it on a server (Windows Server 2016) I get an error.
Set-Location "C:\MID Server\prodAgent\agent"
$MyVariable = '123456'
Set-Content C:\MID Server\prodAgent\agent\config.xml "<?xml version='1.0' encoding='UTF-8'?>
<parameters>
<parameter name='url' value='https://dev.service.com/'/>
<parameter name='mid.instance.username' value='Server'/>
<parameter secure='true' name='mid.instance.password' value='$MyVariable'/>
<parameter name='name' value='Test'/>
<parameter name='mid_sys_id' value=''/>
</parameters>"`
Set-Content : A positional parameter cannot be found that accepts argument '<?xml version='1.0' encoding='UTF-8'?>
<parameters>
<parameter name='url' value='https://dev.service-now.com/'/>
<parameter name='mid.instance.username' value='Server'/>
<parameter secure='true' name='mid.instance.password' value='123456'/>
<parameter name='name' value='Test'/>
<parameter name='mid_sys_id' value=''/>
</parameters>'.
At line:16 char:1
+ Set-Content C:\MID Server\prodAgent\agent\config.xml "<?xml version=' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Content], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetContentCommand
In both cases I am running the command as Admin.
Thanks for your help
On PowerShell 5.1, apart from the final backtick in your code and the unquoted path while this path contains a space character, I cannot reproduce that error.
Since you want to write XML, why not use the xml .Save()
method for this?
$MyVariable = '123456'
[xml]$xml = @"
<?xml version='1.0' encoding='UTF-8'?>
<parameters>
<parameter name='url' value='https://dev.service.com/'/>
<parameter name='mid.instance.username' value='Server'/>
<parameter secure='true' name='mid.instance.password' value='$MyVariable'/>
<parameter name='name' value='Test'/>
<parameter name='mid_sys_id' value=''/>
</parameters>
"@
$xml.Save('C:\MID Server\prodAgent\agent\config.xml')
If you must do this with Set-Content, I'd advise using a Here-String:
$MyVariable = '123456'
Set-Content -Path 'C:\MID Server\prodAgent\agent\config.xml' -Value @"
<?xml version='1.0' encoding='UTF-8'?>
<parameters>
<parameter name='url' value='https://dev.service.com/'/>
<parameter name='mid.instance.username' value='Server'/>
<parameter secure='true' name='mid.instance.password' value='$MyVariable'/>
<parameter name='name' value='Test'/>
<parameter name='mid_sys_id' value=''/>
</parameters>
"@ -Encoding UTF8