skip to main content

Useful PowerShell one-liners and short scripts

These are various PowerShell one-liners and short scripts I have come to use often since the better part of the last year.

Recursive folder removal

gci D:\xfr\test -include .lgf -Recurse -Force | Remove-Item -Recurse -Force

Get network shares of a server

Get-WmiObject -class win32_share -comp $shares | ft name >> domshares.log

Remove .svn folders

gci -rec -force -ea 0| ?{$_.mode -match "h" -and $_.psiscontainer -and $_.name -match ".svn"} | Remove-Item -rec -force

Get free disk space from a list of servers

$servers= @(gc apps.txt)

foreach($server in $servers)
{
Get-WMIObject Win32_LogicalDisk -filter DriveType=3 -computer $server `
    | Select SystemName,DeviceID,@{Name="size(GB)";Expression="{0:N1}" -f($_.size/1gb)},@{Name="freespace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}} 
}

Get available local disk space

$DiskDrive = GWMI -CL Win32_LogicalDisk | Where {$_.DeviceId -Eq "C:"}
$DriveSpace = ($DiskDrive.FreeSpace /1GB)

Write-Host Available Free Disk Space = $DriveSpace GB

Get IIS Version

$key = get-item 'HKLM:\SOFTWARE\Microsoft\InetStp'
$values = get-itemproperty $key.PSPath
write-host $values.VersionString

Unorganize a folder

This is a script that does the opposite of uncluttering your desktop

$cleanfolder = "C:\Documents and Settings\banimesh\Desktop\ORG"
$deorg = "C:\Documents and Settings\banimesh\Desktop\DEORG"

gci $cleanfolder -recurse `
    | ?{!$_.psiscontainer} `
    | mv -dest $deorg

Get last weeks date

(get-date).AddDays(-7).ToShortDateString()

Move certain files to another location

 $paths = get-content paths.txt
 $list = dir $paths -re -fi *.zqx | ?{$_.lastwritetime -lt (get-date)} 

 mv $list -dest e:\xqz

Get backup files not older than seven days

$today = get-date
$todaym7 = $today.AddDays(-7)
$todaym7 = $todayminus7.tostring("yyyy-MM-dd")
$paths = "paths.txt"
dir $paths -re -fi *.bak | ? {$_.lastwritetime -gt $today} | ft name | out-file baklog-"$todaym7".log

Get a comma delimited list from a text file of strings

This script is/was a lifesaver for me on machines with no install rights and Excel.

pats self on back

@(gc file.txt) | % {$_ -replace "$_","'$_',"} >> output.txt