Windows PowerShell

A collection of Windows PowerShell resources

Execution Policy

This command sets the PowerShell execution policy.

If you encounter an error such as …

{script path} cannot be loaded.
The file {script path} is not digitally signed.
You cannot run this script on the current system.
For more information about running scripts and setting execution policy,
see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.

You can set a Bypass execution policy for the current session.

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Menu Example

This PowerShell script contains a menu to execute various tasks using functions.

UtilityMenuExample.ps1
function ListProcess
{
    Get-Process | Group-Object Company | Sort-Object Count -Descending
}

function ListEnvVars
{
    Get-ChildItem env:
}

function ListEventLog
{
    Get-EventLog -List
}

function Cleanup
{
    Write-Host "Delete files from $env:temp older than 24 hours"
    Get-ChildItem -path $env:temp | where {$_.Lastwritetime -lt (date).addhours(-24)} | remove-item
    <# Clear-RecycleBin #>
    $Shell = New-Object -ComObject Shell.Application
    $RecBin = $Shell.Namespace(0xA)
    $RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}
}

function ShowMenu
{
     param (
           [string]$Title = 'Menu'
     )
     Write-Host "====== $env:USERPROFILE - $Title ======="

     Write-Host "1: List Running Processes"
     Write-Host "2: List Environment Variables"
     Write-Host "3: List Event Log"
     Write-Host "4: Clean Temp and Recycle Bin"
     Write-Host "q: quit"
}

do
{
     ShowMenu
     $input = Read-Host "Please make a selection"
     switch ($input)
     {
        '1' {
            Clear-Host
            ListProcess
        }
        '2' {
            Clear-Host
            ListEnvVars
        }
        '3' {
            Clear-Host
            ListEventLog
        }
        '4' {
            Clear-Host
            Cleanup
        }
        'q' {
            return
        }
     }
     pause
}
until ($input -eq 'q')

Compress-Archive

This example creates a zip file of the Documents folder with a datetime string in the zip filename.

Compress-Archive "$env:USERPROFILE\Documents" "$env:USERPROFILE\Documents_$(get-date -f yyyyMMdd'T'HHmmss).zip"

Resources

Cygwin Oh My ZSH Recipe

This post documents my Cygwin + Oh My ZSH configuration which gives me a consistent cross platform terminal experience on Windows, OS X and Linux.

Web development workflow with git, node, npm, docker, vagrant, etc. is more comfortable when using the same familiar bash shell interface across different operating systems.

I don't always use the command line in Windows - But when I do, I prefer Cygwin

Install Cygwin

I used these settings with the Cygwin for 64-bit versions of Windows.

    Cygwin Setup

  1. Choose A Download Source: Install from Internet
  2. Select Root Install Directory: C:\Cygwin
    Install For All Users
  3. Select Local Package Directory: C:\Users\{UserName}\AppData\Local\Cygwin
    note: if your %userprofile% contains spaces, for example: C:\Users\Jared Dunn, this may cause issues.
  4. Select Your Internet Connection: Direct Connection
  5. Choose A Download Site: http://mirrors.xmission.com
    This mirror was reliable for me. They should generally all be up to date. It is recommended that you select a mirror site that is closest to you. Visit the Cygwin Mirror Sites page for more information.
  6. Select Packages:
    • curl: Muti-protocol file transfer tool
    • fzf-zsh: fzf key bindings for Z shell
    • fzf-zsh-completion: fzf completion for Z shell
    • git: Distributed version control system
    • gitk: Git repository browser
    • zsh: The Z-Shell

Configure Cygwin Home Directory

Make your Cygwin home directory the same as your Windows User profile.

Edit the Cygwin /etc/nsswitch.conf file.

Add or edit the following line: db_home: /%H

more info: Stack Overflow – How can I change my Cygwin home folder after installation?

Install Oh My ZSH

Launch Cygwin and install Oh My ZSH using curl

sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

I received this output while Oh My ZSH install completed:

Looking for an existing zsh config...
Using the Oh My Zsh template file and adding it to ~/.zshrc
Copying your current PATH and adding it to the end of ~/.zshrc for you.
I can't change your shell automatically because this system does not have chsh.
Please manually change your default shell to zsh!

Edit the Cygwin /etc/nsswitch.conf file.

Add or edit the following line: db_shell: /bin/zsh

More info: Stack Overflow – Set Default Shell in Cygwin

Mintty Configuration

This section documents some additional personalization preferences. Access the options by selecting the Cygwin application icon in the Title bar. For Looks, I have medium transparency selected.

Cygwin - Options - Looks
Options – Looks

For text, I have the Fira Code fonts installed on my system so have elected to use them and since my display is UHD, I am using the retina version. I have also set the font smoothing to full which is equivalent to subpixel anti-aliasing (“ClearType”).

Cygwin - Options - Text
Options – Text

Lastly, I wanted to add some spacing between the window borders and command text. I discovered that this could be done by editing the mintty configuration file in my home directory. I added the following line to the file, Padding=16. The entire configuration file is shown below.

~/.minttyrc
BoldAsFont=-1
Columns=96
Rows=48
Transparency=medium
Padding=16
Font=Fira Code Retina
FontWeight=450
FontSmoothing=full

Test drive using this handy cal 2017 command to display a calendar.

cal 2017

Resources

Laravel Install on Windows IIS

This post documents installing PHP 7, PHP Manager and Laravel 5.3 on Internet Information Services (IIS) Manager version 10 which ships with Windows 10 Pro. This Laravel Installation will also be configured to connect to a SQLite database.

Internet Information Services (IIS) Manager

IIS needs to be installed, open the Windows Features dialog to check the installation. One way to do this is by selecting the start button and type Windows Features to bring up a list where “Turn Windows features on or off” can be selected. Another way to get to this Control Panel app is Windows + R key combination and run appwiz.cpl. Turn Windows features on or off link should be in the upper left panel.

Windows Features - IIS and .NET Framework 3.5 enabled
Windows Features

Notice that under .NET Framework 3.5 that both Windows Communication Foundation features are enabled. This may be needed in order for a successful install of PHP Manager. Installation of PHP Manager for IIS requires .NET 3.5 to work properly.

PHP and PHP Manager

Install PHP 7 for Windows using the Microsoft Web Platform Installer. It’s an easy way to get both PHP and the PHP Manager installed and takes some of the guess work out of getting PHP up and running on Windows and IIS.

  • If PHP Manager Fails to install after confirming that .NET 3.5 is installed and enabled, this is likely due to the installer throwing an error when checking the IIS version. Change the W3SVC MajorVersion value to 7 (decimal) in the registry. After the install is completed, change the value back to 10. More info is available at the PHP Manager – Refuses to install for WTP10 view issue page.
Registry Editor - HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters]

* YMMV, I am not responsible if you hose your system when editing the registry.

PHP Extensions

In the Internet Information Services (IIS) Manager, Open PHP Manager and select the Enable or disable an extension link. Ensure that the extensions needed for Laravel are enabled. If you want to be able to connect to a SQLite database, enable the php_sqlite3.dll PHP extension. The figure below shows the PHP extensions I have enabled for a working Laravel 5 installation.

PHP Extensions provide additional functionality to PHP runtime, such as database connectivity, caching, debugging and others. Use this feature to enable or disable PHP extensions and to configure PHP extensions settings.
PHP Manager – PHP Extensions

Composer for Windows

Download and run Composer-Setup.exe Windows Installer. The installer will download Composer and set up the PATH environment variable.

Using the Windows Command Prompt, make sure Composer for Windows is installed by running the composer –version command.

composer --version

Git for Windows

Git for Windows is needed so Composer for Windows can download packages. During the installation process, Adjusting your PATH environment, make sure the option, Use Git from the Windows Command Prompt is enabled.

Using the Windows Command Prompt, make sure Git for Windows is installed by running the git –version command.

git --version

Create Laravel Project

Bring up the Adminstrator Command Prompt. One way to do this is by selecting the start button and type command to bring up a list where “Command Prompt” can be selected. Right click on Command Prompt and select Run as administrator
.

cd c:/intepub

composer create-project laravel/laravel laravel "5.3.*"

Add Website

Open Internet Information Services (IIS) Manager. Right click on the server and select Add Website. Fill out the form as follows:
Site name: Laravel
Application pool: DefaultAppPool
Physical path: C:\inetpub\laravel\public
Host name: laravel.win

Select “Test Settings” and then “OK” if successful.

Add Website
IIS – Add Website

Hosts Mapping

Since the Host name laravel.win was entered for the website, the hosts file needs to be updated. Open Notepad as an administrator. One way to do this is by selecting the start button and type Notepad to bring up a list where it can be selected. Right click on Notepad and select Run as administrator.

Select File | Open, or Ctrl + O and change the File type from Text Documents (*.txt) to All Files (*.*). Browse to C:\Windows\System32\drivers\etc and select the hosts file. Add an entry to map localhost to laravel.win as follows.

hosts
127.0.0.1   localhost
127.0.0.1   laravel.win

Laravel Storage Permissions

In File Explorer, right click on the storage folder in C:\inetpub\laravel and select Properties. Under the Security tab, grant full control of the storage folder to IUSR as shown in the figure below.

Properties Dialog - Security
Permissions for storage
Laravel web.config

Since IIS does not have an .htaccess file like Apache, create a web.config file in C:\inetpub\laravel\public as follows. *

web.config
<configuration>
    <system.webServer>
        <defaultDocument>
            <files>
                <clear />
                <add value="index.php" />
                <add value="default.aspx" />
                <add value="Default.htm" />
                <add value="Default.asp" />
                <add value="index.htm" />
                <add value="index.html" />
            </files>
        </defaultDocument>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)/$" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Redirect" redirectType="Permanent" url="/{R:1}" />
                </rule>
                <rule name="Imported Rule 2" stopProcessing="true">
                    <match url="^" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
        <httpErrors errorMode="Detailed" />
    </system.webServer>
</configuration>

* The rewrite rule definitions in the web.config require the URL Rewite 2.0 extension. For easy installation, use the Free Web Platform Installer.

Laravel SQLite Database

Create a SQLite database * in C:\inetpub\laravel\database. Edit C:\inetpub\laravel\.env database values to configure the database connection.

.env
DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database/laravel.sqlite
DB_USERNAME=
DB_PASSWORD=

* DB Browser for SQLite is an open source, freeware tool used to create, design and edit SQLite database files.

Restart IIS

In an Administrative Command Prompt, restart IIS so all of the changes get applied.

iisreset /restart

In IIS, make sure that the Larvel web site has been started. If the W3SVC service is not running, it can be started with the following command.

net start w3svc

Once all is said and done, load http://laravel.win in a web browser. Laravel 5.3 default page should look similar to the screen shot below.

Laravel 5.3 Default Screen
Laravel 5.3

Installing Laravel on XAMPP

This post documents how to install Laravel locally using XAMPP. When you are developing with Laravel on an older computer or one with limited resources, using XAMPP for your local PHP and MySQL development server works well on Windows.

Laravel PHP Requirements

This table shows the minimum PHP version requirements for the latest versions of Laravel.

Laravel PHP
5.3 5.6.4
5.1, 5.2 5.5.9
5.0 * 5.4

* PHP 7 not supported in this version

Head over to the Apache Freinds site to download the version of XAMPP that meets the minimum PHP requirements for the version of Laravel you are supporting. If you are developing in Laravel 5.2 currently and also want to be able to support Laravel 5.3, get the XAMPP version that includes PHP 7.

For Windows, I have xampp installed at the root directory on C:\ drive. here is the virtual hosts configuration I am using for Laravel. More information for setting up XAMPP on Windows.

httpd-vhosts.conf
<VirtualHost *:8080>
    DocumentRoot "C:/xampp/htdocs/laravel/public"
    ServerName laravel.dev
    ServerAlias www.laravel.dev
    SetEnv APPLICATION_ENV development
    <Directory "C:/xampp/htdocs/laravel">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Edit C:\Windows\System32\drivers\etc\hosts file, mapping laravel.dev hostname to 127.0.0.1 localhost IP address.

hosts
127.0.0.1   laravel.dev

Install Laravel

This example will install laravel 5.2 into C:/xampp/htdocs/laravel using Composer. Use the create-project command and the laravel/laravel package name followed by the directory to create the project in. The optional third argument is for a version number.

cd c:/xampp/htdocs

composer create-project laravel/laravel laravel "5.2.*"

Clink Gives CMD.exe Unix Shell Bash Features

Finally, I can use the Windows Command Prompt like Unix thanks to Clink. This CMD.exe extension adds the powerful Unix Bash-style functionality of the GNU Readline library to the Windows command line. If you are a Microsoft PowerShell user, there is also a PSReadLine module available for it. My favorite bash shell for Windows is Cygwin + ZSH + Oh My ZSH.

Command Prompt with Clink
Command Prompt with Clink
Update: March 30, 2016

Bash will be built into the Windows 10 Anniversary update

Windows Command Prompt Tricks

Use either explorer . or start . to open an Explorer window from the current directory.

explorer .

start .

List directory structure. Use the > redirection operator to print the tree structure into a text file.

tree | more

tree /a > c:\tree.txt
  • F1: Pastes the last executed command (character by character)
  • F2: Pastes the last executed command (up to the entered character)
  • F3: Pastes the last executed command
  • F4: Deletes current prompt text up to the entered character
  • F5: Pastes recently executed commands (does not cycle)
  • F6: Pastes ^Z to the prompt
  • F7: Displays a selectable list of previously executed commands
  • F8: Pastes recently executed commands (cycles)
  • F9: Asks for the number of the command from the F7 list to paste

Git for Windows

Git for Windows includes a Bash shell emulator built with MinGW-w64 and MSYS2. Browse the Git for Windows source code repositories.


Cygwin + ZSH + Oh My ZSH

CYGWIN + ZSH + Oh My ZSH
Cygwin + ZSH + Oh My ZSH

This is also a great Windows bash shell solution to give you the power of Unix. After launching Cygwin setup and installing git and zsh, install Oh My ZSH. For more info, see my Cygwin Oh My ZSH Recipe.

Want More?! › ConEmu

ConEmu can be used with any other console application. To add Cygwin + ZSH + Oh My ZSH to ConEmu,
Open ConEmu Settings:

  1. Under Startup › Tasks
  2. Under Predefined tasks,
    Select {Bash::CygWin bash}
  3. Locate the Commands input and Copy the text. For example,

    set CHERE_INVOKING=1 & %ConEmuDrive%\Users
    \admin\Cygwin\bin\sh.exe --login -i -
    new_console:C:"%ConEmuDrive%\Users\admin\Cygwin
    \Cygwin.ico"
    

  4. Select the + sign button to create a new command group task.
  5. Rename the new command group,
    Bash::CygWin zsh
  6. Paste in the Commands input text copied from Bash::CygWin bash command group in step 3.
  7. Replace sh.exe with zsh.exe. For example,

    set CHERE_INVOKING=1 & %ConEmuDrive%\Users
    \admin\Cygwin\bin\zsh.exe --login -i -
    new_console:C:"%ConEmuDrive%\Users\admin\Cygwin
    \Cygwin.ico"
    

Update: August 18, 2016

Bash on Ubuntu on Windows 10 in ConEmu

After installing Oh My ZSH to Bash on Ubuntu on Windows, launch it within ConEmu to make it even better. It is defined as Bash::bash under tasks.

Command Prompt with Clink
ConEmu Settings – Tasks
%windir%\system32\bash.exe -cur_console:p

More info,
ConEmu – Using Bash on Windows


Microsoft PowerShell

Another command line option is available when using the Microsoft PowerShell task automation and configuration management framework from Microsoft. PowerShell provides access to WMI, COM and the .NET object model in an interactive and scriptable command line environment. Learning PowerShell is made easier by using its console-based help, like man pages in Unix shells, with the Get-Help Cmdlet. Help contents can be downloaded using the Update-Help Cmdlet. Context help is available with the -online switch to Get-Help.

PowerShell Resources

Code Editors


Atom is a free open-source “hackable” text and code editor developed by GitHub.
Configure Atom for JavaScript and Web Development


Brackets is a a modern, open source text editor that understands web design. TIP: if you are fairly new to markdown and/or would like a live preview while you edit, checkout this Markdown Preview plugin for Brackets.


Sublime Text is a fast, stable editor with a huge number of features and plugins termed packages.


Visual Studio Code is a free code editor from Microsoft and is available for Linux, Mac OSX, and Windows. This editor has a growing community and new features with each release. One feature I recently discovered is the live markdown preview, Ctrl+Shift+V.

Configuration Considerations

If you’re running under Windows and work with Git, create and edit shell scripts, etc., you may want to consider setting the default line endings to Unix instead of Windows.

Line Endings
Windows CR LF
Unix LF

The Windows version of Sublime Text 3 is set to use Windows line endings by default. You can set Unix as the default in Sublime Text 3 as follows:

  1. From the Menu, select Preferences (alt + n)
  2. Select Settings – User
  3. Add the following to the Preferences.sublime-settings file *

    {
        "default_line_ending": "unix"
    }
    

* If there are pre-existing settings in the Preferences.sublime-settings file, the curly braces are not needed since they already surround the settings. The Sublime Text settings files are in json format.

TIP: Convert line endings from Windows to Unix with the dos2unix command using Cygwin, a Unix like command-line interface for Windows.

# find all files inside current directory
# and execute dos2unix on them
$ find . -type f -exec dos2unix {} \;

Further reading, I like Jeff Atwood’s blog post from 2010, The Great Newline Schism.

Line Ending Plugins

Sublime Text comes with all the tools for handling line endings built in. What about the others?

Atom – As of version 1.0.8 you can change the default line endings for new files. Select File | Settings | Packages | Core Packages | line-ending-selector. Select Settings, Default line ending setting. You can also convert line endings for an open file selecting LF or CRLF at the bottom right hand corner status area.

Brackets – An extension to convert line endings may be needed. The brackets-newline extension worked for me. The default line endings adjusts to the OS it’s running on. There doesn’t seem to be a way to set default line endings for new files.

Visual Studio Code – Use an .editorconfig file and the respective EditorConfig for VS Code extension. Line endings can be converted by selecting LF or CRLF at the bottom right hand corner status area. Like Brackets, the default line endings adjusts to the OS it’s running on and there doesn’t seem to be a way to set default line endings in the core settings.

Sublime Text

Settings

For those of you that are interested and for my own records, my Sublime Text settings file. The Fira Code fonts are a great addition to a developer work station.

User/Preferences.sublime-settings
{
    "caret_style": "phase",
    "color_scheme": "Packages/Colorsublime-Themes/Facebook.tmTheme",
    "detect_indentation": false,
    "detect_slow_plugins": false,
    "fade_fold_buttons": false,
    "font_face": "Fira Code",
    "font_size": 14,
    "highlight_line": true,
    "ignored_packages":
    [
        "Vintage"
    ],
    "line_padding_bottom": 3,
    "line_padding_top": 3,
    "tab_size": 4,
    "theme": "Material-Theme.sublime-theme",
    "trim_trailing_white_space_on_save": true,
    "use_tab_stops": true
}

I have also modified the Facebook.tmTheme file so the background color matches the sidebar.

Packages/Colorsublime – Themes/Facebook.tmTheme

    <key>background</key>
    <string>#263238</string>

Packages

Emmet toolkit for web-developers. Usage cheat-sheet

HTML-CSS-JS Prettify — HTML, CSS, JavaScript and JSON code formatter for Sublime Text 2 and 3.

Resources

Compass on Windows

This post documents my latest compass install on Windows which should be simple enough. I ran into a minor issue and was getting an error:

$ gem install compass
ERROR:  Error installing compass:
        The 'ffi' native gem requires installed build tools.

How to install the build tools

Go to the same place that has the RubyInstaller for Windows, http://rubyinstaller.org and select Downloads. Download the Development Kit (build tools) that corresponds with your version of Ruby. If you need to install Ruby (required), it is recommended that you use the Ruby 1.9.3 installers. I noticed that a newer version of the Ruby 1.9.3 installers were available, might as well get the updates. To summarize, here are the two packages I downloaded for my Windows 8.1 machine:

Install or update Ruby using the Ruby 1.9.3-p550 RubyInstallers before installing the DevKit. Check your installed version as follows:

C:\>ruby --version
ruby 1.9.3p550 (2014-10-27) [i386-mingw32]

Important – during Ruby Setup, make sure “Add Ruby executables to your PATH.” is selected:

Setup - RubyInstallers
Setup – Ruby 1.9.3

After extracting the DevKit to C:\RubyDevKit, run these these commands:

C:\RubyDevKit>devkitvars.bat
Adding the DevKit to PATH...

C:\RubyDevKit>ruby dk.rb init
[INFO] found RubyInstaller v1.9.3 at C:/Ruby193

Initialization complete! Please review and modify the auto-generated
'config.yml' file to ensure it contains the root directories to all
of the installed Rubies you want enhanced by the DevKit.

C:\RubyDevKit>ruby dk.rb install
[INFO] Updating convenience notice gem override for 'C:/Ruby193'
[INFO] Installing 'C:/Ruby193/lib/ruby/site_ruby/devkit.rb'
Test the DevKit install
C:\RubyDevKit>bash
bash-3.1$ gcc --version
gcc.exe (tdm-1) 4.5.2
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

bash-3.1$ exit
exit

Install Compass

$ gem install compass
Temporarily enhancing PATH to include DevKit...
Building native extensions.  This could take a while...
Fetching: rb-inotify-0.9.5.gem (100%)
Fetching: compass-1.0.1.gem (100%)
    Compass is charityware. If you love it, please donate on our behalf at http:
//umdf.org/compass Thanks!
Successfully installed ffi-1.9.6
Successfully installed rb-inotify-0.9.5
Successfully installed compass-1.0.1
3 gems installed
Installing ri documentation for ffi-1.9.6...
Installing ri documentation for rb-inotify-0.9.5...
Installing ri documentation for compass-1.0.1...
Installing RDoc documentation for ffi-1.9.6...
Installing RDoc documentation for rb-inotify-0.9.5...
Installing RDoc documentation for compass-1.0.1...

Going from Windows to OS X

After twenty plus years using Microsoft and Windows dating back to DOS 6.1 and Windows 3.1, I am learning how to make the switch to OS X. One thing I had to get used to was how to bring up context menus that I would always invoke by right clicking an object in Windows. To right click in OS X on the MacBook Pro, use the Multi-Touch trackpad and tap with two fingers at once. Another was the Delete key functions the same as backspace on a PC. No Home and End keys on the Mac took some getting used to as well, command and cursor key combo’s did the trick. A majority of shortcuts can be replicated by simply replacing what was done with the Ctrl key on a PC with the command key in OS X.

Windows and OS X Keyboard Comparison

Sony VAIO FW290 Keyboard
Windows/PC Keyboard – Sony VAIO FW290
MacBook Pro Keyboard
MacBook Pro Keyboard

Here is a table of my frequently used keyboard shortcuts for each OS.

OS X Windows
Cut ⌘ command+X Ctrl+X
Copy ⌘ command+C Ctrl+C
Cycle Tabs control+tab Ctrl+Tab
Cycle Windows ⌘ command+tab Alt+Tab
Cycle Windows
Current App
⌘ command+ ~
End of Document ⌘ command+ Ctrl+End
End of Line ⌘ command+
or: control+E
End
or: Fn+
Force Quit
Applications
⌘ command+option+esc
Reload Webpage ⌘ command+R Ctrl+R
or: F5
Start of Document ⌘ command+ Ctrl+Home
Start of Line ⌘ command+
or: control+A
Home
or: Fn+
Page Down fn+ Page Down
Page Up fn+ Page Up
Paste ⌘ command+V Ctrl+V
Select Words shift+option+ Shift+Ctrl+
Show Desktop fn+F11 Win+D
Spotlight / Run ⌘ command+space Win+R
Webkit Dev Tools ⌘ command+option+I Ctrl+Shift+I
Lock Screen

After enabling the lock screen in System Preferences > Security & Privacy by checking require password after sleep or screensaver begins …

For external keyboards with an Eject key use control + shift + eject

For keyboards without an Eject key, like the MacBook Air and MacBook Pro Retina, use control + shift + power

Screen Capture, OS X

Command (⌘)-Shift-3

Take a picture of part of the screen

Command (⌘)-Shift-4, and then drag the crosshair pointer to select the area. Continue to press the mouse button, release the keys, and then press Shift, Option, or the Space bar while you drag to resize the selection area. When you are ready to take a picture, release the mouse button.

To cancel, press Escape before you release the mouse button.

Terminal

base64 files
To base64 encode a file. Typically a font or image to inline into a CSS file. Add this function into your .bash_profile.

# usage: base64 foo.png
function base64() {
openssl base64 < $1 | tr -d '\n' | pbcopy && printf "\n\e[0;31m -- base64 string copied to clipboard -- \e[0m\n"
}
Compress (ZIP) Files
# to create a zip archive of the entire folder named myproject into myproject.zip
# and exclude .DS_Store, node_modules and .git directory
# cd to the directory that has the myproject folder, then
$ zip -r myproject.zip myproject --exclude "*.DS_Store" --exclude "*.git*" --exclude "*node_modules*"
Command History

Don't search history by grepping ~/.bash_history, or repeatedly hitting the up arrow, instead use control+R - press enter to immediately run the command.

Command Line Cursor
  • Ctrl + U: Clear line
  • Ctrl + K: Clear everything after the cursor
  • Ctrl + A: Move cursor to the beginning
  • Ctrl + E: Move cursor to the end

Change Owner and/or Group
# chown USER DIR/FILE
$ sudo chown jimfrenette /usr/local

# chgrp GROUP DIR/FILE
$ sudo chgrp staff /usr/local

# chown USER:GROUP DIR/FILE
$ sudo chown jimfrenette:staff /usr/local
Disk Maintenance
$ sudo periodic daily weekly monthly
Download Files
$ curl -O http://code.jquery.com/jquery-1.10.2.min.js
Finder
# open Finder in current directory
$ open .
IP Config
# Network
$ ipconfig getifaddr en0
# wifi/2nd adapter
$ ipconfig getifaddr en1

# External
$ curl ipecho.net/plain; echo

# grep example
$ ifconfig |grep inet
Hosts File Edits
$ sudo nano /private/etc/hosts
Launch Apps
$ sudo open /Applications/FileZilla.app
Print Working Directory
$ pwd

View hidden files and folders in Finder

$ defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Finder

Hide files and folders [default]

$ defaults write com.apple.finder AppleShowAllFiles -boolean false ; killall Finder
Shutdown / Restart
# shut down immediately
$ sudo shutdown -h now
# restart immediately
$ sudo shutdown -r now
# restart in 1 minute
$ sudo shutdown -r +1
SSH

Ctrl + D to logout of SSH session

Symbolic Links - symlinks

Symbolic link files contain path metadata of the target file or directory. If you move the target file, the symlink will break. Note that ~/ will target the current users home directory. This example creates a symlink to the Photos directory in the Downloads directory.

# /target /symlink
$ ln -s ~/Dropbox/Photos ~/Downloads
Web Server

Start a simple web server at the root of any folder by navigating to the folder. This example will create a web server with a base URL http://localhost:8000

$ python -m SimpleHTTPServer 8000

If you want to use port 80, simply leave off the port number that follows the SimpleHTTPServer command. Ctrl+C to stop the server

Other Useful OS X Tips

Activity Monitor

Use Spotlight (command + spacebar) and start typing Activity Monitor, select it to monitor what is going on with your system.

Finding Files

While in Finder, select Edit > Find (command + F). Then click the plus button to the right of the search window to add a filter. Select "other" in the first drop-down menu and select "System files". Now select "System Files" which is now an available option in the first drop-down. Select "are included" in the second drop-down and enter your search term.

I find searching for text inside of files hit or miss with Finder. The free Text Wrangler app does a nice job searching for text strings within files. Select Search > Multi File Search (up arrow + command + F). For Windows, my favorite free file search utility is Agent Ransack.

URL Shortcuts

Creating a internet shortcut that can be opened in both OS X and Windows is as easy as creating a text file and saving it with the .url extension

[InternetShortcut]
URL=http://jimfrenette.com/2013/10/going-from-windows-to-os-x/
IconIndex=0

Resources

Windows 8 Shortcut Keys

I installed Windows 8 on my 2009 SONY VAIO FW series laptop today. Here are a few keyboard shortcuts I found useful.

  • Windows Key + C – Charms
  • Windows Key + D – Desktop
  • Windows Key + F – Search Files
  • Windows Key + I – Settings
  • Windows Key + K – Devices
  • Windows Key + P – Projector options
  • Windows Key + Q – Search Applications
  • Windows Key + R – Run
  • Windows Key + X – Administrator tools
  • Windows Key + Enter – Narrator

Smart Snap

  • Windows Key + Right or Left Arrow
    Moves the open window to the left or right half of the screen.

Additionally, if you are on the metro screen, and there is not a search input shown, just start typing and one will appear with your query. Tapping the Windows key will cycle you through open screens as well. The ever faithful Alt + F4 (close) and Alt + Tab (cycle windows/apps) shortcuts are indispensable… Ctrl + Tab is handy as well.