This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Frank Tucker Frank Tucker 2 months, 2 weeks ago.

  • Author
  • #68058
    Profile photo of rbiboy

    Hi, I am reading a book on PowerShell. I am confused on a particular code on attributes.
    The attribute to the file has both "Archive" and "ReadOnly". What am confused about is that where in this code that it deleted the attribute of "ReadOnly" and how did it do it?

    # Get File Attributes
    $file = get-item –path "c:\Program Files\MyCustomSoftware\Graphics\FirstGraphic.png"
    $attributes = $file.attributes
    # Convert attributes to string
    $attributes = $attributes.tostring()
    # Split individual attributes into array
    $attributes = $attributes.split(",")
    # Read through the individual attributes
    Foreach ($attribute in $attributes) {
    # If read Only, skip
    if ($attribute –like "*ReadOnly*") {
    write-host "Skipping Attribute: $attribute"
    # Else add attribute to attribute list
    else {
    $newattribute += "$attribute,"
    Write-Host "Attribute Added: $attribute"
    # Remove the trailing comma
    $newattribute = $newattribute.trimend(",")
    # Write over existing attributes with new attributes
    $file.attributes = $newattribute
    Write-host "New File attributes are: " $file.attributes

  • #68061
    Profile photo of Frank Tucker
    Frank Tucker

    It does not delete it, just not added to the list... The final output comes from $newattribute
    Any attribute that is -like "*readonly*" is never added to $newattribute
    Only items that are ELSE (anything not *readonly*) are added in line 16 $newattribute += "$newattribute,"

    To help understand: run one line at a time in PowerShell ISE while manually checking variables/arrays below by just typing in their names and pressing enter. Don't forget to reset/blank $newattribute = $null after run the script before running again. Y

You must be logged in to reply to this topic.