Category Archives: QuickTip

QuickTip: Get Domain Name of Computer

In PowerShell it is relatively trivial to retrieve the domain for the logged in user, as this is stored in the environment variable. In multi-domain environments it is often the case that the user account is a member of the same domain as the computer account. To retrieve the domain name of the current computer the following command can be executed:

1
[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()

ComputerDomainName

To only retrieve the Domain Name the following command can be used:

1
[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().DomainName

For more information about the GetIPGlobalProperties method and the IPGlobalProperties class please refer to the following article:
MSDN – IPGlobalProperties

Quicktip: PowerShell command history on Windows 10 using PSReadline

In Windows 10 PowerShell 5.0 comes bundled with PSReadline. This module allows for a number of useful features and today we will focus on getting access to the command history. A very useful feature of PSReadline is that it writes the history of PowerShell commands to a text file and this text file is easily accessible. The path where this file is stored can be found by executing the following command:

1
(Get-PSReadlineOption).HistorySavePath

PSReadLine

To view the list of previously executed commands you can type the following:

1
Get-Content -Path (Get-PSReadlineOption).HistorySavePath

This will output the contents of the history file to your PowerShell console. Alternatively the file can be opened by your favorite editor by using the Invoke-Item cmdlet:

1
Invoke-Item -Path (Get-PSReadlineOption).HistorySavePath

A very useful feature if you accidentally closed your console without saving your command history.

Quicktip: Use a Csv file to splat parameters into a function

I recently received a question on Reddit that asked if it is possible to use a csv file to create a hash table that can be used for splatting parameters into a function. The goal of this exercise is to be able to specify a csv file and to pass on the proper arguments to a function.

For example there is a csv file with the following contents:

SplatCsv

So based on this the New-Server function should be called as such:

1
New-Server -Templare 2012R2 -Spec DomainJoinSpec -Datastore Production2 -Cpus 1

In order to achieve this, the first step would be to remove the empty fields from the equasion as such:

1
2
$Csv = Import-Csv -Path Parameters.csv
$Csv.psobject.Properties | Where-Object {$_.Value}

This will import the csv and only display the colums in the csv that actually contain data. To ensure this data is stored in a hash table we can use the ForEach-Object. This cmdlet can be used to loop through the remaining results and to create a hashtable:

1
2
3
4
5
6
$Csv = Import-Csv c:\temp\params.csv
$Csv.psobject.Properties | Where-Object {$_.Value} | ForEach-Object -Begin {
$SplatParams = @{}
} -Process {
$SplatParams[$_.Name] = $_.Value
}

Now that the hash table has been created this can be used for splatting into the New-Server function:

1
New-Server @SplatParams

By combining the ForEach-Object cmdlet and the PSObject property that is piped into Where-Object it is possible to construct a custom hashtable that can be used for splatting. This can provide an easy alternative for non-technical users to provide parameters and arguments into a PowerShell function.

Quicktip: Use Windows Defender to scan a file or folder

As I was experimenting with the new PowerShell 5.0 cmdlets for Windows Defender I noticed that there is no parameter for starting a custom scan. As a workaround I used the mpcmdrun.exe tool to initiate the scan. For example the following code will execute a custom scan on C:\Temp:

1
& "$($env:programfiles)\Windows Defender\mpcmdrun.exe" -Scan -ScanType 3 -File 'C:\Temp'

MPCMDRun

This allows for scanning a custom folder, and the results will be displayed to the console. The results are also logged in the Windows Defender Operational log, if logging for Windows Defender has not been disabled. Using the Get-WinEvent cmdlet we can get this information from the eventlog.

1
2
Get-WinEvent -LogName 'Microsoft-Windows-Windows Defender/Operational' |
Select-Object -First 2 -ExpandProperty Message

MPCMDRun-EventLog

For more information on this topic have a look at the following resources:

Windows Defender
Security-Malware-Windows-Defender
Run (and Automate) Windows Defender from the Command Line

Quicktip: Create an object that refers to its own properties

Recently I received the question the /r/PowerShell community if it was possible to create an object that refers to its own properties when it is created. The user specified that they would prefer to create this as a one-liner.

Using the Add-Member cmdlet in combination with the -Passthru parameter this is quite simple to do, for example:

1
2
3
$Object = New-Object PSObject -property @{
    Property1 = 'Hello World'
} | Add-Member ScriptProperty GetProperty1 {$This.Property1} -PassThru

To make this slightly more interesting it is also possible to manipulate this object by using the manipulating the property. In the following example a property ‘Today’ is created and the script property uses this property to calculate the next week. For example:

1
2
3
$Object = New-Object PSObject -Property @{
        Today = (Get-Date).Date
} | Add-Member ScriptProperty NextWeek {($This.Today).AddDays(7)} -PassThru

ScriptPropertyNextWeek

It is also possible to create a ScriptMethod that uses the previously defined property, in the next example I create a ScriptMethod that can add or substract a week from the Today property:

1
2
3
4
$Object = New-Object PSObject -Property @{
        Today = (Get-Date).Date
} | Add-Member ScriptProperty NextWeek {($This.Today).AddDays(7)} -PassThru |
Add-Member ScriptMethod AddWeeks {param([int]$Week) $This.Today.AddDays($Week*7)} -PassThru

ScriptMethodAddWeeks

QuickTip: Pin PowerShell to the Taskbar

When you are working with PowerShell in your daily work it might be worth considering pinning PowerShell to the taskbar. By doing this you have easy access using either the the mouse of the keyboard hotkeys.

PinPowerShell

By placing PowerShell in the first location on the taskbar you will have the following hotkeys available:

Description of action Key Combination
Open new (non-administrative) PowerShell console if not open already, otherwise cycle through open consoles <WIN> 1
Open new Administrative PowerShell console if not open already, otherwise cycle through open consoles <CTRL> <SHIFT><WIN> 1
Open new (non-administrative) PowerShell console even if a console is already open <WIN> <SHIFT> 1
Open the context menu, allows for opening:

  • PowerShell as Administrator
  • PowerShell
  • ISE as Administrator
  • ISE
<WIN> <ALT> 1

Using the mouse you have the following, similar, options available to you. Similar to the keyboard combinations:

Description of action Mouse Combination
Open new (non-administrative) PowerShell console if not open already, otherwise cycle through open consoles Click
Open new (non-administrative) PowerShell console even if a console is already open <SHIFT> Click
Open new Administrative PowerShell console even if a console is already open <CTRL> <SHIFT> Click
Open the context menu, allows for opening:

  • PowerShell as Administrator
  • PowerShell
  • ISE as Administrator
  • ISE
RightClick

Using these key combinations allows you to access PowerShell faster and no mouse-clicking will be required anymore.

QuickTip: Select all links using Invoke-WebRequest

Today I was looking for a way to discover all links on my blog. Invoke-WebRequest returns a number of interesting properties, which can be listed by piping the output into the Get-Member cmdlet:

1
2
Invoke-WebRequest -Uri 'www.jaapbrasser.com' |
Get-Member -MemberType Property

The output from the previous command shows that there is a property named ‘Links’, we will use this property to retrieve all the urls from a site. For example by executing the following code:

1
(Invoke-WebRequest -Uri 'www.jaapbrasser.com').Links.Href

To ensure that only the unique links are selected Select-Object -Unique can be used:

1
2
(Invoke-WebRequest -Uri 'www.jaapbrasser.com').Links.Href |
Select-Object -Unique

Invoke-WebRequest