homepage
Open menu
Go one level top
  • Train and Certify
    Train and Certify

    Immediately apply the skills and techniques learned in SANS courses, ranges, and summits

    • Overview
    • Courses
      • Overview
      • Full Course List
      • By Focus Areas
        • Cloud Security
        • Cyber Defense
        • Cybersecurity and IT Essentials
        • DFIR
        • Industrial Control Systems
        • Offensive Operations
        • Management, Legal, and Audit
      • By Skill Levels
        • New to Cyber
        • Essentials
        • Advanced
        • Expert
      • Training Formats
        • OnDemand
        • In-Person
        • Live Online
      • Course Demos
    • Training Roadmaps
      • Skills Roadmap
      • Focus Area Job Roles
        • Cyber Defence Job Roles
        • Offensive Operations Job Roles
        • DFIR Job Roles
        • Cloud Job Roles
        • ICS Job Roles
        • Leadership Job Roles
      • NICE Framework
        • Security Provisionals
        • Operate and Maintain
        • Oversee and Govern
        • Protect and Defend
        • Analyze
        • Collect and Operate
        • Investigate
        • Industrial Control Systems
    • GIAC Certifications
    • Training Events & Summits
      • Events Overview
      • Event Locations
        • Asia
        • Australia & New Zealand
        • Latin America
        • Mainland Europe
        • Middle East & Africa
        • Scandinavia
        • United Kingdom & Ireland
        • United States & Canada
      • Summits
    • OnDemand
    • Get Started in Cyber
      • Overview
      • Degree and Certificate Programs
      • Scholarships
    • Cyber Ranges
  • Manage Your Team
    Manage Your Team

    Build a world-class cyber team with our workforce development programs

    • Overview
    • Why Work with SANS
    • Group Purchasing
    • Build Your Team
      • Team Development
      • Assessments
      • Private Training
      • Hire Cyber Professionals
      • By Industry
        • Health Care
        • Industrial Control Systems Security
        • Military
    • Leadership Training
  • Security Awareness
    Security Awareness

    Increase your staff’s cyber awareness, help them change their behaviors, and reduce your organizational risk

    • Overview
    • Products & Services
      • Security Awareness Training
        • EndUser Training
        • Phishing Platform
      • Specialized
        • Developer Training
        • ICS Engineer Training
        • NERC CIP Training
        • IT Administrator
      • Risk Assessments
        • Knowledge Assessment
        • Culture Assessment
        • Behavioral Risk Assessment
    • OUCH! Newsletter
    • Career Development
      • Overview
      • Training & Courses
      • Professional Credential
    • Blog
    • Partners
    • Reports & Case Studies
  • Resources
    Resources

    Enhance your skills with access to thousands of free resources, 150+ instructor-developed tools, and the latest cybersecurity news and analysis

    • Overview
    • Webcasts
    • Free Cybersecurity Events
      • Free Events Overview
      • Summits
      • Solutions Forums
      • Community Nights
    • Content
      • Newsletters
        • NewsBites
        • @RISK
        • OUCH! Newsletter
      • Blog
      • Podcasts
      • Summit Presentations
      • Posters & Cheat Sheets
    • Research
      • White Papers
      • Security Policies
    • Tools
    • Focus Areas
      • Cyber Defense
      • Cloud Security
      • Digital Forensics & Incident Response
      • Industrial Control Systems
      • Cyber Security Leadership
      • Offensive Operations
  • Get Involved
    Get Involved

    Help keep the cyber community one step ahead of threats. Join the SANS community or begin your journey of becoming a SANS Certified Instructor today.

    • Overview
    • Join the Community
    • Work Study
    • Teach for SANS
    • CISO Network
    • Partnerships
    • Sponsorship Opportunities
  • About
    About

    Learn more about how SANS empowers and educates current and future cybersecurity practitioners with knowledge and skills

    • SANS
      • Overview
      • Our Founder
      • Awards
    • Instructors
      • Our Instructors
      • Full Instructor List
    • Mission
      • Our Mission
      • Diversity
      • Scholarships
    • Contact
      • Contact Customer Service
      • Contact Sales
      • Press & Media Enquiries
    • Frequent Asked Questions
    • Customer Reviews
    • Press
    • Careers
  • Contact Sales
  • SANS Sites
    • GIAC Security Certifications
    • Internet Storm Center
    • SANS Technology Institute
    • Security Awareness Training
  • Search
  • Log In
  • Join
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. Month of PowerShell - PowerShell Version of Keeper (Save Useful Command Lines)
370x370_Joshua-Wright.jpg
Joshua Wright

Month of PowerShell - PowerShell Version of Keeper (Save Useful Command Lines)

Let's build a useful PowerShell function to save useful commands for later reference: Save-Keeper!

July 26, 2022

#monthofpowershell

My why did we pick a month with 31 days co-conspirator for the Month of PowerShell Mick Douglas offered up a quick Bash function a while back called keeper():

keeper() {
    fc -ln | tail -n 1 >> ~/.keeper.txt
}

I added it to my .bash_profile script, and whenever I'm particularly pleased with a Bash command that I want to save for future reference, I run keeper:

PrintExport-5x7 $ ls
Crop-5x7-DSC_4745.jpg    Crop-5x7-DSC_4947.jpg    Crop-5x7-DSC_5043.jpg    Crop-5x7-DSC_5296.jpg
Crop-5x7-DSC_4791.jpg    Crop-5x7-DSC_4973.jpg    Crop-5x7-DSC_5187.jpg    Crop-5x7-DSC_5312.jpg
Crop-5x7-DSC_4830.jpg    Crop-5x7-DSC_5035.jpg    Crop-5x7-DSC_5217.jpg
PrintExport-5x7 $ for image in *.jpg; do newimagename=${image#Crop-5x7-}; echo "Renaming $image to mv $newimagename" ; mv $image $newimagename; done
Renaming Crop-5x7-DSC_4745.jpg to mv DSC_4745.jpg
Renaming Crop-5x7-DSC_4791.jpg to mv DSC_4791.jpg
Renaming Crop-5x7-DSC_4830.jpg to mv DSC_4830.jpg
Renaming Crop-5x7-DSC_4947.jpg to mv DSC_4947.jpg
Renaming Crop-5x7-DSC_4973.jpg to mv DSC_4973.jpg
Renaming Crop-5x7-DSC_5035.jpg to mv DSC_5035.jpg
Renaming Crop-5x7-DSC_5043.jpg to mv DSC_5043.jpg
Renaming Crop-5x7-DSC_5187.jpg to mv DSC_5187.jpg
Renaming Crop-5x7-DSC_5217.jpg to mv DSC_5217.jpg
Renaming Crop-5x7-DSC_5296.jpg to mv DSC_5296.jpg
Renaming Crop-5x7-DSC_5312.jpg to mv DSC_5312.jpg
PrintExport-5x7 $ keeper
PrintExport-5x7 $ tail -1 ~/.keeper.txt
    for image in *.jpg; do newimagename=${image#Crop-5x7-}; echo "Renaming $image to mv $newimagename" ; mv $image $newimagename; done

Forgive me for my use of Bash here during the Month of PowerShell; it is only for illustrative purposes. 🥸

In this Bash example, I used a for loop to rename a bunch of files, removing the Crop-5x7- beginning of the file name using the Bash shell parameter expansion feature {image#Crop-5x7-}. Then, because I was pretty pleased with myself, I ran keeper to save that command to ~/.keeper.txt so I could reference and reuse it later.

Let's create this for PowerShell!

We can use Get-History to see a list of commands that we ran in the current session:

PS C:\Users\Sec504> Get-History

  Id CommandLine
  -- -----------
   1 Get-WmiObject -Class Win32_Product
   2 $InstalledSoftware = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion...
   3 foreach($obj in $InstalledSoftware){write-host $obj.GetValue('DisplayName') -NoNewl...
   4 $InstalledSoftware = (Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersio...
   5 $InstalledSoftware = (Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersio...
   6 $InstalledSoftware = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion...
   7 ForEach-Object ($obj in $InstalledSoftware){ Write-Host $obj.GetValue('DisplayName'...
   8 foreach ($obj in $InstalledSoftware){ Write-Host $obj.GetValue('DisplayName') -NoNe...

The parameter CommandLine is what we want, and can use Select-Object -Last 1 to retrieve the last command:

PS C:\Users\Sec504> Get-History | Select-Object -Last 1 -Property CommandLine

CommandLine
-----------
foreach ($obj in $InstalledSoftware){ Write-Host $obj.GetValue('DisplayName') -NoNewline...

Perfect! Now, just add the Out-File to save to ~/keeper.txt (I'm recalling the previous foreach command before running Get-History for consistency in examples):

PS C:\Users\Sec504> Get-History | Select-Object -Last 1 -ExpandProperty CommandLine | Out-File -Append ~/keeper.txt
PS C:\Users\Sec504> Get-Content C:\Users\Sec504\keeper.txt
foreach ($obj in $InstalledSoftware){ Write-Host $obj.GetValue('DisplayName') -NoNewline; Write-Host " - " -NoNewline; Write-Host $obj.GetValue('DisplayVersion') }
PS C:\Users\Sec504>

A couple of things to point out here:

  • I used ExpandProperty instead of just Property with Select-Object; this allows us to get the CommandLine by itself without the accompanying header line
  • It's necessary to add -Append to the Out-File command to keep adding to the file; by default, Out-File will overwrite the specified file

Next, all that is needed is to add this as a function to the PowerShell profile:

PS C:\Users\Sec504> notepad $profile
PS C:\Users\Sec504>

To keep with the Verb-Noun convention, I called this Save-Keeper:

Notepad window showing PowerShell profile with highlighted function Save-Keeper.

Here is the function to copy-paste into your PowerShell profile.

Function Save-Keeper() {
    Get-History | Select-Object -Last 1 -ExpandProperty CommandLine | Out-File -Append ~/keeper.txt
}

Then you can close and open a new PowerShell session, or reload your PowerShell profile:

PS C:\Users\Sec504> . $profile

Let's put this new function to use. I want to build a list of installed software on Windows by enumerating the software uninstall keys for HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE. First, identify the keys using Get-ChildItem in the variable $InstalledSoftware:

PS C:\Users\Sec504> $InstalledSoftware = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall", "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
PS C:\Users\Sec504> Save-Keeper
PS C:\Users\Sec504>

Next, get the DisplayName and DisplayVersion elements for each key:

PS C:\Users\Sec504> foreach ($obj in $InstalledSoftware){ Write-Host $obj.GetValue('DisplayName') -NoNewline; Write-Host " - " -NoNewline; Write-Host $obj.GetValue('DisplayVersion') }
7-Zip 19.00 (x64) - 19.00
 -
 -
 -
 -
Git version 2.21.0 - 2.21.0
 -
 -
 -
 -
 -
Process Hacker 2.39 (r124) - 2.39.0.124
Rekall v1.6.0 Gotthard -
 -
USBPcap 1.1.0.0-g794bf26-5 - 1.1.0.0-g794bf26-5
 -
Update for Windows 10 for x64-based Systems (KB4480730) - 2.55.0.0
Update for Windows 10 for x64-based Systems (KB4023057) - 2.67.0.0
OpenCL™ runtime for Intel® Core™ and Xeon® Processors - 6.4.0.25
Microsoft Visual C++ 2013 x64 Additional Runtime - 12.0.40649 - 12.0.40649
Java 8 Update 111 (64-bit) - 8.0.1110.14
PowerShell 7-x64 - 7.2.3.0
Microsoft Visual C++ 2008 Redistributable - x64 9.0.30729.6161 - 9.0.30729.6161
Java SE Development Kit 8 Update 111 (64-bit) - 8.0.1110.14
Microsoft Update Health Tools - 3.67.0.0
Microsoft Visual C++ 2019 X64 Minimum Runtime - 14.24.28127 - 14.24.28127
Microsoft Visual C++ 2019 X64 Additional Runtime - 14.24.28127 - 14.24.28127
Microsoft Visual C++ 2013 x64 Minimum Runtime - 12.0.40649 - 12.0.40649
VMware Tools - 11.0.6.15940789
PS C:\Users\Sec504> Save-Keeper

By running Save-Keeper after the commands, I can stash those commands in my keeper.txt file:

PS C:\Users\Sec504> Get-Content C:\Users\Sec504\keeper.txt
...
$InstalledSoftware = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall", "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
foreach ($obj in $InstalledSoftware){ Write-Host $obj.GetValue('DisplayName') -NoNewline; Write-Host " - " -NoNewline; Write-Host $obj.GetValue('DisplayVersion') }

This works great, and I'll be sure to use it immediately after interesting commands to populate the keeper.txt file with interesting tidbits.

Consider extending the Save-Keeper function on your own to add some more features:

  • Record the date and time in the keeper.txt file
  • Get a few additional lines of context before the keeper using Select-Object -Last 3
  • Save the user name, computer name, and current directory for each saved command
  • Accept an optional argument to Save-Keeper for a description of the command, or maybe a URL to remember where the inspiration for a command came from

If you add these (or more) features to Save-Keeper, let me know! Tag me @joswr1ght or #MonthOfPowerShell in your tweet, DM me, or email me! Thanks!

-Joshua Wright

Return to Getting Started With PowerShell


Joshua Wright is the author of SANS SEC504: Hacker Tools, Techniques, and Incident Handling, a faculty fellow for the SANS Institute, and a senior technical director at Counter Hack.

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Recommended Training

  • SEC660: Advanced Penetration Testing, Exploit Writing, and Ethical Hacking
  • SEC580: Metasploit for Enterprise Penetration Testing
  • SEC511: Continuous Monitoring and Security Operations

Tags:
  • Cyber Defense
  • Cybersecurity and IT Essentials
  • Penetration Testing and Red Teaming

Related Content

Blog
CD_Blog_HowtoautomateinAzure_Part1_2.jpg
Cyber Defense, Cloud Security
October 11, 2022
How to Automate in Azure Using PowerShell - Part 1
In this post, we’ll cover how to automate the assessment and reporting of your cloud security configuration opportunities.
370x370_josh-johnson.jpg
Josh Johnson
read more
Blog
powershell_option_340x340.jpg
Cybersecurity and IT Essentials, Cyber Defense, Penetration Testing and Red Teaming
August 4, 2022
Month of PowerShell - Discoveries from the Month of PowerShell
A final wrap-up from the Month of PowerShell: discoveries, recommendations, complaints, and successes.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
Blog
powershell_option_340x340.jpg
Cybersecurity and IT Essentials, Cyber Defense, Penetration Testing and Red Teaming
July 31, 2022
Month of PowerShell - Keyboard Shortcuts Like a Boss
Let's look at several keyboard shortcuts to speed up your PowerShell sessions.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters & Cheat Sheets
  • White Papers
  • Focus Areas
  • Cyber Defense
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • © 2023 SANS™ Institute
  • Privacy Policy
  • Contact
  • Careers
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn