tsunami

log in
history

PowerShell: code snippets

Luke Breuer
2010-04-26 22:08 UTC

# list files greater than a certain size by size
dir c:\dotnet\ -Recurse | 
    ? {$_.length -ge 5mb} | 
    sort -Prop length -Descending | 
    % {"{0,6:0.00} {1}" -f ($_.length / 1mb), $_.fullname}
# list entries in the system PATH variable
(dir env:path).Value | split-string -sep ';' | sort
# replace text in files
dir | % { Set-Content $_ ((get-content $_) -replace ("oldtext", "newtext")) }
# back up files
dir *.txt | cp -dest {"$_.bak"}
# parse http://stackoverflow.com/badges/30/beta
[Regex]::Split((Get-Clipboard), "(?<=\x3F\d+)(?=[A-Za-z])") |
    % { $_ -match "[A-Za-z0-9_ -]+[0-9,]+" } | 
    % { $matches[0] } | 
    Sort-Object { [int]::Parse([Regex]::Match($_, "[0-9,]+$").Value.Replace(',', '')) }
# list free space on various computers
("asp5", "asp2", "bc2", "dev2", "is1", "nn1", "web1", "web2", "xpvm2") | 
    % {
        $_
        Get-WmiObject Win32_LogicalDisk -Filter "DriveType = 3" -ComputerName $_ | 
            % { "{0} {1,4:0.0} / {2,4:0.0}" -f $_.DeviceID, ($_.FreeSpace / 1GB), ($_.Size / 1GB) }
    }

# alternatively
$servers = ("asp5", "asp2", "bc2", "dev2", "is1", "nn1", "web1", "web2", "xpvm2")

foreach ($server in $servers)
{
    $drives = Get-WmiObject Win32_LogicalDisk -Filter "DriveType = 3" -ComputerName $server

    $server

    $drives | % { "{0} {1,4:0.0} / {2,4:0.0}" -f $_.DeviceID, ($_.FreeSpace / 1GB), ($_.Size / 1GB) }
}
# nicer syntax for lists
> function list() { $args }
> list a b c
a
b
c
> (list a b c).GetType().Name
Object[]
# do a rough job of capitalizing SQL
$capitalize = list select update delete ifnull from union intersect natural inner `
                   right outer left join group order by where having avg sum min `
                   max count on as distinct and or not in set like between

(get-clipboard) | 
  % { $s = $_; 
      $capitalize | % { $s = $s -replace ("(?<!--[^\r\n]*)\b$_\b((?<!sum|min|max|avg|count)|(?=())"), ($_.ToUpper()) }; 
      $s 
    } | 
  write-clipboard
stolen
### Required to reference from inside the script.
$SQLDT = New-Object "System.Data.DataTable"

############
# SQL Data #
############
function Get-SqlData
{
    param([string]$serverName=$(throw 'serverName is required.'), [string]$databaseName=$(throw 'databaseName is required.'),
          [string]$query=$(throw 'query is required.'))
    $sqldt.reset()
    $connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
    $da = New-Object "System.Data.SqlClient.SqlDataAdapter" ($query,$connString)
    [void]$da.fill($SQLDT)
}

for($i=0;$i -lt $sqldt.rows.count;$i++) {
  $sqldt.rows[$i].lanid # do something with the result

}

LDAP
############
# Get-user #
############
function Get-User($email)
{
        # this function should be passed the email of the user to be returned
        $root = [ADSI] "LDAP://yourdomain.com";
        $searcher = New-Object System.DirectoryServices.DirectorySearcher $root
        $searcher.filter = "(&(objectCategory=person)(objectClass=user)(mail=$email))"
        $user = $searcher.FindOne()
        $Script:ADUser = $user.GetDirectoryEntry()
}