archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Windows PowerShell 1.0 Looping with the for and foreach Statements - Techotopia
    a scenario is exactly what the for loop is intended to handle The syntax of a Windows PowerShell for loop is as follows for initializer conditional expression loop expression statements to be executed google ADSDAQBOX FLOW google The initializer typically initializes a counter variable Traditionally the variable i is used for this purpose For example i 0 This sets the counter to be the variable i and sets it to zero The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of iterations For example if we want to loop 100 times i lt 100 Finally the loop expression specifies the action to perform on the counter variable For example to increment by 1 i The body of statements to be executed on each iteration of the loop are contained within the code block defined by the opening and closing braces Bringing this all together we can create a for loop to perform the task outlined in the earlier example y 10 for i 0 i lt 10 i y y y 10240 Creating an Infinite for Loop A for loop which will execute an infinite number of times may be constructed using for syntax For example the following code sample will output Hello from Windows PowerShell until the program is manually terminated by the user or the computer is turned off or rebooted for Hello from Windows PowerShell Breaking Out of a for Loop Having created a loop it is possible that under certain conditions you might want to break out of the loop before the completion criteria have been met and particularly if you have created an infinite loop One such example might involve continually checking for activity on a network socket Once activity has been detected it will be necessary to break out of the monitoring loop and perform some other task For the purpose of breaking out of a loop Windows PowerShell provides the break statement which breaks out of the current loop and resumes execution at the code directly after the loop For example for i 0 i lt 10 i y y if y gt 100 break y 160 In the above example the loop will continue to execute until the value of j exceeds 100 at which point the loop will exit Nested for Loops So far we have looked at only a single level of for loop It is also possible to nest for loops where one for loop resides inside another for loop For example for i 0 i lt 100 i i i for j 0 j lt 10 j j j The above example will loop 100 times displaying the value of i on each iteration In addition for each of those iterations it will loop 10 times displaying the value of j Breaking From Nested Loops with Labels An important point to be aware of when breaking out of a nested for loop is that the break only exits

    Original URL path: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_Looping_with_the_for_and_foreach_Statements (2016-02-13)
    Open archived version from archive


  • Windows PowerShell 1.0 Looping with do and while Statements - Techotopia
    tasks This is essentially an upfront evaluation process If on the other hand myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of myCount This process repeats until the value of myCount is greater than 100 at which point the loop exits Windows PowerShell do while loops It is often helpful to think of the do while loop as an inverted while loop The while loop evaluates an expression before executing the code contained in the body of the loop If the expression evaluates to false on the first check then the code is not executed The do while loop on the other hand is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once For example you may want to keep stepping through the items in an array until a specific item is found You know that you have to at least check the first item in the array to have any hope of finding the entry you need The syntax for the do while loop is as follows do Windows PowerShell statements here while conditional expression In the do while example below the loop will continue until the value of a variable named i equals 0 i 10 do i i while i gt 0 Breaking from while Loops As with the for and foreach loop it is also possible to exit from a while or do while loop at any time through the use of the break statement When the execution path encounters a break statement the looping will stop and execution will proceed to the statements immediately following the loop In the following example the

    Original URL path: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_Looping_with_do_and_while_Statements (2016-02-13)
    Open archived version from archive

  • The Windows PowerShell 1.0 switch Statement - Techotopia
    if elseif else construct write host Please Enter Your Vehicle Model carModel read host switch carModel Patriot carManufacturer Jeep Focus carManufacturer Ford Corolla carManufacturer Toyota default carManufacturer unknown write host Manufacturer is carManufacturer Explaining the Example When executed the sample script will once again prompt for a car model Once entered the response is assigned to the carModel variable which in turn is used as the governing variable in the switch statement The default option simply sets the carManufacturer string to unknown if none of the case statements match the string entered by the user Using break in a Windows PowerShell switch Statement In the above example we did not use the break statement to exit out of the switch statement Although it was not visible during the execution the switch statement continued to perform matching even after a match was found To demonstrate this consider the following example where the Patriot match is included twice carModel Patriot switch carModel Patriot write host First match The car is a Jeep Patriot write host Second match The car is still a Jeep Corolla write host This car is a Toyota Because there is no break after a match has been found the switch statement moves on to other cases resulting in the following output First match The car is a Jeep Second match The car is still a Jeep To avoid this problem all that is needed is a break statement in each set of match statements For example carModel Patriot switch carModel Patriot write host First match The car is a Jeep break Patriot write host Second match The car is still a Jeep break Corolla write host This car is a Toyota As a result of these changes the switch statement will exit when it finds a match to the Patriot car model resulting in just one line of output First match The car is a Jeep The switch Variable When a switch is operating the value being evaluated for a match is assigned to a special variable referenced by This is provided so that the value may be accessed within the body of the switch construct This is of particular use when using expressions in a switch statement as described in the following section Using Expressions in a Windows PowerShell switch Statement One of the features of the Windows PowerShell switch statement that is missing from many other implementations in other languages is the ability to use expressions to evaluate whether a case matches For example the following switch construct is designed to find out whether the value falls within a particular value range Note the use of the variable as described above myVal 15 switch myVal lt 5 write host is less than 5 lt 10 write host is less than 10 lt 20 write host is less than 20 Note also that the expression must be enclosed in curly braces When executed the preceding example will generate the following output 15 is less than 20 Wildcards

    Original URL path: http://www.techotopia.com/index.php/The_Windows_PowerShell_1.0_switch_Statement (2016-02-13)
    Open archived version from archive

  • Windows PowerShell 1.0 Functions - Techotopia
    PS C Users Administrator names john First name is john Last name is Unknown Specifying Function Parameter Types By default if Windows PowerShell receives a parameter which is of the wrong type for the operations performed in the body of a function it will attempt to perform a type conversion to the correct type The following function for example multiplies two numbers passed through as arguments function multiply numbers val1 val2 Performing calculation val1 val2 If a string is passed through as a parameter Windows PowerShell will attempt to convert it to a number This may or may not be possible depending on the contents of the string For example the following works PS C Users Administrator multiply numbers 2 004 Performing calculation 8 but the following does not PS C Users Administrator multiply numbers 2 FOUR Performing calculation Cannot convert value FOUR to type System Int32 Error Input string was not in a correct forma t At line 4 char 11 val1 val2 Unfortunately as can be seen from the above error message the function was allowed to begin executing It printed out the Performing calculation message before the error was reported on line 3 Clearly it would be advantageous for the function to reject a parameter if it is not of a specified type before the function starts to do anything This can be achieved by using type casting in the parameter declaration For example to force the two parameters for our multiply numbers function to be numbers they could be cast as type int32 function multiply numbers int32 val1 int32 val2 Performing calculation val1 val2 Now when a parameter is specified that is both of the wrong type and unsuitable for conversion to the correct type the function rejects the parameter immediately without commencing the execution process PS C Users Administrator multiply numbers 4 five multiply Cannot convert value five to type System Int32 Error Input string was not in a co rrect format At line 1 char 9 multiply 4 five Using Functions in a Pipeline As discussed in previous chapters Windows PowerShell allows cmdlets to be executed in a sequence with the results from one cmdlet used as input to the next cmdlet in the pipeline chain Pipelines are created by separating the cmdlets by the pipe character In order to include a function in a pipeline it is necessary for that function to process the input variable This variable contains the results from the previous cmdlet or function in the pipeline In the following example a function named filelengths is designed to take the output from the dir cmdlet iterate through the input variable and display the name and length of each file function filelengths foreach file in input Filename file Length file length All that remains to test out this function is to pipe a dir command through to it PS C Users Administrator dir txt filelengths Filename C Users Administrator date txt Length 162 Filename C Users Administrator error txt Length 334

    Original URL path: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_Functions (2016-02-13)
    Open archived version from archive

  • Working with File Systems in Windows PowerShell 1.0 - Techotopia
    Name get RootDirectory Property System IO DirectoryInfo RootDirectory get TotalFreeSpace Property System Int64 TotalFreeSpace get TotalSize Property System Int64 TotalSize get VolumeLabel Property System String VolumeLabel get set For example the drive format may be obtained either using the get DriveFormat method or by reference to the DriveFormat property PS C Users Administrator mydrive get driveformat NTFS PS C Users Administrator mydrive DriveFormat NTFS Alternatively the WMI Win32 LogicalDisk object may be accessed as follows mydrive Get WmiObject Win32 logicaldisk Filter DeviceID C PS C Users Administrator mydrive FreeSpace 9110175744 Once again the full complement of properties and methods available may be obtained using the Get Member cmdlet PS C Users Administrator Get WmiObject Win32 logicaldisk Filter DeviceID C get member TypeName System Management ManagementObject root cimv2 Win32 LogicalDisk Name MemberType Definition Chkdsk Method System Management ManagementBaseObject Chkdsk System B Reset Method System Management ManagementBaseObject Reset SetPowerState Method System Management ManagementBaseObject SetPowerState S Access Property System UInt16 Access get set Availability Property System UInt16 Availability get set BlockSize Property System UInt64 BlockSize get set Caption Property System String Caption get set Compressed Property System Boolean Compressed get set ConfigManagerErrorCode Property System UInt32 ConfigManagerErrorCode get set ConfigManagerUserConfig Property System Boolean ConfigManagerUserConfig get set CreationClassName Property System String CreationClassName get set Description Property System String Description get set DeviceID Property System String DeviceID get set DriveType Property System UInt32 DriveType get set ErrorCleared Property System Boolean ErrorCleared get set ErrorDescription Property System String ErrorDescription get set ErrorMethodology Property System String ErrorMethodology get set FileSystem Property System String FileSystem get set FreeSpace Property System UInt64 FreeSpace get set InstallDate Property System String InstallDate get set LastErrorCode Property System UInt32 LastErrorCode get set MaximumComponentLength Property System UInt32 MaximumComponentLength get set MediaType Property System UInt32 MediaType get set Name Property System String Name get set NumberOfBlocks Property System UInt64 NumberOfBlocks get set PNPDeviceID Property System String PNPDeviceID get set PowerManagementCapabilities Property System UInt16 PowerManagementCapabilities get set PowerManagementSupported Property System Boolean PowerManagementSupported get set ProviderName Property System String ProviderName get set Purpose Property System String Purpose get set QuotasDisabled Property System Boolean QuotasDisabled get set QuotasIncomplete Property System Boolean QuotasIncomplete get set QuotasRebuilding Property System Boolean QuotasRebuilding get set Size Property System UInt64 Size get set Status Property System String Status get set StatusInfo Property System UInt16 StatusInfo get set SupportsDiskQuotas Property System Boolean SupportsDiskQuotas get set SupportsFileBasedCompression Property System Boolean SupportsFileBasedCompression get set SystemCreationClassName Property System String SystemCreationClassName get set SystemName Property System String SystemName get set VolumeDirty Property System Boolean VolumeDirty get set VolumeName Property System String VolumeName get set VolumeSerialNumber Property System String VolumeSerialNumber get set CLASS Property System String CLASS get set DERIVATION Property System String DERIVATION get set DYNASTY Property System String DYNASTY get set GENUS Property System Int32 GENUS get set NAMESPACE Property System String NAMESPACE get set PATH Property System String PATH get set PROPERTY COUNT Property System Int32 PROPERTY COUNT get set RELPATH Property System String RELPATH get set SERVER Property System String SERVER get set SUPERCLASS Property

    Original URL path: http://www.techotopia.com/index.php/Working_with_File_Systems_in_Windows_PowerShell_1.0 (2016-02-13)
    Open archived version from archive

  • Windows PowerShell 1.0 File Handling - Techotopia
    test txt name attributes value System IO FileAttributes ReadOnly bxor System IO FileAttributes Hidden A full list of PowerShell supported file attributes provided through System IO FileAttributes is outlined in the following table google ADSDAQBOX FLOW google Member Description ReadOnly File is read only Hidden File is hidden and thus is not included in an ordinary directory listing System File is a system file The file is part of the operating system or is used exclusively by the operating system Archive File archive status Used to mark files for backup or removal Normal The file is normal and has no other attributes set Cannot be used in conjunction with other attributes Reading Text Files in Windows PowerShell Text files are read in PowerShell using the Get Content cmdlet which is also available via the cat and type aliases When executed with one or file names the content of those files is directed to the output stream The following example reads and displays the contents of a single text file PS C tmp get content test txt This is a test The contents of multiple files may be read in a single command by providing a comma separated array of file names PS C tmp get content test txt test2 txt test3 txt test4 txt This is a test This is a test2 This is a test3 This is a test4 The Get Content supports text files which are encoded as String Unicode Byte BigEndianUnicode UTF8 UTF7 and Ascii selectable using the encoding option For example get content encoding Ascii test txt Reading Binary Files in Windows PowerShell Binary files are also read using the Get Content cmdlet using the encoding Byte option For example the following command reads the contents of a binary file and assigns it to a variable mybinfile get content encoding byte c windows winhelp exe Writing to Files in Windows PowerShell Content is written to files in Windows PowerShell using the Set Content and Out File cmdlets Whilst both commands write data to files each provides different results Set Content writes the raw data to the file in the form in which it is received by the cmdlet Out File on the other hand will format the output for human consumption in much the way content is formatted by default when displayed in the Windows PowerShell console As such Out File is unsuitable for writing binary files As an example of reading and writing files the following command make a binary copy of the Windows winhelp exe executable binary file get content encoding byte winhelp exe set content encoding byte c tmp myhelp exe To append content to the end of an existing file the Add Content cmdlet may be used Searching for Strings in Files with Windows PowerShell The contents of files may be searched for specific pattern matches through the use of the Select String cmdlet In the simplest form Select String can be used to find a specific string in a single file

    Original URL path: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_File_Handling (2016-02-13)
    Open archived version from archive

  • An Overview of Windows PowerShell 1.0 and .NET - Techotopia
    Install dll MetadataToken PortableExecutableKind ReflectionOnly False Specific values may be extracted using the select object cmdlet For example to list just the FullName field PS C AppDomain CurrentDomain GetAssemblies select object FullName FullName mscorlib Version 2 0 0 0 Culture neutral PublicKeyToken b77a5c561934e089 Microsoft PowerShell ConsoleHost Version 1 0 0 0 Culture neutral PublicKeyToken 31bf3856ad364e35 System Version 2 0 0 0 Culture neutral PublicKeyToken b77a5c561934e089 System Management Automation Version 1 0 0 0 Culture neutral PublicKeyToken 31bf3856ad364e35 System Configuration Install Version 2 0 0 0 Culture neutral PublicKeyToken b03f5f7f11d50a3a Microsoft PowerShell Commands Management Version 1 0 0 0 Culture neutral PublicKeyToken 31bf3 Microsoft PowerShell Security Version 1 0 0 0 Culture neutral PublicKeyToken 31bf3856ad364e35 Microsoft PowerShell Commands Utility Version 1 0 0 0 Culture neutral PublicKeyToken 31bf3856 System Data Version 2 0 0 0 Culture neutral PublicKeyToken b77a5c561934e089 System Xml Version 2 0 0 0 Culture neutral PublicKeyToken b77a5c561934e089 System DirectoryServices Version 2 0 0 0 Culture neutral PublicKeyToken b03f5f7f11d50a3a System Management Version 2 0 0 0 Culture neutral PublicKeyToken b03f5f7f11d50a3a Loading NET Assemblies into Windows PowerShell If NET functionality is required from an assembly which is not loaded by default when Windows PowerShell is invoked it must first be loaded before it can be used This is achieved using the LoadWithPartialName static method of the System Reflection Assembly class For example to load the WinForms assembly in preparation for creating a GUI based application the following would need to be executed PS C System Reflection Assembly LoadWithPartialName System Windows Forms GAC Version Location True v2 0 50727 C Windows assembly GAC MSIL System Windows Forms 2 0 0 0 b77a5c561934e08 Once loaded the classes in the assembly may subsequently be called upon to perform tasks from within Windows PowerShell NET Static Members and Properties Static methods and properties may be accessed without creating instances of the class in question The syntax for accessing a static method is as follows Classname Method parameters For example the following invokes the Get BackgroundColor static method of the System Console class to obtain the background color of the Windows PowerShell console window PS C System Console get backgroundcolor DarkMagenta Alternatively the Set BackgroundColor method may be invoked to switch the background of the console to a different color PS C System Console Set backgroundcolor red Similarly the static properties of a class may be accessed using the following syntax Classname Property In the following example the above syntax is used to extract today s date from the System DateTime class PS C System DateTime Today Tuesday December 09 2008 12 00 00 AM It is not typically possible to set the value of a static property Instance Members and Properties In the case of instance members an instance of the class must first be created before the methods and properties of that class may be used from within PowerShell The syntax for creating an instance of a class also referred to as an object requires the use of the new object cmdlet as

    Original URL path: http://www.techotopia.com/index.php/An_Overview_of_Windows_PowerShell_1.0_and_.NET (2016-02-13)
    Open archived version from archive

  • Creating GUIs in Windows PowerShell 1.0 with WinForms - Techotopia
    the pre loaded assemblies it is necessary to load WinForms prior to creating GUIs Assemblies are loaded using the static LoadWith PartialName method of the reflection assembly class passing through the name of the WinForms assembly as an argument reflection assembly LoadWithPartialName System Windows Forms Once loaded we are ready to create a simple GUI from within Windows PowerShell A Basic Windows PowerShell GUI Once the WinForms assembly has been loaded the next step is to create a simple example As previously discussed WinForms GUIs consist of containers controls and events With this in mind the following example creates a form container and a button control adds the button to the form and displays the dialog reflection assembly LoadWithPartialName System Windows Forms form New Object Windows Forms Form button New Object Windows Forms Button button text Click Here form controls add button form ShowDialog When executed the resulting dialog will appear as follows Windows PowerShell and WinForms Events The next area to cover involves the handling of events An event is typically triggered when a user interacts with a control For example clicking on a button control will trigger an event Event handlers are nothing more than lines of code which define what is to happen when the event is triggered for example an event handler may be written to exit the application when a Close button is clicked In Windows PowerShell event handlers take the form of scriptblocks which are essentially sequences of commands wrapped in braces Event handlers are added to a control using methods which have the following syntax add eventname scriptblock where eventname is the name of the event to be handled and scriptblock is the code to be executed when the event is triggered For example to close the dialog in the above example when the button is clicked button add click form close Using scriptblocks would quickly become unwieldy if all the code to be executed had to be included along with the add eventname method An alternative to this approach is to call a function instead The following adaptation of our example defines a function called do exit and subsequently references it in the event handler scriptblock reflection assembly LoadWithPartialName System Windows Forms function do exit form close form New Object Windows Forms Form button New Object Windows Forms Button button text Click Here button add click do exit form controls add button form ShowDialog Setting WinForms Properties WinForms components are essentially objects and as such have properties which can be set to alter component appearance and behavior As with other object properties these can be accessed using standard dot notation In the previous example we used this approach to set the text of the button control button text Click Here Similarly we could set the title of the form using the form object s text property form text PowerShell WinForms Example Bringing it all Together Now that we have seen a simple GUI created in Windows PowerShell and covered some of the

    Original URL path: http://www.techotopia.com/index.php/Creating_GUIs_in_Windows_PowerShell_1.0_with_WinForms (2016-02-13)
    Open archived version from archive



  •