Blog   ❯   Author: Fabio MoschiniDate: 09.12.2022

PowerShell examples - 2

alt text for image

PowerShell Script Examples - 2

Displaying a Message Box

With PowerShell, it's possible to display information through windows, for example using a message box.
With the following example, we'll display a simple message box with only a confirmation button:
Add-Type -AssemblyName PresentationFramework $msgBoxInput = [System.Windows.MessageBox]:: Show('This is an information','Title','Ok','Info')
Output:
alt text for image


Let's look at the two instructions used in detail. The first one:
Add-Type -AssemblyName PresentationFramework
is used to add the PresentationFramework assembly to the PowerShell session.
Within the assembly, the namespace System.Windows is defined, which contains the implementation of the MessageBox class.

The second instruction:
$msgBoxInput = [System.Windows.MessageBox]:: Show('This is an information','Title','Ok','Info')
invokes the Show method of theSystem.Windows.MessageBox class with the appropriate parameters:
  • the first parameter is a string that defines the text to be displayed inside the message box
  • the second parameter is a string with the title of the message box
  • the third parameter is a string that indicates the buttons to display in the message box:
    • - 'OK'
    • - 'OKCancel'
    • - 'YesNoCancel'
    • - 'YesNo'
  • finally, the fourth parameter is a string that defines the type of icon to display inside the message box:
    • 'None'
    • 'Error'
    • 'Question'
    • 'Warning'
    • 'Information'

For message boxes that display multiple buttons, you can store the type of button pressed like this:
Add-Type -AssemblyName PresentationFramework $msgBoxResponse = [System.Windows.MessageBox]:: Show('Do you want to close the program?','Warning','YesNoCancel','Question') switch ($msgBoxResponse) { 'Yes' { Write-Host "You pressed 'Yes'" } 'No' { Write-Host "You pressed 'No'" } 'Cancel' { Write-Host "You pressed 'Cancel'" } }

Changing the Displayed Text Color

To write a warning message, we use the Write-Warning cmdlet:
Write-Warning "This is a warning."
The text is displayed in yellow.
To modify the color of the displayed text as desired, use theWrite-Host instruction by setting the-BackgroundColor and-ForegroundColor parameters:
Write-Host "Text with red background and default color" -BackgroundColor Red Write-Host "Text with default background and yellow color" -ForegroundColor Yellow Write-Host "Text with blue background and green color" -BackgroundColor Blue -ForegroundColor Green
Output:
alt text for image

Restarting the Computer

To restart the computer, you can use the Restart-Computer cmdlet:
Restart-Computer

Listing Running Processes

To list the processes running on the computer, use:
Get-Process
It's possible to sort the listed processes, for example by descending memory usage:
Get-Process | Sort-Object –Property ws -Descending
If there are many processes, it might be useful to limit the display to the first n elements:
Get-Process | Sort-Object –Property ws -Descending | Select –first 5

Using Hexadecimal or Binary Numbers

To convert a hexadecimal number to decimal, simply prefix the hexadecimal number with the sequence 0x:
$hexValue=0xA3F $hexValue
Output:
2623

To convert a number from decimal to binary, you can use:
[Convert]::ToString(1234,2)
The first parameter is the decimal number to convert.

Using Custom Forms

With PowerShell, you can define "WinForm" objects by setting the appropriate properties.
Forms can contain visual objects like buttons, text boxes, and labels.
Let's see an example:
Add-Type -AssemblyName System.Windows.Forms # line 1 $NewForm = New-Object Windows.Forms.Form # line 2 $NewForm.Text = "WinForm Example" # line 3 $NewForm.Size = New-Object Drawing.Size @(300,200) # line 4 $NewForm.StartPosition = "CenterScreen" # line 5 $Button = New-Object System.Windows.Forms.Button # line 6 $Button.add_click({(Get - Date) | (Out - Host)}) # line 7 $Button.Text = "Click here" # line 8 $Button.Location = New-Object System.Drawing.Point(100,70) # line 9 $NewForm.Controls.Add($Button) # line 10 $Dialouge = $NewForm.ShowDialog() # line 11
Let's analyze each line:
line 1: as we've seen in one of the previous examples, this instruction adds the System.Windows.Forms assembly to the PowerShell session;
line 2: creation of a Windows.Forms.Form object;
line 3: setting the form's Text property;
line 4: setting the form's dimensions;
line 5: defining the position where the form will be displayed;
line 6: creation of a System.Windows.Forms.Button object;
line 7: adding the click event handler, whose code displays the current date and time;
line 8: setting the button's Text property;
line 9: defines the button's position relative to the form;
line 10: adds the button to the form;
line 11: displays the form as a modal window. The form is very simple: it contains a button whose press displays the current date and time in the prompt from which the script is run.

Clearing the History

To clear the command history of a PowerShell session, the command to use is:
Clear-History

Information About Disks Connected to the Computer

To get information about disks connected to the computer, use theGet-Disk cmdlet:
Get-Disk
Get-Disk lists logical disks; to get the list of physical disks, use:
Get-PhysicalDisk
Finally, to get the list of volumes:
Get-volume

Taking a Screenshot

With this script, you can take a screenshot of the main monitor:
# Directory that will contain the screenshot files $Path = "C:Test" # If the directory doesn't exist, notify and stop the script If (!(test-path $path)) { Write-Output "The directory '$path' does not exist." exit } # Add the assembly to the PowerShell session Add-Type -AssemblyName System.Windows.Forms # Determine the image dimensions in the main monitor $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds # Initialize the image with dimensions equal to the screen resolution $image = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height) # Create a graphics object based on the screen content $graphic = [System.Drawing.Graphics]::FromImage($image) $point = New-Object System.Drawing.Point(0, 0) $graphic.CopyFromScreen($point, $point, $image.Size); $cursorBounds = New-Object System.Drawing.Rectangle([System.Windows.Forms.Cursor]::Position, [System.Windows.Forms.Cursor]::Current.Size) # Take the screenshot [System.Windows.Forms.Cursors]::Default.Draw($graphic, $cursorBounds) $screen_file = "$Path" + $env:computername + "_" + $env:username + "_" + "$((get-date).tostring('yyyy.MM.dd-HH.mm.ss')).png" # Save the screenshot in PNG format $image.Save($screen_file, [System.Drawing.Imaging.ImageFormat]::Png) # Display the filename Write-Output "The screenshot has been saved to:" Write-Output $screen_file

Customizing PowerShell Colors

To modify the colors in a PowerShell window, you can use this script:
$Host.UI.RawUI.BackgroundColor="Blue" $Host.UI.RawUI.ForegroundColor="white"
In this case, blue is used for the background color, while the text is white.

Stopping a Process

We've already seen the Get-Process cmdlet for listing running processes.
To stop a process, use the Stop-Process command followed by the parameter -Id <process id> or the parameter -Name <process name>.
The process id is information that can be determined throughGet-Process.

Examples:
  • to terminate all instances of the "CalculatorApp" process:Stop-Process -Name "CalculatorApp"
  • to terminate a specific instance of a process, you need to use its Id:Stop-Process -id 12345

Converting to HTML

It's possible to convert PowerShell command output information to HTML format.
For example, to have an HTML page with the list of running processes, you can use this command:
Get-Process | ConvertTo-Html -Property Name, Path, Company -Title "Process Information" | Out-File proc.html
Let's see in detail what happens:
  • the first command executed is Get-Process which returns the list of active processes;
  • the result is sent to the ConvertTo-Html command through |, which extracts the information specified by-Property and uses it to create an HTML table with the title indicated by the -Title parameter;
  • finally, the result of the ConvertTo-Html command is sent to Out-File to write theproc.html file.