Power Blah
Fancy Select Statement
dir | select name, @{Name="Initial"; Expression = {$Global:foo = $null; $global:foo=$_.Name.Substring(0,1);$foo}}, @{Name="test";Expression = {$Global:foo += " Test"; $Global:foo}}
Different way to do fancy select
http://www.getshifting.com/wiki/powerclinotes
$LastBootProp = @{
Name = 'LastBootTime'
Expression = {
( Get-Date ) - ( New-TimeSpan -Seconds $_.Summary.QuickStats.UptimeSeconds )
}
}
Get-View -ViewType VirtualMachine -Property Name, Summary.QuickStats.UptimeSeconds | Select Name, $LastBootProp
Disk Space
Find all "local" drives (drivetype 3) and display name, size, freespace in GB and percent free
Get-WmiObject Win32_LogicalDisk -Filter "DriveType='3'" | select DeviceID,
@{Name=’SizeGB’;Expression={[Math]::Round($($_.Size / 1GB),1)}},
@{Name='FreespaceGB';Expression={[Math]::Round($($_.FreeSpace / 1GB ),1)}},
@{Name=’PercentFree’;Expression={[Math]::Round($($_.FreeSpace /$_.Size * 100),1)}} | ft -autosize
more stuff
get-qaduser $env:username -IncludedProperties webpage | select name, webpage
get-qaduser -sl 0 -IncludedProperties webpage | where {$_.webpage -ne $null} | select samaccountname, webpage
find the latest backup files
$date = get-date 3/27/2009
$date = $date.AddHours(20)
$pathlist = gci \\servername\g$ -include *.bak -Recurse | where {$_.LastWriteTime -ge $date } | select PSPath
dd
Grouping stuff
Get-Service | Group-Object status (Get-Service | Group-Object status)[1].group
Ping a list of servers
Simple ping list
$pinglist = Import-Csv "C:\Reports\check.csv" $pinglist = $pinglist | where {$_.DiscoveryComputername -ne ""} foreach ($machine in $pinglist) { $pingable = $null $counter ++ $pingable=$(Test-Connection -Quiet -ComputerName $machine.DiscoveryComputerName) write-host "$counter testing $($machine.DiscoveryComputerName) $pingable" $machine | Add-Member -membertype noteproperty -name Pingable -Value $($Pingable) } $pinglist | Export-Csv -notype "C:\Reports\output.csv"
Simple ping list with DNS query
$pinglist = Import-Csv "c:\temp\Servers.csv" foreach ($machine in $pinglist) { $pingable = $null $DNS = $null $IPAddress = $null $counter ++ $DNS = [System.Net.Dns]::GetHostByName($machine.servername) $IPAddress = $DNS.AddressList[0].IPAddressToString $pingable=$(Test-Connection -Quiet -Count 1 -ComputerName $machine.servername) write-host "$counter testing $($machine.servername) $pingable" $machine | Add-Member -membertype noteproperty -name IP -Value $($IPAddress) $machine | Add-Member -membertype noteproperty -name Pingable -Value $($Pingable) } $pinglist | Export-Csv -notype "c:\temp\Servers_output.csv"
Ping list of windows boxes
$PingList= Get-QADComputer blah* | select name, operatingsystem foreach ($machine in $pinglist) { $pingable=$(Test-Connection -Quiet -ComputerName $machine.name) $bios= Get-WmiObject -ComputerName $machine.name -Class win32_bios $machine | Add-Member -membertype noteproperty -name Pingable -Value $($Pingable) $machine | Add-Member -membertype noteproperty -name SerialNumber -Value $($Bios.SerialNumber) write-host $machine.name ", " $pingable ", " $($Bios.SerialNumber) } $PingList
$pinglist = Get-Content .\PingList.csv
foreach ($machine in $pinglist)
{
$foo= Get-QADComputer $machine
$pingable=$(Test-Connection -Quiet -ComputerName $machine)
write-host $machine ", " $foo.operatingsystem "," $pingable
}
Get Group Membership
$SGGroups = Get-QADGroup sg*
foreach ($SGGroup in $SGGroups)
{
Write-Host $SGGroup.name
Get-QADGroupMember $SGGroup.name | select name
}
$GroupList = Get-QADGroup -SearchRoot 'blah.corp/groups/foo'
Write-Host "GroupName, Name, UserName"
foreach ($Group in $GroupList)
{
foreach ($User in (Get-QADGroupMember $Group.name))
{
Write-Host $Group.name "," $User.name "," $User.samAccountname
}
}
DNS / Name Resolution
http://blogs.msdn.com/powershell/archive/2006/06/26/647318.aspx
[System.Net.Dns]::GetHostAddresses("www.msn.com")
[System.Net.Dns]::GetHostbyAddress("207.46.198.30")
List Open Files / Sessions
sysinternals psfile will list open files on a remote machine have not found a way to do it in powershell yet
http://powershell.com/cs/forums/p/1911/2642.aspx
$server = "server"
$filePath="blah.txt"
$adsi = [adsi]"WinNT://$server/LanmanServer"
$users = $adsi.psbase.invoke("resources") | foreach {$_.gettype().invokeMember("user","GetProperty",$null,$_,$null)}
$paths = $adsi.psbase.invoke("resources") | foreach {$_.gettype().invokeMember("path","GetProperty",$null,$_,$null)}
$userfiles =for($i = 0;$i -lt $users.length; $i++) { "{0}: {1}" -f $users[$i],$paths[$i] }
$userfiles | where {$_.contains("$filePath")}
Scheduling a script (Scheduled Tasks)
powershell.exe -nologo -noprofile -windowstyle hidden -command "& {set-executionpolicy Bypass -scope Process; c:\scripts\blah.ps1}"
Change the field / column header in a select statement
get-qaduser "kevin c" | select-object logonName, @{Name="containerName"; Expression={$_.parentContainer}}
PowerGUI Reporting Pack
PowerGUI AD Recycle Bin power pack
http://powergui.org/shares/powergui/sbin/docs/AD_Recycle_Bin_PowerPack/AD_Recycle_Bin_PowerPack.html
Required Parameters (param)
param(
[parameter(Mandatory=$true,Position=0)]
[string]$Studio
)
Datestamp
Datestamp, date math etc.
get-date -uformat "%Y-%m-%d" #2014-04-22 get-date -uformat "%Y-%m-%d %T" #2014-04-22 20:11:54
$StartTime = get-Date
$StopTime = Get-Date
$ElapsedTime =$StopTime - $StartTime
$([Math]::Round($ElapsedTime.TotalMinutes,0))
write-host $([Math]::Round($($(get-date) -$StartTime).TotalMinutes,0)) Minutes
Substring
$MasterList = gci $MasterFiles -Recurse -include *.idx,*.dct | where {$_.Name -match "^[0-9]"} | foreach {$($_.name).substring(4)} | sort -Unique
Check-Even
http://mow001.blogspot.com/2006/10/powershell-how-can-i-tell-whether.html
Function check-even ($num) {[bool]!($num%2)}
Advanced Functions
get-help -full about_Advanced Functions | less -i
[Parameter(mandatory=$true)]
ValueFromePipeLine = $true
Position = 0
Format Operator
http://bsonposh.com/archives/229
Cloning Objects
Copy a variable / object. clone object
http://powershell.com/cs/blogs/tips/archive/2009/05/06/cloning-objects.aspx
$a = @{} $a.Test = 1 $a.Value = 2 $b = $a.Clone() $a.New = 3 $b
Renaming files
$files = Get-ChildItem *.jpg | sort -Property LastWriteTime $counter = $null foreach ($file in $files) { $counter ++ move $($file.Name) "Picture$Counter.jpg" }
Zip files
http://mow001.blogspot.com/2006/01/msh-out-zip-function.html
function out-zip { Param([string]$path) if (-not $path.EndsWith('.zip')) {$path += '.zip'} if (-not (test-path $path)) { set-content $path ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) } $ZipFile = (new-object -com shell.application).NameSpace($path) $input | foreach {$zipfile.CopyHere($_.fullname)} }
Get-Item test.txt | out-zip c:\temp\foo.zip
Unzip files
function unzip-file { [CmdletBinding()] Param( [parameter(Position=0,Mandatory=$True)] [ValidateScript({Test-Path $_ -PathType 'leaf'})] [string]$Zipfile, [parameter(Position=1,Mandatory=$True)] [ValidateScript({Test-Path $_ -PathType 'Container'})] [string]$DestinationFolder ) $ShellApp = new-object -com shell.application $ZipFileObject = $ShellApp.NameSpace($zipfile) $DestinationObject = $ShellApp.NameSpace($destinationFolder) $DestinationObject.CopyHere($ZipFileObject.Items(),20) <# .synopsis Unzip a file .description Unzip .PARAMETER Zipfile You must specify the zip file path .PARAMETER DestinationFolder You must specify the Destination Folder path .example unzip-file -Zipfile C:\foo.zip -DestinationFolder C:\blah .Link http://www.google.com #> }
unzip-file -Zipfile C:\foo.zip -DestinationFolder C:\blah
Uptime
http://technet.microsoft.com/en-us/magazine/2008.12.heyscriptingguy.aspx?pr=blog
function Get-Uptime { [CmdletBinding()] Param( [Parameter(Mandatory=$false, HelpMessage="Computer Name")][String]$ComputerName ) If ($ComputerName) {$wmi = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName} Else {$wmi = Get-WmiObject -Class Win32_OperatingSystem} $wmi.ConvertToDateTime($wmi.LocalDateTime) - $wmi.ConvertToDateTime($wmi.LastBootUpTime) <# .synopsis Check the uptime of a machine .description Uptime .PARAMETER ComputerName specify the Computer Name .example Get-Uptime -ComputerName Server01 .example Get-Uptime Server01 .Link http://technet.microsoft.com/en-us/magazine/2008.12.heyscriptingguy.aspx?pr=blog #> }
$Uptime = Get-Uptime $Uptime.TotalDays (Get-Uptime).totaldays (Get-Uptime).gettype()
Splatting splat
$ComputerSystem = @{Query="Select * From Win32_ComputerSystem"} Get-WmiObject @ComputerSystem
passing parameters to next function
@psBoundParameters
Fast Active Directory Search
No import module
$ADSearcher = [adsisearcher]"(samaccountname=$env:USERNAME)" $ADSearcher.FindOne().Properties.mail
Get MD5 Checksum
http://stackoverflow.com/questions/10521061/how-to-get-a-md5-checksum-in-powershell
function Get-MD5($path) { $fullPath = Resolve-Path $path $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider $file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read) [System.BitConverter]::ToString($md5.ComputeHash($file)) $file.Dispose() }
Check for locked file
test for filelock
http://stackoverflow.com/questions/24992681/powershell-check-if-a-file-is-locked
function Test-FileLock { param ([parameter(Mandatory=$true)][string]$Path) $oFile = New-Object System.IO.FileInfo $Path if ((Test-Path -Path $Path) -eq $false) { return $false } try { $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($oStream) { $oStream.Close() } $false } catch { # file is locked by a process. return $true } }