Join-Path is a PowerShell cmdlet that combines a base path and a child path into a single one. This is useful for constructing file or directory paths dynamically. The syntax for using Join-Path is:
Join-Path -Path <base path> -ChildPath <child path>
Here's an example of using Join-Path to create a file path:
$directory = "C:\MyFolder"
$filename = "example"
$path = Join-Path -Path $directory -ChildPath "$($filename).txt"
In this example, $directory is the base path, $filename is the child path, and "$($filename).txt" is the desired file extension. Join-Path combines these to create the full file path, which would be "C:\MyFolder\example.txt".
The Invoke-WebRequest
PowerShell cmdlet is used to fetch content from a web page on the internet. It allows you to make HTTP requests, retrieve HTML content, and interact with web APIs directly from your PowerShell script.
Gets content from a web page on the internet.
# Here we are asking Google about PowerShell and saving the response
$Response = Invoke-WebRequest -URI https://www.google.com/search?q=powershell
# We use the Content property of $Response to access the webpage content
$Response.Content
In the example above, $Response
will store the content retrieved from the specified URL (https://www.google.com/search?q=powershell
). You can then use $Response
to parse and extract information from the web page as needed.
To learn more about Invoke-WebRequest
, you can visit the Microsoft documentation page. This resource provides detailed information and examples to help you understand and use this cmdlet effectively.
In PowerShell, you can show elapsed time using a simple timer script. Start by capturing the current time when your script begins with $StartTime = $(Get-Date)
. Then, calculate the elapsed time by subtracting the start time from the current time: $elapsedTime = $(Get-Date) - $StartTime
. Format the elapsed time into hours, minutes, and seconds using the "{0:HH:mm:ss}"
format and apply it to a DateTime object: $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
.
$StartTime = $(Get-Date)
# Your script here
$elapsedTime = $(Get-Date) - $StartTime
$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "Total elapsed time: $totalTime"
For more details and discussions, you can refer to this Stack Overflow post.
Writes the specified objects to the pipeline. If Write-Output
is the last command in the pipeline, the objects are displayed in the console.
Write-Output [-InputObject] <PSObject[]> [-NoEnumerate] [<CommonParameters>]
Write-Output
sends objects to the primary pipeline, also known as the "output stream" or the "success pipeline." To send error objects to the error pipeline, use Write-Error
.
This cmdlet is typically used in scripts to display strings and other objects on the console. One of the built-in aliases for Write-Output
is echo
and similar to other shells that use echo
. The default behavior is to display the output at the end of a pipeline.
Examples
Write-Output "Warning: setting not available"
Write-Output "Error message" >> $logfile
Write-Output "$Message" | Tee-Object $logFile -Append
Additional Resources
Saves command output in a file or variable and also sends it down the pipeline.
Tee-Object [-InputObject <PSObject>] [-FilePath] <String> [-Append] [[-Encoding] <Encoding>] [<CommonParameters>]
The Tee-Object
cmdlet redirects output, that is, it sends the output of a command in two directions (like the letter T). It stores the output in a file or variable and also sends it down the pipeline. If Tee-Object
is the last command in the pipeline, the command output is displayed at the prompt.
Example
Write-Output "$Message" | Tee-Object $logFile -Append
The PowerShell redirection operators are as follows, where n
represents the stream number. The Success stream ( 1
) is the default if no stream is specified.
>
Send specified stream to a file. n>
>>
Append specified stream to a file. n>>
>&1
Redirects the specified stream to the Success stream. n>&1
This example sends all Success stream data to a file called script.log
.
.\script.ps1 > script.log
This example sends all streams output from a script called script.ps1
to a file called script.log
.\script.ps1 *> script.log
Writes customized output to a host.
Write-Host [[-Object] <Object>] [-NoNewline] [-Separator <Object>] [-ForegroundColor <ConsoleColor>] [-BackgroundColor <ConsoleColor>] [<CommonParameters>]
The Write-Host
cmdlet's primary purpose is to produce for-(host)-display-only output, such as printing colored text like when prompting the user for input in conjunction with Read-Host. Write-Host
uses the ToString() method to write the output. By contrast, to output data to the pipeline, use Write-Output or implicit output.
Write-Host "no newline test " -NoNewline
Write-Host "second string"
no newline test second string
Further information can be found at Write-Host (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs.
The Copy-Item
cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it can't copy a file to a certificate drive.
This example copies the mar1604.log.txt file to the C:\Presentation directory. The original file isn't deleted.
Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation"
This example copies the contents of the C:\Logfiles directory into the existing C:\Drawings directory. The Logfiles directory isn't copied.
If the Logfiles directory contains files in subdirectories, those subdirectories are copied with their file trees intact. By default, the Container parameter is set to True, which preserves the directory structure.
Copy-Item -Path "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse
Further information and samples can be found at Copy-Item (Microsoft.PowerShell.Management) - PowerShell | Microsoft Docs
Selects objects or object properties.
The Select-Object
cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array.
To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters. To select object properties, use the Property parameter. When you select properties, Select-Object
returns new objects that have only the specified properties.
Example 1: Select objects by property
This example creates objects that have the Name, ID, and working set (WS) properties of process objects.
Get-Process | Select-Object -Property ProcessName, Id, WS
Select-Object (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs
Module: Microsoft.PowerShell.Utility
Creates table-like custom objects from the items in a comma-separated value (CSV) file.
Import-Csv [[-Delimiter] <Char>] [-Path] <String[]> [-Header <String[]>] [-Encoding <Encoding>] [<CommonParameters>]
The Import-Csv
cmdlet creates table-like custom objects from the items in CSV files. Each column in the CSV file becomes a property of the custom object and the items in rows become the property values. Import-Csv
works on any CSV file, including files that are generated by the Export-Csv
cmdlet.
Import-Csv (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs
Module: Microsoft.PowerShell.Core
Performs an operation against each item in a collection of input objects.
ForEach-Object [-InputObject <PSObject>] [-Begin <ScriptBlock>] [-Process] <ScriptBlock[]> [-End <ScriptBlock>] [-RemainingScripts <ScriptBlock[]>] [-WhatIf] [-Confirm] [<CommonParameters>]
The ForEach-Object
cmdlet performs an operation on each item in a collection of input objects. The input objects can be piped to the cmdlet or specified by using the InputObject parameter.
Starting in Windows PowerShell 3.0, there are two different ways to construct a ForEach-Object
command.
Module: Microsoft.PowerShell.Utility
Converts object properties in comma-separated value (CSV) format into CSV versions of the original objects.
ConvertFrom-Csv [[-Delimiter] <Char>] [-InputObject] <PSObject[]> [-Header <String[]>] [<CommonParameters>]
The ConvertFrom-Csv
cmdlet creates objects from CSV variable-length strings that are generated by the ConvertTo-Csv
cmdlet.
ConvertFrom-Csv (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs
Selects objects from a collection based on their property values.
Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] [-EQ] [<CommonParameters>]
The Where-Object
cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the Where-Object
cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows.
Example 1: Get stopped services
Get-Service | Where-Object {$_.Status -eq "Stopped"} Get-Service | where Status -eq "Stopped"
Where-Object (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs
Module: Az.ConnectedMachine
Retrieves information about the model view or the instance view of a hybrid machine.
Get-AzConnectedMachine [-SubscriptionId <String[]>] [-DefaultProfile <PSObject>] [<CommonParameters>]
Retrieves information about the model view or the instance view of a hybrid machine.
Example 1: List all connected machines in a subscription
Get-AzConnectedMachine -SubscriptionId 67379433-5e19-4702-b39a-c0a03ca8d20c Name Location OSName Status ProvisioningState ---- -------- ------ ------ ----------------- winwestus2_1 westus2 windows Connected Succeeded linwestus2_1 westus2 linux Connected Succeeded winwestus2_2 westus2 windows Connected Succeeded winwestus2_3 westus2 windows Connected Succeeded
Get-AzConnectedMachine (Az.ConnectedMachine) | Microsoft Docs
Gets preferences for the Windows Defender scans and updates.
Get-MpPreference [-CimSession <CimSession[]>] [-ThrottleLimit <Int32>] [-AsJob] [<CommonParameters>]
The Get-MpPreference cmdlet gets preferences for the Windows Defender scans and updates. For more information about the preferences that this cmdlet retrieves, see Windows Defender Preferences Class.
Example to view the scheduled scan day
$Preferences = Get-MpPreference
$Preferences.ScanScheduleDay
Details about the preferences for Windows Defender scans and updates can be found in Set-MpPreference PowerShell Cmdlet.
For additional details visit Get-MpPreference (Defender) | Microsoft Docs.
Module: Defender
Configures preferences for Windows Defender scans and updates.
The Set-MpPreference cmdlet configures preferences for Windows Defender scans and updates. You can modify exclusion filename extensions, paths, or processes, and specify the default action for high, moderate, and low threat levels.
Example to schedule to check for definition updates everyday.
This command configures preferences to check for definition updates every day.
Set-MpPreference -SignatureScheduleDay Everyday
Additional examples at Schedule antivirus scans using PowerShell | Microsoft Docs
Details about the cmdlet at Set-MpPreference (Defender) | Microsoft Docs
To construct an array of objects in PowerShell, each item within the array is inherently treated as an object. Unlike conventional arrays that may consist of strings or integers, PowerShell arrays primarily contain objects. Below is a structured example demonstrating the creation of an array comprising objects through explicit declaration:
$people = @(
[PSCustomObject]@{Name='John'; Age=26},
[PSCustomObject]@{Name='Jane'; Age=22}
)
In this illustration, $people is an array variable containing two objects. Each object is defined using the [PSCustomObject] syntax followed by property-value pairs enclosed within curly braces {}. This structured approach ensures clarity and ease of comprehension while creating arrays of objects in PowerShell.
Using the *-Content
cmdlets. There are four *-Content
cmdlets:
Add-Content
– appends content to a file.Clear-Content
– removes all content of a file.Get-Content
– retrieves the content of a file.Set-Content
– writes new content which replaces the content in a file.The two cmdlets you use to send command or script output to a file are Set-Content and Add-Content. Both cmdlets convert the objects you pass in the pipeline to strings and then output these strings to the specified file. A very important point here – if you pass either cmdlet a non-string object, these cmdlets use each object’s ToString() method to convert the object to a string before outputting it to the file.
See more at How to send output to a file - PowerShell Community (microsoft.com)
To install PowerShell on Windows, use the following link to get detailed instructions
For Windows 11 you can also use the Microsoft Store.
After you have created your PowerShell module, you will likely want to install the module on a system, so that you or others may use it. Generally speaking, this consists of copying the module files (ie, the .psm1, or the binary assembly, the module manifest, and any other associated files) onto a directory on that computer.
Installing a PowerShell Module - PowerShell | Microsoft Docs
Execution Policy is a Windows security measure that determines whether PowerShell scripts can run on a computer. PowerShell scripts cannot run on Windows by default (even for an administrator). The security policy that controls the ability to run PowerShell scripts on Windows is called Execution Policy.
You can check the current Execution Policy value in Windows 10 using the command:
Get-ExecutionPolicy
By default in Windows 10, this parameter is set to Restricted, which prevents any PowerShell scripts from executing.
You can set one of the following values in the PowerShell Execution Policy:
By default, the LocalMachine = Restricted policy is set at the computer level. To allow PowerShell scripts to run only in the current session, you can run the commands:
Set-ExecutionPolicy RemoteSigned –Scope Process
> Get-ExecutionPolicy
AllSigned
> Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine AllSigned