Question

I'm trying to insert a line into a file with a format similar to HTML

This is what I'm running as is

$ID = read-host "ENTER NEW ID"
$infile = C:\testfile
$outfile = C:\testfileout
Get-Content $infile |`
  foreach-object {$_ -replace "<string>ABCD</string>", "<string>ABCD</string> <string>$ID</string>"} |`
  set-content $outfile

The problem I'm having is that the file will work, but only the first time I do it. I'd rather a more eloquent solution where it looks for the parent header for <string> (which is <array>) but I haven't been able to find a good one. There are also multiple <array> nodes under the <master> node.

EDIT: Here is a sample

<plist version="1.0">
 <dict>
  <key>XYZ</key>
  <string>ID</string>
  <key>APID</key>
  <array>
    <string>!@#$$!!</string>
  </array>
  <key>CreationDate</key>
  <date>9/20/2013</date>
  <key>Cert</key>
  <array>
    <data>
    abcs
    </data>
  </array>
  <key>ZZZ</key>
 <dict>
    <key>APID</key>
    <string>Filename</string>
    <key>get</key>
    <false/>
    <key>chain</key>
    <array>
        <string>oohhui</string>
    </array>
 </dict>
 <key>EXP</key>
 <date>9/21/2013</date>
 <key>Name</key>
 <string>Con</string>
 <key>IDstring</key>
 <array>
    <string>ABCD</string>
    <string>hdhd</string>
    </array>
Était-ce utile?

La solution

assuming your file is compatible with xml format you can use somethiing like

[xml]$x=gc c:\temp\test.xml
$x.plist.dict.key | %{$_ -replace 'XYZ','ABC'} #will replace any XYZ key value by ABC value;

Autres conseils

Try something like this:

$ID = ...

[xml]$plist = gc 'C:\path\to\your.plist'
$node = $plist.SelectSingleNode("//array/string[text()='ABCD']")

$newNode = $plist.CreateElement('string')
$newNode.AppendChild($plist.CreateTextNode($ID)) >$null

$node.ParentNode.InsertAfter($newNode, $node)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top