Access modifiers

Depending on the type of object, properties may be read-only or read/write. These may be identified using Get-Member and by inspecting the access modifiers.

In the following example, the value in curly braces at the end of each line is the access modifier:

PS> $File = New-Item NewFile.txt -Force
PS> $File | Get-Member -MemberType Property

TypeName: System.IO.FileInfo

Name MemberType Definition
---- ---------- ----------
Attributes Property System.IO.FileAttributes Attributes {get;set;}
CreationTime Property datetime CreationTime {get;set;}
CreationTimeUtc Property datetime CreationTimeUtc {get;set;}
Directory Property System.IO.DirectoryInfo Directory {get;}
DirectoryName Property string DirectoryName {get;}
Exists Property bool Exists {get;}

When the modifier is {get;}, the property value is read-only; attempting to change the value will result in an error:

PS> $File = New-Item NewFile.txt -Force
PS> $File.Name = 'NewName'
'Name' is a ReadOnly property.
At line:1 char:1
+ $File.Name = 'NewName'
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException

When the modifier is {get;set;}, the property value may be read and changed. In the preceding example, CreationTime has the set access modifier. The value can be changed; in this case, it may be set to any date after January 1, 1601:

$File = New-Item NewFile.txt -Force
$File.CreationTime = Get-Date -Day 1 -Month 2 -Year 1692 

The result of the preceding command can be seen by reviewing the properties for the file in PowerShell:

Get-Item NewFile.txt | Select-Object -ExpandProperty CreationTime

Alternatively, you can use explorer, as shown in the following screenshot:

In the preceding example, the change made to CreationTime is passed from the object representing the file to the file itself. The object used here, based on the .NET class System.IO.FileInfo, is written in such a way that it supports the change. A property may indicate that it can be changed (by supporting the set access modifier in Get-Member) and still not pass the change back to whatever the object represents.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.69.152