Powershell

PowerShell

Cheat Sheet

http://channel9.msdn.com/wiki/default.aspx/Channel9.WindowsPowerShellQuickStart

ShortHand

?  : where
% : foreach
$_ : current item

Get content from a file

Get-Content "c:\servers.txt" | foreach {$i}

Write to an HTML File

Get-Process | Convertto-Html -property Name,Path,Company > test.htm

Examples

Speed up powershell start up (run once per machine)

Set-Alias ngen @(dir (join-path ${env:\windir} "Microsoft.NET\Framework") ngen.exe -recurse | sort -descending lastwritetime)[0].fullName
[appdomain]::currentdomain.getassemblies() | %{ngen $_.location}

Shorten Prompt

function prompt {"PS >"}

Foreach

Foreach ($i in Get-Childitem c:\) {$i.name; $i.creationtime}

Reset File permissions

$acl = Get-Acl "c:\path"
Get-ChildItem . -Recurse | ForEach-Object { Set-Acl $_.FullName $acl }

Unhide / Hide Files

gci -r -fo | where { $_.Extension -eq ".suo" } | foreach { $_.Attributes = $_.Attributes -bxor [System.IO.FileAttributes]::Hidden}

Delete Subfolders (with WhatIf)

*note the second recurse allows subfolders of to be deleted folders to be deleted without prompting

Without Folder Check (includes hidden files)

gci . -fil *.svn -r -fo | rm -r -whatIf

With Folder Check (includes hidden files)

gci . -fil '*.svn' -r -fo | where {$_.PSIsContainer} | rm -r -fo -whatIf

Filter at where with Folder Check (includes hidden files)
gci . -recurse -force | where {$_.PSIsContainer -and $_.Extension -eq ".svn"} | remove-item -recurse -force -whatIf

Fix Line endings for notepad

[System.IO.File]::ReadAllText("desktop\MyFile.txt").Replace("value", "`r`nvalue") > newFile.txt

Download a file

$client = new-object System.Net.WebClient
$client.DownloadFile("http://www.google.com/favicon.ico","C:\Users\lexm\Desktop\favicon.ico")

Windowed Process names formatted

Get-Process |where {$_.mainWindowTItle} |format-table id,name,mainwindowtitle –AutoSize

On a remote machine:

[System.Reflection.Assembly]::LoadWithPartialName(’System.ServiceProcess’)

[System.ServiceProcess.ServiceController]::GetServices("MACHINENAME") | where{ (($_.name -match "NAME") -or
($_.displayname -match "NAME"))}

Hash table to get distinct filenames

$hash = @{}
get-childitem -recurse |where {$_.Extension -match "dll"} |foreach {$hash[($_.Name)] = $_.FullName}
 
gci -recurse |where {$_.Extension -match "dll"} |foreach {$hash[($_.Name)] = $_.FullName}
 
gci -recurse -filter MyNAME.*dll |foreach {$hash[($_.Name)] = $_.FullName}
 
$hash.Keys | where {$_ -match "dll"}

String Manipulation (for text based applications)

svn status | select-string "\?" | foreach {dir $_.ToString().SubString(7)}

Count Lines of code

$items = gci . -include *.cs,*.aspx -rec; ($items | select-string "//").Count / ($items | select-string .).Count
 
gci . -include *.cs,*.aspx -rec | % { [System.IO.File]::ReadAllText($_.FullName) } | Measure-Object -Line
 
dir . -r -i *.cs,*.aspx,*.sql |% {[System.IO.File]::ReadAllText($_.FullName)} |Measure-Object -Line
 
$items = gci . -r -i *.cs,*.aspx,*.sql ; ($items | select-string "//","--").Count

Find file(s) with line of text

gci . -r -i *.cs,*.aspx,*.sql | select-string "message_device_content_ins"

Count filtered Files

(gci . -fi *.exe -rec).Count

List unique filtered and sorted Files

gci . -fi *.exe -rec | get-unique | sort | foreach { $_.name}

Find in event log

get-eventlog -logname system |where {$_.Message -match "PATTERN"} | foreach {$_.Message}

Remote Event logs

$logs = [System.Diagnostics.EventLog]::GetEventLogs("ServerName")
$logs
 
Max(K) Retain OverflowAction        Entries Name
------ ------ --------------        ------- ----
20,480      0 OverwriteAsNeeded      10,716 Application
15,168      0 OverwriteAsNeeded           0 DFS Replication
20,480      0 OverwriteAsNeeded           0 Hardware Events
   512      7 OverwriteOlder              0 Internet Explorer
20,480      0 OverwriteAsNeeded           0 Key Management Service
16,384      0 OverwriteAsNeeded           4 Microsoft Office Diagnostics
16,384      0 OverwriteAsNeeded          38 Microsoft Office Sessions
 
20,480      0 OverwriteAsNeeded      37,642 System
15,360      0 OverwriteAsNeeded          81 Windows PowerShell
 
$logs[0].Machinename
 
ServerName
 
$logs[0].Entries | where {$_.Message -match "PATTERN"} | foreach {$_.Message}
 
$entries = $logs[0].Entries | where {$_.Message -match "file not found"}
$entries | format-table timewritten, message -autosize -wrap | out-file errors.txt

Registry

cd hklm:
 
get-ItemProperty 'hkcu:\Software\Microsoft\Internet Explorer\Main'
 
gp .

Other commands

gci . -recurse -filter MyNAME*
 
gci . *.cs -Recurse | select-string . | Group Path
 
Measure-Command {Get-Service | Export-Clixml c:\scripts\test.xml}
 
Invoke-Item c:\windows\system32\calc.exe
 
Copy-Item \\ c:\testrecurse
 
Test-Path c:\scripts\*.wma

Chop first 3 characters off every file with example extension

gci . *.example | foreach {& ren $_  $_.ToString().SubString(3)}

Replace a section of a filename

gci . *.example | foreach {& ren $_  $_.ToString().Replace("Blah", "") }

Add a prefix (or suffix)

gci . *.example | foreach {& echo $_  "PREFIX$_SUFFIX" }

Use TextInfo to rename to TitleCase (Pascal casing)

gci . *.example | foreach {& ren $_  (Get-Culture).TextInfo.ToTitleCase($_.ToString())}

Active Directory Machine names

$category = "computer"

$domain = New-Object System.DirectoryServices.DirectoryEntry

$searcher= New-Object System.DirectoryServices.DirectorySearcher
$searcher.SearchRoot = $domain 
$searcher.Filter = ("(objectCategory=$category)")

$properties = "name"
foreach ($i in $properties ){$searcher.PropertiesToLoad.Add($i)}

$results= $searcher.FindAll()

foreach ($results in $results){$computer = $results.Properties; $computer.name}

Profile script

function cd.. {cd ..}
function cd\ {cd \}

Registry Access

cd HKLM:
cd SOFTWARE\Microsoft\
cd '.\Microsoft\NET Framework Setup\NDP\v3.5'
dir
 
    Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5
 
SKC  VC Name                           Property
---  -- ----                           --------
  0   4 1033                           {Version, CBS, Install, SP}
 
Get-ItemProperty .
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
PSChildName  : v3.5
PSDrive      : HKLM
PSProvider   : Microsoft.PowerShell.Core\Registry
Version      : 3.5.30729.4926
CBS          : 1
Install      : 1
InstallPath  : C:\Windows\Microsoft.NET\Framework\v3.5\
SP           : 1
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License