## pwsh -NoProfile -ExecutionPolicy Bypass -File xmlupdate.ps1 XMLファイル名 using namespace System.Xml.Linq using namespace System.Xml.XPath param( [Parameter(Mandatory = $true)] [string] $InputPath ) if (Test-Path $InputPath) { $dir = (Get-Location).Path $base = [System.IO.Path]::GetFileNameWithoutExtension($InputPath) $OutputPath = [System.IO.Path]::Combine($dir, ($base + ".new.xml")) } else { Write-Host "ファイルなし" exit } # SaveOptions の明示的生成 $saveOptions = [System.Xml.Linq.SaveOptions]::None ## XML読み込み $xmldoc = [System.Xml.Linq.XDocument]::Load($InputPath) ## ノード修正 $node = [System.Xml.XPath.Extensions]::XPathSelectElement($xmldoc, "/root/items/item[@id='005RD']") if ($node -ne $null) { $node.Value = "アイテムX" $node.SetAttributeValue("id", "005X") } ## ノード追加 $node = [System.Xml.XPath.Extensions]::XPathSelectElement($xmldoc, "/root/items") if ($node -ne $null) { $itemdoc = [System.Xml.Linq.XElement]::new("item","") $itemdoc.Value = "アイテム7Z" $itemdoc.SetAttributeValue("id","007Z") [void] $node.Add($itemdoc) } ## 修正結果書き出し $xmldoc.Save($OutputPath, $saveOptions)