úterý 24. ledna 2012
Bad device
neděle 16. října 2011
Primarní networkadapter
nebo
get-wmiobject win32_networkadapter -filter "netenabled=’true’"
get-wmiobject win32_networkadapterconfiguration -filter "IPEnabled=’True’"
pátek 16. září 2011
Seznam fontů
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$objFonts = New-Object System.Drawing.Text.InstalledFontCollection
$colFonts = $objFonts.Families
$objIE = New-Object -com "InternetExplorer.Application"
$objIE.Navigate("about:blank")
$objIE.ToolBar = 0
$objIE.StatusBar = 0
$objIE.Visible = $True
$objDoc = $objIE.Document.DocumentElement.LastChild
foreach ($objFont in $colFonts)
{
$strHTML = $strHTML + "<font size='5' face='" + $objFont.Name + "'>" + $objFont.Name + "</font><br>"
}
$objDoc.InnerHTML = $strHTML
pátek 9. září 2011
HOSTS
Function Get-HostsFile {
.SYNOPSIS
Retrieves the contents of a hosts file on a specified system.
.DESCRIPTION
Retrieves the contents of a hosts file on a specified system.
.PARAMETER ComputerName
The computers to access.
.NOTES
Name: Get-HostsFile
Author: Boe Prox
DateCreated: 15Mar2011
1.1 - 2011-03-17 - Jason Archer
Improved pipeline support (and fixed positional usage).
Added custom object creation and incremental output (better performance and cleaner code).
For local host, use local path.
Added error messages for error conditions.
1.0 - 2011-03-15 - Boe Prox
Initial release.
.LINK
http://boeprox.wordpress.com
.EXAMPLE
Get-HostsFile "server1"
Description
-----------
Retrieves the contents of the hosts file on 'server1'.
#>
[CmdletBinding()]
Param(
[Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[ValidateNotNull()]
[string[]]$ComputerName = "localhost"
)
Begin {
$PSBoundParameters.GetEnumerator() | Foreach-Object {
Write-Verbose "Parameter: $_"
}
}
Process {
Write-Verbose "Starting process of computers"
ForEach ($c in $ComputerName ) {
Write-Verbose "Testing connection of $c"
If (Test-Connection -ComputerName $c -Quiet -Count 1) {
Write-Verbose "Validating path to hosts file"
if ($c -eq "localhost") {
$root = "C:"
} else {
$root = "\\$c\C`$"
}
If (Test-Path "$root\Windows\system32\drivers\etc\hosts") {
Switch -regex -file ("$root\Windows\system32\drivers\etc\hosts") {
"^#\w+" {
}
"^\d\w+" {
Write-Verbose "Adding IPV4 information to collection"
$new = $_.Split("") | Where-Object {$_ -ne ""}
If ($new[2] -eq $null) {
$notes = $null
} Else {
$notes = $new[2]
}
New-Object PSObject -Property @{
ComputerName = $c
IPV4 = $new[0]
IPV6 = $null
Hostname = $new[1]
Notes = $notes
}
}
Default {
If (!("\s+" -match $_ -OR $_.StartsWith("#"))) {
Write-Verbose "Adding IPV6 information to collection"
$new = $_.Split("") | ? {$_ -ne ""}
If ($new[2] -eq $null) {
$notes = $null
} Else {
$notes = $new[2]
}
New-Object PSObject -Property @{
ComputerName = $c
IPV4 = $null
IPV6 = $new[0]
Hostname = $new[1]
Notes = $notes
}
}
}
}
} ElseIf (Test-Path "$root\WinNT\system32\drivers\etc\hosts") {
Switch -regex -file ("$root\WinNT\system32\drivers\etc\hosts") {
"^#\w+" {
}
"^\d\w+" {
Write-Verbose "Adding IPV4 information to collection"
$new = $_.Split("") | ? {$_ -ne ""}
If ($new[2] -eq $null) {
$notes = $null
} Else {
$notes = $new[2]
}
New-Object PSObject -Property @{
ComputerName = $c
IPV4 = $new[0]
IPV6 = $null
Hostname = $new[1]
Notes = $notes
}
}
Default {
If (!("\s+" -match $_ -OR $_.StartsWith("#"))) {
Write-Verbose "Adding IPV6 information to collection"
$new = $_.Split("") | ? {$_ -ne ""}
If ($new[2] -eq $null) {
$notes = $null
} Else {
$notes = $new[2]
}
New-Object PSObject -Property @{
ComputerName = $c
IPV4 = $null
IPV6 = $new[0]
Hostname = $new[1]
Notes = $notes
}
}
}
}
} Else {
## TODO: Could use the properly localized path not found error
Write-Error "Unable to locate host file on computer: $c"
}
} Else {
## TODO: Could use the properly localized can not locate host error
Write-Error "Unable to locate computer: $c"
}
}
}
}
pátek 22. července 2011
Portable powershell
pátek 10. června 2011
Seskupovaní podle kriterií
Opět tip z powertips
Někde v hloubi blogu je myslim už group a totožne co je na powertips jenom misto
Get-Process | Group-Object -property Company je tam seskupovaní služeb.
Ukazka z powertips ukazuje vlastni seskupení podle tří kataegorii – rozdilná velikost,jak si je kdo nazve ve scriptu nebo kolik si takových kriteríí uděla a jaká velikost bude patřit k čemu je věc jenom toho co hledám a seskupuji.
PS> $criteria = {
if ($_.Length -lt 1KB) {
'tiny'
} elseif ($_.length -lt 1MB) {
'average'
} else {
'huge' }
}
PS> dir $env:windir | Group-Object -Property $criteria
Výsledek
Tvorba hash table se samozřejmě neomezuje na velikost nebo seskupovaní procesů,nakombinovat jde spousta věcí.
pondělí 14. března 2011
pondělí 7. března 2011
Powershell a Nmap
Dnes jsem při upravování výstupu pro netstat v powershellu narazil v jine souvislosti na zajimavý ps1 script pro nmap.
http://blogs.sans.org/windows-security/2009/06/11/powershell-script-to-parse-nmap-xml-output/
Jeden z možných vystupů ktere exportuje potom vypadá takto
neděle 27. února 2011
History script powershell
Start-demo mimochodem podporuje vylepšenou automatizaci – autoexecute mode a autospeed parametr a mnoho mnoho dalšího.Je to předělavka původního Jeffrey Snover's original Start-Demo script od Joel "Jaykul" Bennetta.
Jak pracuje start demo a jak si tam vkladat svoje sekvence je popsáno jak na strankach poshcode kde je upravené start-demo ke stažení tak někde,bůhvíkde o hodně přispěvků zpět na tomto blogu.
Na konci videa je ještě ukazka prace s profilem powershellu– jeho uprava ,vlastní alias,vložení funkce,volání funkce.
Slibovaný script pro práci s historií,význam má alespon pro mne je to tak ,pokud je v profilu.Autora a popis si vyhledejte – bude bud na pashcode nebo technet scriptcentru,změnil jsem nazev funkce a maxcount,takže kdo chce původní hodnoty může se po něm mrknout,vzhledem k tomu že ho mam v profilu původní popis scriptu už nemám.Nicmeně vychazet by se mělo z http://www.nivot.org/2009/08/15/PowerShell20PersistingCommandHistory.aspx
#region History archiving
function exporthistory {
param ([string]$path=$historyPath)
$cmdArray = @()
if (Test-Path $path) {
$savedHistory = @(Import-Clixml $historyPath)
$savedHistory | % { $cmdArray += $_.CommandLine }
Get-History -Count $MaximumHistoryCount | % {
#first level of filtering
if ($cmdArray -notcontains $_.CommandLine) { $savedHistory += $_ }
#Second level of filtering to remove duplicates from current session also
$cmdArray = @()
$savedHistory | % { $cmdArray += $_.CommandLine }
}
$savedHistory | Export-Clixml $path
Write-Host -ForegroundColor Green "`nExported history to $path along with old import`n"
} else {
Get-History -Count $MaximumHistoryCount | Export-Clixml $path
Write-Host -ForegroundColor Green "`nExported history to $path`n"
}
}
function Import-History {
param ([parameter(mandatory=$true)][string]$path=$historyPath)
if (Test-Path $(Split-Path $path)) {
Import-Clixml $path | ? {$count++;$true} | Add-History
Write-Host -Fore Green "`nLoaded $count history item(s) from $path`n"
}
}
function Get-HistoryArchives {
$historyArchives = @()
$historyItems = Get-ChildItem $(Split-Path $profile) History*.clixml
$historyItems | % {
$archive = New-Object PSObject
$archive | Add-Member NoteProperty Name $_.Name
$archive | Add-Member NoteProperty FullName $_.FullName
$archive | Add-Member NoteProperty CreatedOn ($_.LastWriteTime).GetDateTimeFormats()[18]
$historyArchives += $archive
}
$historyArchives
}
function Show-HistoryArhive {
param ([parameter(mandatory=$true)][string]$path)
if (Test-Path $path) {
Import-Clixml $path
}
}
#reset $MaximumHistoryCount to 300
$MaximumHistoryCount = 300
#Generate Histry export path for this session
$date = Get-Date
#This is not so good. But OK for now
$historyPath = "$((split-path $profile))\History$($date.Month)$($date.Day)$($date.Year).clixml"
# This is from Nivot Ink's (@oising) blog post http://www.nivot.org/2009/08/15/PowerShell20PersistingCommandHistory.aspx
Register-EngineEvent -SourceIdentifier powershell.exiting -SupportEvent -Action { Export-History }
# load the most recent history, if it exists
if ((Test-Path $(Split-Path $profile))) {
try {
if (Test-Path $historyPath) {
Import-History $historyPath
} else {
Write-Host -Fore Red "`nNo command history to restore`n"
}
}
catch {
Write-Host -Fore Red "`nNo command history to restore`n"
}
}
#endregion
function prompt {
$mapped_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=4" | foreach {echo $_.deviceid}
$local_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" | foreach {echo $_.deviceid}
$removable_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=2" | foreach {echo $_.deviceid}
$t = $(get-date -format "HH:mm:ss")
$a = (get-location).path
$d = (get-location).path.substring(0,$a.indexof(":")+1)
$a = $a.substring($a.LastIndexOf("`\")+1)
if ((get-location).path.substring(0,(get-location).path.indexof(":")) -eq "Microsoft.PowerShell.Core\FileSystem") {
$a = (get-location).path
$a = $a.substring($a.indexof(":")+2)
write-host -fore white -back blue "$t - $a ";"`$`> "}
else {
if ($a -eq "") {$a = "`\"}
if ($d.length -gt 2) {
write-host -ForegroundColor black -backgroundcolor red "[$t] - [$d] $a ";"`$`> "}
elseif ($local_drives -contains "$d") {
write-host -ForegroundColor black -backgroundcolor green "[$t] - [$d] $a ";"`$`> "}
elseif ($removable_drives -contains "$d") {
write-host -ForegroundColor black -backgroundcolor yellow "[$t] - [$d] $a ";"`$`> "}
elseif ($mapped_drives -contains "$d") {
write-host -ForegroundColor black -backgroundcolor magenta "[$t] - [$d] $a ";"`$`> "}
}
}
čtvrtek 3. února 2011
úterý 1. února 2011
Powershell rozdilný výstup auditu
Další variantou jak najednou ziskat zakladní informace o PC a dal s nimi pracovat je vystup ogv.
Spuštění potom můžeme řešit přes ps1,execute in powershell a –NOEXIT,nebo přes dejme tomu vytvořeni funkce a spouštění scriptu nazvem funkce až ho chceme spustit,nebo cestou ke scriptu.Každopaádně admin mode bych preferoval.Na videu je varianta kdy udělame ps1 script obsahujici jenom přikazy a spouštime zadáním cesty k němu.
Varianta dvě zkopirujeme do okna powershellu nasledující
function audit
{Get-process|select-object *|ogv
Get-WmiObject Win32_Process | ForEach-Object { $ownerraw = $_.GetOwner(); $owner = '{0}\{1}' -f $ownerraw.domain, $ownerraw.user; $_ | Add-Member NoteProperty Owner $owner -PassThru } | Select-Object Name, Owner|ogv
Get-service|select-object *|ogv
Get-WmiObject Win32_Service | sort -property Name | select Name, State, ProcessId, Description, StartName |ogv
get-wmiobject Win32_QuickFixEngineering | sort -property HotFixID | select -property HotFixID, Description|ogv
get-wmiobject Win32_Desktop | sort -property Name | select Name, BorderWidth, Caption, CoolSwitch, CursorBlinkRate, Description, DragFullWindows, GridGranularity, IconSpacing, IconTitleFaceName, IconTitleSize, IconTitleWrap, Pattern, ScreenSaverActive, ScreenSaverExecutable, ScreenSaverSecure, ScreenSaverTimeout, SettingID, Wallpaper, WallpaperStretched, WallpaperTiled|ogv
get-wmiobject Win32_Environment | sort -property Name | select -property Name, Status, SystemVariable, UserName|ogv
get-wmiobject Win32_StartupCommand | sort -property Name | select -property Name, Location, Command|ogv
get-wmiobject Win32_BootConfiguration | select -property Name, BootDirectory, Description, LastDrive, ScratchDirectory, TempDirectory|ogv
get-wmiobject Win32_LogonSession | sort -property LogonId | select -property LogonId, LoginType, AuthenticationPackage, Description, InstallDate, StartTime|ogv
Get-EventLog -list|ogv
get-wmiobject Win32_ComputerSystem | select Name, Description, @{Label="DNS Host Name"; Expression={$_.DNSHostName}}, Domain, Manufacturer, Model, @{Label="# Processors";Expression={$_.NumberOfProcessors}}, @{Label="System Type";Expression={$_.SystemType}}, @{Label="Physical Memory";Expression={"{0,12:n0} MB" -f ($_.TotalPhysicalMemory/1mb)}}|ogv
get-wmiobject Win32_BIOS | select Name, Manufacturer, ReleaseDate, SerialNumber|ogv
get-wmiobject Win32_PhysicalMemory | select @{Label="Device Location";Expression={$_.DeviceLocator}}, DataWidth, @{Label="Capacity";Expression={"{0,12:n0} MB" -f ($_.Capacity/1mb)}}, PartNumber, SerialNumber, Speed|ogv
get-wmiobject Win32_IP4RouteTable | sort Destination | select Destination, Mask, NextHop, Age |ogv
get-wmiobject Win32_NetworkAdapterConfiguration | sort Description | select Description, DHCPEnabled, IPEnabled, ServiceName, SettingID|ogv
get-wmiobject Win32_NetworkAdapter | sort Name | select Name, Manufacturer, PhysicalAdapter, ServiceName, PNPDeviceID|ogv
get-wmiobject Win32_NetworkClient | select Name, Description, Manufacturer, Status|ogv
get-wmiobject Win32_NetworkLoginProfile -filter "NOT Name LIKE 'NT AUTHORITY%'" | sort Name | select Name, Comment, NumberOfLogons, LastLogon|ogv
get-wmiobject Win32_NetworkProtocol | sort Name | select Name, Description|ogv
get-wmiobject Win32_Printer | sort Name | select Name, Comment, DriverName, Location, Network, PortName, ShareName|ogv
get-wmiobject Win32_PrintJob | select Document, @{Label="Status";Expression={$_.JobStatus}}, Owner, @{Label="Pages";Expression={$_.TotalPages}}, @{Label="Submitted";Expression={[System.Management.ManagementDateTimeconverter]::ToDateTime($_.TimeSubmitted)}}|ogv
get-wmiobject Win32_PrinterDriver | sort Name | select Name, DriverPath|ogv
get-wmiobject Win32_DiskPartition | sort Name | select Name, @{Label="Size";Expression={"{0,12:n0} MB" -f ($_.Size/1mb)}}, @{Label="Primary?";Expression={$_.PrimaryPartition}}, @{Label="Boot?";Expression={$_.BootPartition}}|ogv
get-wmiobject Win32_LogicalDisk | select Name, Description, FileSystem, @{Label="Size";Expression={"{0,12:n0} MB" -f ($_.Size/1mb)}}, @{Label="Free Space";Expression={"{0,12:n0} MB" -f ($_.FreeSpace/1mb)}}, ProviderName|ogv
get-wmiobject Win32_MappedLogicalDisk | select Name, Description, FileSystem, @{Label="Size";Expression={"{0,12:n0} MB" -f ($_.Size/1mb)}}, @{Label="Free Space";Expression={"{0,12:n0} MB" -f ($_.FreeSpace/1mb)}}, ProviderName|ogv
get-wmiobject Win32_DiskDrive | sort Name | select Name, Model, MediaType, InterfaceType, Partitions, @{Label="Size";Expression={"{0,12:n0} MB" -f ($_.Size/1mb)}}|ogv
get-wmiobject Win32_Share | sort Name | select Name, Path, Status|ogv
Get-Content $env:windir\windowsupdate.log -encoding utf8 | Where-Object { $_ -like '*successfully installed*'} | Foreach-Object { $infos = $_.Split("`t"); $result = @{}; $result.Date = [DateTime]$infos[6].Remove($infos[6].LastIndexOf(":")); $result.Product = $infos[-1].SubString($infos[-1].LastIndexOf(":")+2); New-Object PSobject -property $result }|ogv
Get-Alias | Group-Object Definition|ogv
}
Odentrujeme a napišeme audit.
Video
Další variantou je použit Powershell ISE,pro něj addon ISE MENU CREATOR a viz. obrazky niže.
Nedefinujeme si klavesovou zkratku a pouštime potom prostě klavesovou zkratkou.
pondělí 31. ledna 2011
Powershell existence kliče
Otestuj existenci daneho kliče v registru a pokud neexistuje tak ho vytvoř.
if (Test-Path 'HKCU:\Software\testovaci') {
"Registry key HKCU:\Software\testovaci already exists."
} else {
md HKCU:\Software\testovaci}
neděle 26. prosince 2010
Powershell patchimage windowsupdate
Osobně VHD mam ve virtualu,jako multiboot a v několika verzich jak plynul čas a k nejrůznějšímu použití.
Funkce má nespočet využití – některe si prostě přečtete ve scriptu,jiné na strankach autora scriptu,no a další a další můžete přidávat podle toho k čemu vhd nebo wim použivate – nepouživate.
Stránky autora scriptu s podrobným popisem
http://www.optimalizovane-it.cz/windows-7/imagepatcher-aktualizujte-wim-a-vhd-z-windows-update.html
Video
pondělí 8. listopadu 2010
Powershell set-acl
Cest existuje několik,je to serial o powershellu takže ukazka jak na to v Powershellu – jedna z mnoha cest v něm.za jistých okolností napřiklad v AD nebo když jde o okopirovaní nikoliv složka a co je v ní a vše stejně na jinou složku a vše co je v ní ale jde o strom – strom a třeba v AD tak se to děla v Powershellu jinak.
Takže
get-acl D:\experimenty\test | set-acl D:\experimenty\test2
Další možne scenaře a cesty
$PesACL = get-acl c:\pes.txt
set-acl -path C:\kocka.txt -AclObject $PesACL
Varianta soubor – soubor,trochu jinak napsaná.
Potom napřiklad
get-childitem c:\tvojeslozka-recurse -force | set-acl -aclobject $PesACL –whatif
tvojeslozka na disku C a vše co je v ní přebira stejne nastavení od pes.txt
Další varianta – vhodne pro kapku jine situace
$Acl.RemoveAccessRule($Ar) $Acl.RemoveAccessRuleAll()
Remove acl myslim netřeba komentovat.
Video k prvnímu připadu,ostatní jsou ukazky zbytečné ,k active directory a servrům se hodlam posunout až se mně budet chtít víc věnovat Powergui.