Környezet ([environment])

Nézzük az első olyan egyszerű .NET osztályt, amelynek statikus metódusai és tulajdonságai hasznunkra válhatnak. Ez a System.Environment , vagy röviden [Environment]. Nézzük, miről is van szó:

[13] PS C:\> [environment] | get-member -Static

 

 

   TypeName: System.Environment

 

Name                       MemberType Definition

----                       ---------- ----------

Equals                     Method     static bool Equals(System.Object objA...

Exit                       Method     static System.Void Exit(int exitCode)

ExpandEnvironmentVariables Method     static string ExpandEnvironmentVariab...

FailFast                   Method     static System.Void FailFast(string me...

GetCommandLineArgs         Method     static string[] GetCommandLineArgs()

GetEnvironmentVariable     Method     static string GetEnvironmentVariable(...

GetEnvironmentVariables    Method     static System.Collections.IDictionary...

GetFolderPath              Method     static string GetFolderPath(System.En...

GetLogicalDrives           Method     static string[] GetLogicalDrives()

ReferenceEquals            Method     static bool ReferenceEquals(System.Ob...

SetEnvironmentVariable     Method     static System.Void SetEnvironmentVari...

CommandLine                Property   static System.String CommandLine {get;}

CurrentDirectory           Property   static System.String CurrentDirectory...

ExitCode                   Property   static System.Int32 ExitCode {get;set;}

HasShutdownStarted         Property   static System.Boolean HasShutdownStar...

MachineName                Property   static System.String MachineName {get;}

NewLine                    Property   static System.String NewLine {get;}

OSVersion                  Property   static System.OperatingSystem OSVersi...

ProcessorCount             Property   static System.Int32 ProcessorCount {g...

StackTrace                 Property   static System.String StackTrace {get;}

SystemDirectory            Property   static System.String SystemDirectory ...

TickCount                  Property   static System.Int32 TickCount {get;}

UserDomainName             Property   static System.String UserDomainName {...

UserInteractive            Property   static System.Boolean UserInteractive...

UserName                   Property   static System.String UserName {get;}

Version                    Property   static System.Version Version {get;}

WorkingSet                 Property   static System.Int64 WorkingSet {get;}

Osztályok statikus tulajdonságértékeinek felderítéséhez készítettem egy függvényt:

function get-staticprops ([type] $type)

{

    $h = @{}

    $type | Get-Member -Static -MemberType property |

        ForEach-Object {$h.($_.name) = $type::($_.name)}

    $h

}

Ezzel megvizsgálva az [environment] osztály tulajdonságait, a következőket kaphatjuk:

[17] PS C:\> get-staticprops environment

 

Name                           Value

----                           -----

NewLine                        ...

CommandLine                    "C:\WINDOWS\system32\WindowsPowerShell\v1.0\...

UserName                       Administrator

ExitCode                       0

TickCount                      173265703

ProcessorCount                 1

StackTrace                        at System.Environment.get_StackTrace()...

MachineName                    DC

OSVersion                      Microsoft Windows NT 6.1.7600.0

UserDomainName                 R2

CurrentDirectory               C:\Users\Administrator

UserInteractive                True

Version                        2.0.50727.4927

HasShutdownStarted             False

SystemDirectory                C:\Windows\system32

WorkingSet                     49762304

Ezek közül szkriptjeinkben haszonnal használhatunk nem egy tulajdonságot. Például a TickCount megadja milliszekundumokban, hogy mennyi ideje fut a gépünk. Ezt felhasználva könnyen kiszámolhatjuk gépünk futását a legutóbbi indítástól napokban kifejezve:

PS C:\> [timespan]::FromMilliseconds([environment]::TickCount).totaldays

1,22547722222222

Nézzünk pár metódust is! Ugyan a környezeti változókhoz hozzáférünk közvetlenül PowerShellből is, de nézzük csak a $env:path változót:

[25] PS C:\> $env:path

%SystemRoot%\system32\WindowsPowerShell\v1.0\;C:\Windows\system32;C:\Windows;C

:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\

Windows Server 2008 R2 esetében ez közvetlenül nem használható, hiszen az elején ott van a %SystemRoot% környezeti változó, de még a DOS-os szintaxissal, ami a PowerShell számára nem értelmezhető. Ahhoz, hogy ez behelyettesíthető legyen a PowerShell segítségével, egy viszonylag bonyolult regex kifejezést kellene használni, de ennél sokkal egyszerűbb a ExpandEnvironmentVariables metódus használata:

[26] PS C:\> [environment]::ExpandEnvironmentVariables($env:path)

C:\Windows\system32\WindowsPowerShell\v1.0\;C:\Windows\system32;C:\Windows;C:\

Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\

Ezzel már tökéletes az eredmény!

Még egyértelműbb a speciális mappák tényleges elérési útját megmutató metódus haszna:

[34] PS C:\> [environment]::GetFolderPath("MyPictures")

C:\Users\Administrator\Pictures

[35] PS C:\> [environment]::GetFolderPath("ProgramFiles")

C:\Program Files

Hiszen ezek az elérési utak eltérnek különböző Windows verziók esetében, ezzel viszont verzió-függetlenül jól működő szkripteket tudunk írni. De nézzük meg, hogy mit is használhatunk a GetFolderPath metódus paramétereként, azaz mik ezek a speciális mappák! Ehhez legegyszerűbben írjunk olyan mappanevet, ami biztos nem jó, mert a hibajelzés el fogja árulni, hogy a lehetséges értékeket hol is találjuk:

PS C:\> [environment]::GetFolderPath("blabla")

Cannot convert argument "0", with value: "blabla", for "GetFolderPath" to type

"System.Environment+SpecialFolder": "Cannot convert value "blabla" to type "Sys

tem.Environment+SpecialFolder" due to invalid enumeration values. Specify one o

f the following enumeration values and try again. The possible enumeration valu

es are "Desktop, Programs, Personal, MyDocuments, Favorites, Startup, Recent, S

endTo, StartMenu, MyMusic, DesktopDirectory, MyComputer, Templates, Application

Data, LocalApplicationData, InternetCache, Cookies, History, CommonApplicationD

ata, System, ProgramFiles, MyPictures, CommonProgramFiles"."

At line:1 char:29

+ [environment]::GetFolderPath <<<< ("blabla")

    + CategoryInfo          : NotSpecified: (:) [], MethodException

    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

A hibajelzés 2. sorában látható, hogy ő a System.Environment+SpecialFolder felsorolás-típus elemeire vár, így már tudjuk, hogy mit kell keresni, amit a következő kifejezéssel ki is tudunk fejteni:

PS C:\> [System.Environment+SpecialFolder] | gm -Static -MemberType property

 

 

   TypeName: System.Environment+SpecialFolder

 

Name                  MemberType Definition

----                  ---------- ----------

ApplicationData       Property   static System.Environment+SpecialFolder App...

CommonApplicationData Property   static System.Environment+SpecialFolder Com...

CommonProgramFiles    Property   static System.Environment+SpecialFolder Com...

Cookies               Property   static System.Environment+SpecialFolder Coo...

Desktop               Property   static System.Environment+SpecialFolder Des...

DesktopDirectory      Property   static System.Environment+SpecialFolder Des...

Favorites             Property   static System.Environment+SpecialFolder Fav...

History               Property   static System.Environment+SpecialFolder His...

InternetCache         Property   static System.Environment+SpecialFolder Int...

LocalApplicationData  Property   static System.Environment+SpecialFolder Loc...

MyComputer            Property   static System.Environment+SpecialFolder MyC...

MyDocuments           Property   static System.Environment+SpecialFolder MyD...

MyMusic               Property   static System.Environment+SpecialFolder MyM...

MyPictures            Property   static System.Environment+SpecialFolder MyP...

Personal              Property   static System.Environment+SpecialFolder Per...

ProgramFiles          Property   static System.Environment+SpecialFolder Pro...

Programs              Property   static System.Environment+SpecialFolder Pro...

Recent                Property   static System.Environment+SpecialFolder Rec...

SendTo                Property   static System.Environment+SpecialFolder Sen...

StartMenu             Property   static System.Environment+SpecialFolder Sta...

Startup               Property   static System.Environment+SpecialFolder Sta...

System                Property   static System.Environment+SpecialFolder Sys...

Templates             Property   static System.Environment+SpecialFolder Tem...

Az eredményként kapott táblázat első oszlopában láthatók a lehetséges értékek, amiket használhatunk tehát.



Word To HTML Converter