Home › Tag Archives › powershell

Compare http/URL

#################################################
# compareURL - Michal Weis
#
#
#################################################
 
[string]$URL = "http://www.logon.cz"
[string]$workFolder = "C:\temp"
[string]$oldFile = "puvodni.txt"
[string]$newFile = "novy.txt"
 
[string]$SMTPServer = "marge"
[string]$to = "kam@email.com"
[string]$from = "skript@email.com"
[string]$Subject = "Zmena stranky $URL"
[string]$Body = "Nastala zmena stranky $URL <br> Cas kontroly: $(get-Date)"
 
#################################################
# fn. stahni definovany soubor
#################################################
Function DownloadFile()
{
Param
(
[Parameter(Mandatory=$true,Position=1)][string]$URL
)
 
[io.file]::WriteAllText("$workFolder\$newFile",(Invoke-WebRequest -URI $URL).content)
}
 
#################################################
# fn. porovnej soubory
#################################################
Function CompareFile()
{
Param
(
[Parameter(Mandatory=$true,Position=1)][string]$sourceFilePath,
[Parameter(Mandatory=$true,Position=2)][string]$destinationFilePath
)
 
$Result = Compare-Object $(Get-Content $sourceFilePath) $(Get-Content $destinationFilePath)
If ($Result)
{
Return $false
} Else
{
Return $true
}
 
}
 
#################################################
# fn. prejmenuj soubor
#################################################
Function RenameFile()
{
Param
(
[Parameter(Mandatory=$true,Position=1)][string]$oldName,
[Parameter(Mandatory=$true,Position=2)][string]$newName
)
If (Test-Path $newName)
{
Remove-Item $newName -Force
}
Rename-Item $oldName $newName -Force
}
 
#################################################
# fn. posli email
#################################################
Function sendEmail()
{
Param
(
[Parameter(Mandatory=$true,Position=1)][string]$from,
[Parameter(Mandatory=$true,Position=2)][string]$To,
[Parameter(Mandatory=$true,Position=3)][string]$Subject,
[Parameter(Mandatory=$true,Position=4)][string]$Body,
[Parameter(Mandatory=$true,Position=5)][string]$SMTPServer
)
 
Send-MailMessage -SmtpServer $smtpServer -To $to -From $from -Subject $Subject -Body $body  -BodyAsHtml -Priority high
}
 
#################################################
# hlavni telo programu
#################################################
DownloadFile $URL
If (Test-Path $workFolder\$oldFile)
{
If ((CompareFile $workFolder\$oldFile $workFolder\$newFile) -eq $false)
{
sendEmail $from $to $Subject $Body $SMTPServer
}
}
RenameFile $workFolder\$newFile $workFolder\$oldFile

Powershell ISE – function Explorer

Jak jsem bez toho mohl psat :)

http://gallery.technet.microsoft.com/PowerShell-ISE-FunctionExpl-fd7e1c74#content

Powershell convert UTF8 to ASCII

$Text = "blabla"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($Text)
$b = [System.Text.Encoding]::Convert([Text.Encoding]::UTF8,[Text.Encoding]::ASCII,$bytes)
-join[System.Text.Encoding]::ASCII.GetChars($b)

Set culture powershell

[threading.thread]::CurrentThread.CurrentCulture = ‚en-US‘

RDP logon from security log – powershell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[int]$intEventID = 4624
[int]$intLogonType = 10
 
$securityLog = Get-EventLog "Security" | where {$_.EventID -eq $intEventID}
 
$strLog = "TimeGenerated;UserName`n"
 
ForEach ($log in $securityLog) {
	$LogonTypeString = "Logon Type:"
	$idx = $log.Message.IndexOf($LogonTypeString)
	$LogonType = -1
	if( $idx -gt 0 )
	{
	$LogonType = $log.Message.Substring( $idx + 	$LogonTypeString.length, 7).trim()
	}
	If ($LogonType -eq $intLogonType) {
		$logArray = $log.message.split("`n")
		$userName = $logArray[12].Split("`t")
		$strLog = $strLog + $log.TimeGenerated + ";" + 			$userName[3] + "`n"
	}
}
$strLog | out-file data.csv

Powershell – switch

Tohle mě nadchlo :)

Switch -wildcard ($objComputer.Name.split("-")[0].ToLower()) {
	zp* {$strTargetPath = "Praha"}

List users of group

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
$ErrorActionPreference = "Stop"
 
Function listUsers ($group) {
	trap {
		Write-Host "-ERROR-"
        Write-Host "Cannot connect to $domain" -BackgroundColor red -ForegroundColor Black
		Write-Host
		exit
    }  
 
	foreach ($member in $group.member)
	{
		Write-Progress -activity "List users" -status "Search ..." 
 
		$mem = [ADSI] "LDAP://$member"
 
		If ($mem.grouptype) {
			listUsers $mem
		} Else {
			[string]$username = $mem.cn
			[string]$groupname  = $group.cn
			[Boolean]$disable = $mem.psbase.invokeget("AccountDisabled")
			[string]$lastLogon = $(get-date 1/1/1601).adddays(($(&dsquery * $mem.distinguishedName -attr lastLogonTimestamp)[1].Trim())/(60*10000000)/1440)
 
			If (($xmlOutput.SelectNodes("/data/users[path='" + $mem.path + "']")).count -eq 0) {
				$root = $xmlOutput.CreateElement("users")
				$root.set_InnerXML("<username>"+$mem.cn+"</username><path>"+$mem.path+"</path><groups>"+$group.cn+"</groups><disabled>"+$disable+"</disabled><lastlogon>"+$lastLogon+"</lastlogon>")
				$xmlOutput.data.AppendChild($root) > $NULL
			}
			Else{
				$groups = $xmlOutput.SelectNodes("/data/users[path='" + $mem.path + "']/groups").item(0).get_innerText() + ", " + $group.cn
				$node = $xmlOutput.data.users | where {$_.path -eq $mem.path}
				$node.groups = $groups
			}
		}
	}
}
 
 
if ($args.count -lt 1) {
	Write-Host
	Write-Host "LIST USERS v1.0"
	Write-Host "Copyright (c) 2010 Weis Michal"
	Write-Host
	Write-Host "EXAMPLE: listGroups.ps1 ""cn=administrators,cn=builtin,dc=test,dc=local"""
	Write-Host
	exit
}
 
[string]$domain = "LDAP://" + $args[0]
$group = [ADSI] $domain
 
$xmlOutput = [xml] @"
< ?xml version="1.0" standalone="yes"?>
<data>
<users></users>
</data>
"@
Write-Host
listUsers $group
 
ForEach ($user in $xmlOutput.data.users) {
	If ($user.username) {
		Write-Host "Username: " $user.username.toUpper() -ForegroundColor Yellow
		Write-Host $user.path
		Write-Host "Groups :" $user.groups
		If ($user.disabled -eq "True") {
			Write-host "Account is disabled" -ForegroundColor Green
		} Else {
			Write-Host "Account is enabled"
		}
		Write-Host "Last logon:" $user.lastlogon
		Write-host
	}
}

How to write Powershell Cmdlet

http://msdn.microsoft.com/en-us/library/dd878294%28VS.85%29.aspx

Powershell remote registry

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function getRegKey () {
	param (
		[string]$serverName = $args[0],
		[string]$regKeyPath = $args[1],
		[string]$key = $args[2]
	)
 
	$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $serverName)
	$regKey = $reg.OpenSubKey($regKeyPath)
	return $regKey.GetValue($key)
}
 
function setRegKey () {
	param (
		[string]$serverName = $args[0],
		[string]$regKeyPath = $args[1],
		[string]$key = $args[2],
		[string]$value = $args[3]
	)
 
	$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $serverName)
	$regKey = $reg.OpenSubKey($regKeyPath,$true)
	$regKey.SetValue($key, $value)
}
 
getRegKey "nbweis" "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters" "SearchList"
setRegKey "nbweis" "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters" "SearchList" "blbost.cz"
getRegKey "nbweis" "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters" "SearchList"

Powershell Deep Dive

http://neuronspark.com/videos/powershell-deep-dive/

Better Tag Cloud