User Tools

Site Tools




Microsoft Safety Scanner

it does not provide real-time protection against viruses, cannot update its virus definitions and expires after ten days. On the other hand, it can be run on a computer which already has an antivirus product without any potential interference. Therefore, it can be used to scan a computer where there is a potential infection and the user wants a second check from another antivirus.


a command-line disk partitioning utility
list volume

Microsoft Reserved Partition

The MSR should be located after the EFI System Partition (ESP) and any OEM service partitions, but it must be located before any primary partitions of bootable Windows operating systems. Microsoft expects an MSR to be present on every GPT disk, and recommends it to be created as the disk is initially partitioned. However, the MSR partition is not actually required for Windows to work, so can be deleted; though doing this can possibly break the boot-loader.
The GPT label for this partition type is E3C9E316-0B5C-4DB8-817D-F92DF00215AE.
The MSR partition is not visible within the Microsoft Windows Disk Management control utility, but it is listed with the Microsoft Diskpart command line utility.

Microsoft account

In December 1999, Microsoft neglected to pay their annual $35 “” domain registration fee to Network Solutions. The oversight made Hotmail, which used the site for authentication, unavailable on Christmas Eve, December 24. A Linux consultant, Michael Chaney, paid it the next day (Christmas), hoping it would solve this issue with the downed site. The payment resulted in the site being available the next morning. In Autumn 2003, a similar good Samaritan helped Microsoft when they missed payment on the “” address, although no downtime resulted.



The service is built using HTML5 technologies, and files up to 300 MB can be uploaded via drag and drop into the web browser, or up to 2 GB via OneDrive desktop application for Microsoft Windows and OS X.

Plans 5GB free


Disk Usage:

  • C:\myUtils\du64.exe -l 1 works nicely
  • doesn't list individual files, eg in the current directory, so it complements Get-ChildItem
  • du -l 1 -q . usefully lists just the subdirectories, with their sizes.
  • du -v . lists recursively all of the directories in the current one, with their sizes.
  • The executable du.exe needs to be somewhere in your %PATH%. I put mine in C:\Program Files\ConEmu.

Process Explorer:

Windows 10


System Restore:

  • to make a System Restore Point, I hit the windows key, and type “restore”, which gets me a link to “Create a restore point”
  • my system only remembers the last 8 Points…
  • Restoring causes a long, slow system restart

Environment variables


Win+Brk keys together (for System) > Advanced system settings (for System Properties) > Environment Variables > System variables > (select) Path > Edit

Kioskea's guide, eg, in a Console, echo %PATH% (but the capitalisation ain't necessary).

Windows 7

  • Compatibility Center is where you go to discover if your perfectly good, fully functional peripheral device will work with “we've moved on” Windows 7.
  • Recent Places (in Explorer) are super handy.
  • Safe Mode I can't recall ever needing to use.
  • System Configuration Utility (C:\Windows\System32\msconfig.exe) I shortcut onto Desktop to quickly get at anything that I want to stop loading at Startup.
  • WordPad is a handy rtf editor. Pressing <Alt> pops up a load of little shortcut indicators next to the menus – very nice.
  • Works 9.0 I only use now very occasionally for getting at legacy works file formats.

Microsoft Keyboard Layout Creator:

Start Menu:

  • C:\ProgramData\Microsoft\Windows\Start Menu\ - the real location of the global Start Menu.
  • C:\Users\jo\AppData\Roaming\Microsoft\Windows\Start Menu\ - the real location of your user-space-specific Start Menu additions, like Dropbox.


is useful, with extra modes:

  • Scientific
  • Programmer
  • Unit conversion
  • Date calculation

I set: Menu > Calculator > Properties > Shortcut key = Ctrl+Shft+Alt+C


It just works, but if you want to change something you can get at it by typing Firewall in the Menu prompt.

How a Firewall works: - is very techy.

Microsoft Security Essentials


I set: Menu > Paint > Properties > Shortcut key = Ctrl+Alt+P

%windir%\system32\mspaint.exe - I find most useful for pasting a printscreen image into then trim and save. Can reduce jpegs, but doesn't seem to play animated gifs.

System Restore Point

  • I've often got my netbook software into a mess, but have never found a useful or meaningful system restore point to return to. What works very well for me is keeping a precise list of what I've installed, and, from time to time, use Samsung Recovery Solution 4 to make a system backup. That way I know what state I'm returning my netbook to when Windows 7 has gone funny.

Windows shell

Open command window here - Shift + right-click in a folder gets this option.

The Windows shell is the main graphical user interface in Microsoft Windows, and since Windows 95 has been hosted by Windows Explorer. The Windows shell includes well-known Windows components such as the taskbar and the Start menu. The Windows shell is not the same as a “command-line shell”, but the two concepts are related. The Windows shell is also not to be confused with Windows' window manager, which displays windows and controls how they look.

Windows Registry

Windows Registry

The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values or further keys. Keys are referenced with a syntax similar to Windows' path names, using backslashes to indicate levels of hierarchy. Keys must have a case insensitive name without backslashes.
The keys at the root level of the hierarchical database are generally named by their Windows API definitions, which all begin “HKEY”. They are frequently abbreviated to a three- or four-letter short name starting with “HK” (e.g. HKCU and HKLM). Technically, they are predefined handles (with known constant values) to specific keys that are either maintained in memory, or stored in hive files stored in the local filesystem and loaded by the system kernel at boot time and then shared (with various access rights) between all processes running on the local system, or loaded and mapped in all processes started in a user session when the user logs on the system.
Abbreviated HKLM, HKEY_LOCAL_MACHINE stores settings that are specific to the local computer.
Windows PowerShell comes with a Registry provider which presents the Registry as a location type similar to the file system. The same commands used to manipulate files/directories in the file system can be used to manipulate keys/values of the Registry.

File Systems

exFAT has been adopted by the SD Card Association as the default file system for SDXC cards larger than 32 GiB.

NTFS vs FAT vs exFAT


New Technology File System

$Boot Volume boot record. This file is always located at the first clusters on the volume. It contains bootstrap code (see NTLDR/BOOTMGR) and a BIOS parameter block including a volume serial number and cluster numbers of $MFT and $MFTMirr. $Boot is usually 8192 bytes long. is suitably esoteric

Default cluster size for NTFS, FAT, and exFAT: eg 1TB disk – 4KB clusters.

Easy to create a link in Windows 7 by opening a console run as administrator, and using mklink command:

cd C:\Program Files\Ampps\www\IT\data\media\cross_platform
mklink markdown.vim %UserProfile%\vimfiles\ftplugin\markdown.vim
  • C:\Users\jo\vimfiles\ftplugin\markdown.vim = the real file
  • C:\Program Files\Ampps\www\IT\data\media\cross_platform\markdown.vim = the new link to it (if you look at it's Properties, you will see it's just a Shortcut to the real file)

If I now copy the cross_platform folder somewhere (eg when I push my DokuWiki installation to a server), the copied link becomes a real copy of the original file linked to, which is nice.

Here's a symlink for a directory (again in administrator console):

cd C:\Program Files\Ampps\www\IT\data
mklink /D pages D:\IT\DWpages

- it's easy when you know how!

NTFS symbolic link

NTFS junction point

I had a weird case of a folder that I'd not used for years becoming one, and thus unremovable until I booted my netbook with Puppy Linux.

Internet Protocol

Network and Sharing Center > Change adapter settings brings up Control Panel\Network and Internet\Network Connections. If you right-click on Local Area Connection you can send a shortcut for the little Status window to your desktop, which is handy to check Activity. In that Local Area Connection Status window also you can click on Properties > Internet Protocol Version 4 (TCP/IPv4) to bring up an Internet Protocol Version 4 (TCP/IPv4) Properties window in which you can set an IP address for your machine.



or is simply a built in 'name' for your local computer.

ping localhost

http://localhost/ not working on Windows 7. What's the problem? - a labyrinthine chat

The hosts file

C:\Windows\System32\drivers\etc\hosts > is a computer file used by an operating system to map hostnames to IP addresses. The hosts file is a plain text file, and is conventionally named hosts.

How can I reset the Hosts file back to the default?

( with gVim as Administrator) uncommenting (removing # from) the line

#       localhost

- didn't speed up access for my Windows 7 Home Edition.

the URL of localhost

Localhost = http://127.a.b.c:8112 where a, b, c are any integer values from 0-255, except that c can't be 0

So these three IP addresses all go to my Deluge:

Command Prompt

in Windows 10

  • dir/w %windir% lists contents of C:\WINDOWS, as does dir/w \Windows.
dir/w %TEMP%
Directory of C:\Users\Joseph\AppData\Local\Temp


robocopy/mir G:\Files E:\Files /unilog:G:\Files_toHPP.log
 D:\Dropbox\Current>robocopy/mir Artisan F:\Current\Artisan 

- mirror syncs from D:\Dropbox\Current\Artisan to F:\Current\Artisan.

Everything is listed in an indented layout, but differences are preceded by:

  • added from the source:
    • New File = not in the destination folder
    • Newer = there's already an older target
    • Older = there's already a newer target
    • New Dir = not in the destination folder
  • *EXTRA File - deleted from the destination
  • *EXTRA Dir - deleted from the destination


Robocopy, or “Robust File Copy”, is a command-line directory and/or file replication command.
A “mirror” mode, which keeps trees in sync by optionally deleting files out of the destination that are no longer present in the source.
Ability to skip files that already appear in the destination folder with identical size and timestamp.
A continuously updated command-line progress indicator.
Ability to copy file and folder names exceeding 254 characters — up to a theoretical limit of 32,000 characters — without errors.
Folder copier, not file copier


echo %APPDATA%


TYPE (DOS command)

The analogous Unix command is cat. In Windows PowerShell, type is a predefined command alias for the Get-Content Cmdlet which basically serves the same purpose.

definitions from

del - Delete one or more files
  • del/q/a:h * - delete quietly (without requesting confirmation) all files with hidden attribute
  • del/s *.pdf - deletes all pdfs recursively
rd Delete folder(s)


  • dir “%TEMP%”
  • dir /a to also list hidden files.
  • dir/w “%ProgramFiles%”
  • dir/a:h - lists hidden stuff only
  • dir/adh/s lists all hidden subdirectories
    • dir/adh/b/s compactly
  • dir “* (Rahula's conflicted copy *”/a/s - finds files like android (Rahula's conflicted copy 2014-10-22).txt created by Dropbox
  • dir/s/a:h - list only hidden stuff
  • dir/b - will return just the filepaths in a directory, listed without any other info
    • dir/s/b *Céline* will thus list all files containing that person's name in the path

Find a Directory/Folder with CMD without knowing full path: dir *M57SLI* /ad/s finds “M57SLI” somewhere in the name.


eg start/w pandoc -o outfile.pdf.



PS E:\Play1> netsh interface ipv4 show
The following commands are available:
Commands in this context:
show addresses - Shows IP address configurations.
show compartments - Shows compartment parameters.
show config    - Displays IP address and additional information.
show destinationcache - Shows destination cache entries.
show dnsservers - Displays the DNS server addresses.
show dynamicportrange - Shows dynamic port range configuration parameters.
show excludedportrange - Shows all excluded port ranges.
show global    - Shows global configuration parameters.
show icmpstats - Displays ICMP statistics.
show interfaces - Shows interface parameters.
show ipaddresses - Shows current IP addresses.
show ipnettomedia - Displays IP net-to-media mappings.
show ipstats   - Displays IP statistics.
show joins     - Displays multicast groups joined.
show neighbors - Shows neighbor cache entries.
show offload   - Displays the offload information.
show route     - Shows route table entries.
show subinterfaces - Shows subinterface parameters.
show tcpconnections - Displays TCP connections.
show tcpstats  - Displays TCP statistics.
show udpconnections - Displays UDP connections.
show udpstats  - Displays UDP statistics.
show winsservers - Displays the WINS server addresses.
netsh interface ipv4 show addresses
netsh interface ipv4 show dnsservers
netsh interface ipv4 show ipstats
netsh interface ipv4 show subinterfaces

Change DNS with script

netsh interface ipv4 set address name="Local Area Connection" source=static addr= mask= gateway=

- gives a correct syntax for getting into my TL-WR702N

netsh interface ipv4 show config is comprehensive

netsh interface ipv4 show interfaces - reports the names of the interfaces, on my N130:

Wireless Network Connection & Local Area Connection

To set the DHCP Server (ie the default setting), from the command line:

netsh interface ip set address name="Local Area Connection" source=dhcp

among many other things, also allows the user to change the IP address on their machine

.NET Framework

.NET Framework

It includes a large library and provides language interoperability (each language can use code written in other languages) across several programming languages… Microsoft also produces an integrated development environment largely for .NET software called Visual Studio.

Regular Expressions:

Windows PowerShell

"vim: nowrap tw=0:" > G:\Files_toHPP.log; robocopy /mir G:\Files E:\Files /unilog+:G:\Files_toHPP.log /tee

Environment Variables:

  • $Env:PSModulePath -split';'
  • $env:Path -split ';' - lists the path values, nicely split into newlines.

the Pipeline:

Flatten out an image directory structure

Including gif: gci -r -i *.gif, *.jpg, *.jpeg, *.png | %{ cp $_ ((Resolve-Path $_.fullname -Relative).Substring(2) -replace '\\', '--') }

Recursively find all *.jpg, *.jpeg & *.png files in subfolders in the current directory, copy them into the current directory with prefixes representing their relative filepaths.

gci -r -i *.jpg, *.jpeg, *.png |
	$RelativeImagePath=Resolve-Path $_.fullname -Relative
	$FlatPath=($RelativeImagePath.Substring(2) -replace '\\', '--')
	Copy-Item $_ $FlatPath

- compacted down to one line:

gci -r -i *.jpg, *.jpeg, *.png | %{ cp $_ ((Resolve-Path $_.fullname -Relative).Substring(2) -replace '\\', '--') }

- also (usually) catches capitalised file extensions, like *.JPG

one-line Pandoc pdfs updating

So I have a directory containing markdown files, and also subdirectories, and sub-subdirectories, and so on, all containing my markdown files that I keep personal notes in. I find this an incredibly effective system as I can swiftly move around, search and edit these files in gVim. This directory is easily copyable to my smartphones, which can easily open text files in various ways, but sometimes pdf is simpler to open and search on a smartphone. So I would like all of these markdown files to be converted to pdf, and I would like to do this from time to time, efficiently. This is helpful for use on my smartphones but has the added benefit that if I want someone else to access my personal notes, they're in both markdown and pdf format, which is much easier for everyone.

I wondered if I could write a one-liner that would recursively search through the directory for all markdown files, and if there's not an equivalent pdf with a later date, make one. Scott Hanselman's one-liner conviced me that I could. So here is the development of my first ever big Powershell one-liner:

Recursively lits all of the markdown files by name only:

gci -r -i *.md |foreach{echo $}

For existing markdown files in a directory, list the equivalent pdf files with their LastWriteTime's:

gci *.md|foreach{$pdf=$_.directoryname+"\"+$_.basename+".pdf";if(test-path "$pdf"){gi "$pdf"}}

Recursively list pdfs with LastWriteTimes earlier than markdowns:

gci -r -i *.md|%{$pdf=$_.directoryname+"\"+$_.basename+".pdf";if(test-path "$pdf"){$mdd=$_.LastWriteTime;gi "$pdf"|?{$_.LastWriteTime -lt $mdd}}}

Recursively list all of the markdown filepaths with LastWriteTimes, and each followed by the equivalent pdf filepaths with either their LastWriteTimes, and, where the pdf is out-of-date, “- to redo” appended, or, if the equivalent pdf doesn't yet exist, the commment “- not yet made” (This gives us a visual clear visual picture of which pdfs need to be re-Pandoc'd):

gci -r -i *.md|%{$md=$_.fullname;$mdt=$_.LastWriteTime;"$md -> $mdt";$pdf=$_.directoryname+"\"+$_.basename+".pdf";if(test-path "$pdf"){gi "$pdf"|%{$pdft=$_.LastWriteTime; if($pdft -gt $mdt){"$pdf > $pdft"}else{"$pdf > $pdft - to redo"}}}else{"$pdf -- not yet made"}}

Add in a condition to simulate firing off Pandoc for those pdfs that either haven't been made yet, or need redoing:

gci -r -i *.md|%{$md=$_.fullname;$mdt=$_.LastWriteTime;"$md -> $mdt";$gp=$false;$pdf=$_.directoryname+"\"+$_.basename+".pdf";if(test-path "$pdf"){gi "$pdf"|%{$pdft=$_.LastWriteTime; if($pdft -gt $mdt){"$pdf > $pdft"}else{$gp=$true;"$pdf > $pdft - to redo"}}}else{$gp=$true;"$pdf -- not yet made"}if($gp){"- go pandoc"}}

The finished recursive one-liner, firing off Pandoc for all those markdown files whose pdf is either not there or out-of-date:

gci -r -i *.md|%{$md=$_.fullname;$mdt=$_.LastWriteTime;"$md -> $mdt";$gp=$false;$pdf=$_.directoryname+"\"+$_.basename+".pdf";if(test-path "$pdf"){gi "$pdf"|%{$pdft=$_.LastWriteTime; if($pdft -gt $mdt){"$pdf > $pdft"}else{$gp=$true;"$pdf > $pdft - to redo"}}}else{$gp=$true;"$pdf -- not yet made"}if($gp){"- running pandoc";&pandoc -V mainfont="Arial" --toc --toc-depth=4 -f markdown_strict $md -o $pdf --latex-engine=xelatex}}

which Version

$PSVersionTable reports the version you've got, and $PsHome shows it to be installed (for backwards compatibility) in C:\Windows\System32\WindowsPowerShell\v1.0.

Windows PowerShell

Windows PowerShell includes a dynamically typed scripting language which can implement complex operations using cmdlets imperatively. The scripting language supports variables, functions, branching (if-then-else), loops (while, do, for, and foreach), structured error/exception handling and closures/lambda expressions, as well as integration with .NET. Variables in PowerShell scripts have names that start with $; they can be assigned any value, including the output of cmdlets. Strings can be enclosed either in single quotes or in double quotes: when using double quotes, variables will be expanded even if they are inside the quotation marks. Enclosing the path to a file in braces preceded by a dollar sign (as in ${C:\foo.txt}) creates a reference to the contents of the file. If it is used as an L-value, anything assigned to it will be written to the file. When used as an R-value, the contents of the file will be read. If an object is assigned, it is serialized before being stored.
Initially using the code name “Monad”, PowerShell was first shown publicly at the Professional Developers Conference in September 2003. All major releases are still supported, and each major release has featured backwards compatibility with preceding versions.
Comparison of cmdlets with similar commands

Cmdlets & Objects


(PowerShell v5.1.14393.187) Write-Output:

"This file's encoding is UTF-16LE, it has a Byte Order Mark set, and CR+LF newline markings at the end of each line." > PS-defaultFileEncoding.txt


Get-ChildItem . | Sort-Object length -descending
gci * |%{$_.basename}
gci * |?{$_.PSIsContainer}
gci -r . |?{$_.PSIsContainer -and $_.fullname -notmatch '.git'}
gci -r . |?{$_.PSIsContainer}
gci -r . |?{$_.PSIsContainer} |%{echo ($_.basename)}
ls -name
ls -r -name
ls -r *.eml
ls -r *projet* | select fullname
ls -r -i '* (* conflicted copy *' |%{echo $_.fullname}
ls -r -i '* (* conflicted copy *' |%{echo $_.fullname} |ri
ls . | select fullname
  • gci *.md lists the markdown files in the current directory
  • gci -r produces a neatly laid-out series of tables showing all contents of the current tree
  • gci -r -i *.md,*.pdf shows (includes) only the markdown and pdf files
  • ls *\.git\config|%{echo $_.fullname} - returns all of the Git config's in repositories in the current directory.
  • ls -r -force -i |%{echo $_.fullname};; - recursively lists all of the files (which are normally hidden). * Standard Aliases: dir, list, ls, gci Counting: - (ls -r).count reports the number of files and folders under the current one - (ls -r *.eml).count reports the number of eml files - (ls -r -force).count includes hidden stuff LastAccesTime: ls . | select lastaccesstime, fullname ls . -r | select lastaccesstime, fullname Remove-Item: * Aliases: del, erase, rd, rm, rmdir, ri * ls -r -force -i |rm -force - recursively removes all of the files (which are normally hidden). “Repair” some jpg's: * ls *.jpg|%{$out=$_.basename+“magick.JPG”; magick $_ $out} * ls *.jpg|%{$out=$_.basename+“-72dpi.JPG”; exiftool -filename=“$out” -xresolution=72 -yresolution=72 $_} * ls *.jpg|%{$out=$_.basename+“-72dpi.JPG”; exiftool -filename=“$out” -xresolution=72 -yresolution=72 $_; ri $_} === Objects === * Foreach-Object: Looping Through a Collection of Objects * Introduction at WindowsITPro The Get-Member Cmdlet: Listing the Properties and Methods of a Command or Object, Standard Alias: gm. So, for example, gci|gm shows what objects are delivered by Get-ChildItem for directories and for files. Select-Object: * Selecting Specific Properties of an Object * Standard Aliases: select * WindowsITPro's guide === Select-String === * ls -r *.tex | select-string “memoir” finds those *.tex containing the string memoir * ls -r -i *.cls,*.tex | select-string -pattern “\\xspace” finds LaTeX files containing text “\xspace” Sorting files by timestamps: ls -r .gitignore | ForEach-Object { $_.LastWriteTime.ToString('yyyyMMdd-HH:mm:ss') + “ : ” + $_.FullName } | sort ls -r *.eml | ForEach-Object { $_.LastWriteTime.ToString('yyyyMMdd-HH:mm:ss') + “ : ” + $_.FullName } | sort ls -r | ForEach-Object { $_.LastAccessTime.ToString('yyyyMMdd-HH:mm:ss') + “ : ” + $_.FullName } | sort ls -r | ForEach-Object { $_.LastWriteTime.ToString('yyyyMMdd-HH:mm:ss') + “ : ” + $_.FullName } | sort ==== Guides ==== * Guy Thomas' tutorials * Microsoft Script Center's Scripting with Windows PowerShell Command lists: * Simon Sheppard’s "A-Z Index of Windows PowerShell 2.0 commands" * Steve Tibbett's Cheatsheet is basic === Dr Tobias Weltner === Master-PowerShell is excellent, and it's downloadable as a pdf. Chapter 1 The PowerShell Console * Ctrl+C bail out at any time and cancel the current command or input * char(s)F8 then keep on F8'ing until find the previous command beginning with char * Ctrl+Home/End deletes to start/end of line ==== renaming files recursively ==== remove diacritics from a filepath: - Check: gci -r -i '*Céline*' |%{echo ($_.fullname -replace 'é','e')} - Do: gci -r -i '*Céline*' |%{mi $_.fullname ($_.fullname -replace 'é','e')} Add “####” to end of directory names: - check: gci -r . |?{$_.PSIsContainer} |%{echo ($_.fullname -replace '$','####')} - do: gci -r . |?{$_.PSIsContainer} |%{mi $_.fullname ($_.fullname -replace '$','####')} - exclude .git folder: gci -r . |?{$_.PSIsContainer -and $_.fullname -notmatch '.git'} |%{mi $_.fullname ($_.fullname -replace '$','####')} === reset Dropbox conflicted copies === My Dropbox account was unattached from my Dropbox directory on my netbook for a while, but I updated many text files therein, so that when I re-installed Dropbox, it renamed my changes like this: * android (Rahula's conflicted copy 2014-10-22).txt - my local files, considered conflicted by Dropbox * android.txt - the online version, downloaded from, and considered authoratative by Dropbox - evidently these are in the wrong order, so I want a quick script to find these conflicts, remove the downloaded versions, and return the “conflicted” filenames to their original state. First, list all of the changes compactly, and visually scan through them: gci -r -i '* (Rahulas conflicted copy *'

Compact that list to just the file locations:

gci -r -i '* (Rahula''s conflicted copy *' |%{echo $_.fullname}

Now test a generalised regular expression on an example name:

'android (Rahula''s conflicted copy 2014-10-22).txt' -replace ' \(Rahula''s conflicted copy ....-..-..\)',''

& focus on a digital date only:

'android (Rahula''s conflicted copy 2014-10-22).txt' -replace ' \(Rahula''s conflicted copy \d{4}-\d\d-\d\d\)',''

So now list the conflicted files stripped back to their original locations:

gci -r -i '* (Rahula''s conflicted copy *' |%{echo ($_.fullname -replace ' \(Rahula''s conflicted copy \d{4}-\d\d-\d\d\)','')}

Finally, force the conflicted files back to their original locations:

gci -r -i '* (Rahula''s conflicted copy *' |%{mi $_.fullname ($_.fullname -replace ' \(Rahula''s conflicted copy \d{4}-\d\d-\d\d\)','') -force}

at Wikiversity

3. ISE

The Get-Alias cmdlet displays a list of current Windows PowerShell aliases.
The Write-Host cmdlet writes directly to the host environment, bypassing the pipeline.
Write-Host 'Hello PowerShell!'

> The Write-Output cmdlet writes to the pipeline. Write-Output 'Hello PowerShell!'
Comparing Write-Host and Write-Output
When there are no other commands in the pipeline, Write-Host and Write-Output appear functionally identical. The difference is clear, however, when the pipeline is used. To provide the most functionality for future use and automation of PowerShell scripts, Write-Output is the preferred output cmdlet. The Get-Date cmdlet may be used to demonstrate the difference between Write-Host and Write-Output.

# This script demonstrates the difference between Write-Host and Write-Output
Write-Host '1/1/01' | Get-Date      # Displays 1/1/01 (no pipeline content).
Write-Output '1/1/01' | Get-Date    # Displays the formatted date.
'1/1/01' | Get-Date                 # Displays the formatted date.

4. Variables

# This script demonstrates data types and data type conversion.
$value = 1.9
$value              # Displays 1.9
[int32]$value       # Displays 2
[float]$value       # Displays 1.9
[string]$value      # Displays 1.9
[boolean]$value     # Displays True
[datetime]$value    # Displays January 9 ...
Single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.
# This script demonstrates the difference between single quotes and double quotes.
$single = '$(1 + 2)'
$double = "$(1 + 2)"
Write-Output $single    # Displays $(1 + 2)
Write-Output $double    # Displays 3
The Read-Host cmdlet reads a line of input from the console. Following is an example of a script that requests input from the user and then uses that input to generate the output. Note the use of both single and double quotes for string processing.
# This script displays a message based on user input.
$input = Read-Host 'Is it morning, afternoon, or evening? '
Write-Output "Good $input!"

5. Expressions

Arithmetic operators calculate values.
$a = 3
$b = 2
$a + $b    # 5
$a - $b    # 1
$a * $b    # 6
$a / $b    # 1.5
$a % $b    # 1
-$a        # -3
Assignment operators assign calculated values to variables.
$a = 3
$b = 2
$a += $b    # a = 5
$a -= $b    # a = 3
$a *= $b    # a = 6
$a /= $b    # a = 3
$a %= $b    # a = 1
Unary operators increment or decrement a single variable by one.
$a = 1
$a++    # a = 2
$a--    # a = 1
Comparison operators compare values and test conditions.
$a = 3
$b = 2
$a -eq $b    # False
$a -ne $b    # True
$a -lt $b    # False
$a -gt $b    # True
$a -le $b    # False
$a -ge $b    # True
Logical operators compare complex conditions.
$a = 3
$b = 2
$a -lt $b -and $b -lt $a    # False
$a -lt $b -or $b -lt $a     # True
$a -lt $b                   # False
-not ($a -lt $b)            # True
String operators split, join, and concatenate substrings.
$a = 'Cat,Dog,Fish,Hamster'
$a -split ','                           # Cat 
                                        # Dog 
                                        # Fish 
                                        # Hamster 
$b = @('Cat','Dog','Fish','Hamster')
$b -join ','                            # Cat,Dog,Fish,Hamster
'Cat' + 'Dog' + 'Fish' + 'Hamster'      # CatDogFishHamster

6. Conditions

The if statement runs code blocks based on the results of one or more conditional tests.
$input = Read-Host 'Is it Morning (M), Afternoon (A), or Evening (E)? '
if($input -eq 'm')
    Write-Output 'Good morning!'
elseif($input -eq 'a')
    Write-Output 'Good afternoon!'
elseif($input -eq 'e')
    Write-Output 'Good evening!'
    Write-Output 'Hello!'
The switch statement checks multiple conditions for a given value and runs the corresponding code blocks.
$input = Read-Host 'Is it Morning (M), Afternoon (A), or Evening (E)? '
    m {'Good morning!'}
    a {'Good afternoon!'}
    e {'Good evening!'}
    default {'Hello!'}
The -match operator is used to match regular expressions. For example:
$input = Read-Host 'Enter zip code'
if(!($input -match '^\d{5}(-\d{4})?$'))
    Write-Output "$input is not a valid zip code."
The switch -Regex statement checks multiple conditions for a given value based on regular expression matching and runs the corresponding code blocks.
$input = Read-Host 'Enter something'
switch -Regex ($input)
    '.'     {'You entered a character'}
    '\d'    {'You entered a digit'}
    '\s'    {'You entered a space'}
    '\w'    {'You entered a word'}
    '\w \w' {'You entered multiple words'}
    default {'You entered nothing'}
The break statement immediately exits the nearest enclosing Foreach, For, While, Do, or Switch statement.
In regex, | inicates either|or.
In regex, ? inicates there is zero or one of the preceing element.
In regex, * inicates there is zero or more of the preceing element.
In regex, + inicates there is one or more of the preceing element.
In regex, () is use to group elements.
In regex, . matches any single character.
In regex, [] matches any single character containe within the brackets.
In regex, [^] matches any single character not containe within the brackets.
In regex, ^ matches the start of the string.
In regex, $ matches the en of the string.
In regex, w matches a wor.
In regex, matches a igit.
In regex, \s matches whitespace.

7. Loops

$i = 0
while($i -lt 3)
    Write-Output $i
$i = 0
    Write-Output $i
}while($i -lt 3)
$i = 0
    Write-Output $i
}until($i -ge 3)
for($i = 0; $i -lt 3; $i++)
    Write-Output $i
$processes = Get-Process
foreach($process in $processes)
    if($process.PM / 1024 / 1024 -gt 100)
        Write-Output ('Process ' + $process.Name + ' is using more than 100 MB RAM.')
The continue statement immediately returns script flow to the top of the innermost While, Do, For, or ForEach loop.
The break statement causes Windows PowerShell to immediately exit the innermost While, Do, For, or ForEach loop or Switch code block.
Exit causes Windows PowerShell to exit a script or a Windows PowerShell instance.
The ForEach-Object cmdlet runs a command list once for each item in a collection.[9] While the ForEach-Object cmdlet is often more convenient, the foreach statement and a coded loop usually offers better performance.
Get-Process | ForEach-Object { if($_.PM / 1024 / 1024 -gt 100) {'Process ' + $_.Name + ' is using more than 100 MB RAM.'} }

The Start-Sleep cmdlet allows you to pause Windows PowerShell activity for a specified period of time. It is particularly useful with long-running scripts or infinite loops.

8. Arrays and Hash Tables

Initializing an Array $array = @(1, 2, 3)
Checking the Size of an Array $array.Length
Accessing Array Elements $array[0] + $array[1] + $array[2]
Initializing an Empty Array $array = @()
Array elements are removed by combining sub-arrays. $array = $array[0] + $array[2]
for($i = 0; $i -lt $array.Length; $i++)
foreach($element in $array)
Multi-Dimensional Arrays
$array = @(1, 2, 3), @(4, 5, 6), @(7, 8, 9)
$array[0]       # 1
                # 2
                # 3
$array[0][0]    # 1
$array[2][2]    # 9
Initializing a Hash Table
$pets = @{Cat = 'Frisky'; Dog = 'Spot'; Fish = 'Nimo'; Hamster = 'Whiskers'}

> Accessing Hash Table Items

$pets.Cat        # Frisky
$pets.Dog        # Spot
$pets.Fish       # Nimo
$pets.Hamster    # Whiskers
Initializing an Empty Hash Table $pets = @{}
Adding Items to a Hash Table
$pets.Add('Cat', 'Frisky')
$pets.Add('Dog', 'Spot')
$pets.Add('Fish', 'Nimo')
$pets.Add('Hamster', 'Whiskers')
$pets.Cat = 'Frisky'
$pets.Dog = 'Spot'
$pets.Fish = 'Nimo'
$pets.Hamster = 'Whiskers'
Removing Items from a Hash Table $pets.Remove('Hamster')
The Format-Table cmdlet formats hash table output as a table. $pets | Format-Table
The Format-List cmdlet formats hash table output as a list of separate key-value pairs.
$pets | Format-List

9. Functions

# The Get-Time function returns the current time.
function Get-Time()
    return Get-Date -DisplayHint Time
function Get-Square($value)
  $result = $value * $value
  return $result
$value = Read-Host 'Enter a value'
$result = Get-Square $value
Write-Output "$value * $value = $result"
By default, PowerShell arguments are passed by value.
PowerShell arguments may be passed by reference using the Ref keyword.
The $args array variable may be used to access a variable length parameter list.
function Get-Args()
    foreach($arg in $args)
Get-Args 1 2 3 4
By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
You can use a scope modifier to change the scope of a variable.
$x = 1
$script:x = 2

11. File System

Copy-Item -Path 'C:\PSTest\Test2.txt' -Destination 'C:\PSTest\Test.txt'
The Set-Content cmdlet is a string-processing cmdlet that writes or replaces the content in the specified item, such as a file.
The Add-Content cmdlet appends content to a specified item or file.
The Clear-Content cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item.

13. Systems Management

The Get-WmiObject cmdlet gets instances of WMI classes or information about the available WMI classes. Get-WmiObject -List
The Win32_BIOS WMI class represents the attributes of the computer system's basic input/output services (BIOS) that are installed on a computer. Get-WmiObject -Class Win32_BIOS
The Win32_ComputerSystem class represents a computer system operating in a Windows environment.
Get-WmiObject -Class Win32_ComputerSystem

The Win32_NetworkAdapterConfiguration class represents the attributes and behaviors of a network adapter. Get-WmiObject -Class Win32_NetworkAdapterConfiguration

The Get-Member cmdlet gets the members (properties and methods) of objects.
Get-WmiObject -Class Win32_BIOS | Get-Member

14. Event Logs

The Get-EventLog cmdlet gets events and event logs on local and remote computers. Get-EventLog works only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.
Get-EventLog -LogName System -EntryType Error -After (Get-Date).AddDays(-30)

The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the Windows Event Log technology introduced in Windows Vista.

Get-WinEvent -FilterHashTable @{LogName='System'; Level=2; StartTime=(Get-Date).AddDays(-30)}
microsoft.txt · Last modified: 2016/10/05 10:44 (external edit)