Change the ComputerName value in Unattend.xml using PowerShell

A quick and dirty PowerShell script to update the value of ComputerName in Unattend.xml before imaging.

This particular value is located at:

<unattend>
 <settings pass="generalize">
  <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <computername>

Which is a bit of a mouthful, but we can be lazy and just pull the value from the nth component node (in my case it's 3, or the 4th component node). PowerShell uses dots to describe the hierarchical path, which looks a lot neater than the above:

$xml.unattend.settings.component[3].computername


To repeat, the value of .component[n] will change depending on the structure of the file.

The value of the computername node can be changed by just providing the new value:

$xml.unattend.settings.component[3].computername = "$computerName"


The imported XML then needs to be saved back to the file on disk:

$xml.save("$unattendFile")


1:  param(  
2:       [parameter(Mandatory = $true)]  
3:       [ValidateNotNullOrEmpty()]  
4:       [string]$computerName  
5:  )  
6:    
7:  Set-ExecutionPolicy Unrestricted  
8:    
9:  $systemDrive = $env:systemdrive  
10:  $unattendFile = "$systemDrive\Unattend.xml"  
11:    
12:  [xml]$xml = get-content $unattendFile  
13:    
14:  $currentName = $xml.unattend.settings.component[3].computername  
15:  write-host "Current Name: "$currentName"`n"  
16:    
17:  $xml.unattend.settings.component[3].computername = "$computerName"  
18:    
19:  $newName = $xml.unattend.settings.component[3].computername  
20:  write-host "New Name: "$newName"`n"  
21:    
22:  $xml.save("$unattendFile")  

Comments

  1. Hello Sir,
    thanks for this nice article, when I execute the script i am facing a following exception, I could not figure it out, I need your kind guidance,
    let me tell you the path of the Autounattend.xml file is correct and the node exists, when I execute the code it displays the existing value.

    Exception setting "ComputerName": "The property 'ComputerName' cannot be found on this object. Verify that the property exists and can be set."
    At line:18 char:3
    + $xml.unattend.settings.component[3].ComputerName = "$computerName" ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

    Regards
    Abdul Rehman

    ReplyDelete
  2. Abdul... you may want to check to see what section the computername value is found. For me, it was component[4].

    ReplyDelete

Post a Comment

Popular posts from this blog

Testing out Link Aggregation

Xbox 360 Exclusive JRPGs on Xbox One