Reading XML attribute value using PowerShell

Welcome Forums General PowerShell Q&A Reading XML attribute value using PowerShell

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
2 years, 11 months ago.

  • Author
    Posts
  • #33673

    Participant
    Points: 0
    Rank: Member

    I am having trouble reading the session timeout value (20) from the following config file. I have tried different method however, they seem to be not worthy reading the value. Any idea of how to get the value of the Session Timeout. Appreciate your help.

    Web config file :

    ———————————————————————————————————–
    Here are the methods that I have tried to retrieve the value :

    #Accessing the contents of Web Config file

    $path = "\Web.configfile"

    $xdoc = [xml] (get-content $path)

    #reading the default value of SessionTimeout

    $sessionTimeOut = $xdoc.configuration.System.Web.sessionState.timeout

    $timeOut = $sessionTimeOut.timeout

    Write-Host $timeOut´╗┐

  • #33674

    Participant
    Points: 31
    Rank: Member

    Please post the web config file on Gist and paste a link to it here so that we can take a look.

  • #33677

    Participant
    Points: 0
    Rank: Member

    Please find the Gist URL below for the XML content.

    I have tried and got the result with the below script :

    Here is how I am able to read the value of the attribute. However, I am not able to update it by following method. The console shows the value but the web config file does not update at all.

    $path = "\web.config"
    $xdoc = [xml] (get-content $path)

    #reading the default value of SessionTimeout
    $sessionTimeOut = $xdoc.configuration.'System.Web'.sessionState.timeout
    Write-Host $sessionTimeOut

    $sessionTimeOut = "1"

    #Save the Web Config file
    $xdoc.Save($path)

    Write-Host $sessionTimeOut

  • #33680

    Participant
    Points: 52
    Rank: Member

    Because you're assigning the value to another variable. You need to update the value of the property within the xdoc variable as that is what you're saving in the end.

  • #33681

    Participant
    Points: 0
    Rank: Member

    @peter – Thank you very much. It worked.

    Here is how I have retrieved and updated the value of the property :

    #Accessing the contents of Web Config file
    $path = "\Web.config"
    $xdoc = [xml] (get-content $path)

    #reading the default value of SessionTimeout
    $sessionTimeOut = $xdoc.configuration.'System.Web'.sessionState.timeout

    $updateTimOut = $xdoc.configuration.'System.Web'.sessionState
    $finalTimeOut = $updateTimOut.timeout = "1"

    #Save the Web Config file
    $xdoc.Save($path)

    Write-Host $finalTimeOut

The topic ‘Reading XML attribute value using PowerShell’ is closed to new replies.