Добро пожаловать,
Гость
|
Всевозможные подсказки и напоминания по настройке Операционны систем и программ. Чтобы не забыть.
ТЕМА:
PowerShell 6 года 8 мес. назад #45
|
Мне часто приходится настраивать разного рода бот программы, то ли для себя доли для моих друзей. Очень часто у этих программ, то ли по моей вине (не понял синтаксис скрипта) то ли сыровата сама программа, некоторые функции не работают или работают не корректно. Потому мне приходится дополнять их сторонними скриптами. В большинстве случаев я использую PowerShell. Сказать что я сам их писал нельзя, собирались они мной со всех просторов интернета, и переписывались под свои нужды. Все они написаны в разрозненных файлах-скриптах, ну и как бывает рано или поздно некоторые из них теряются. Потому я решил собрать их в один файл функций, и поделится ними с Вами.
Вот они:
ВНИМАНИЕ: Спойлер!
[ Нажмите, чтобы развернуть ]
[ Нажмите, чтобы скрыть ]
function getscreen #Получить картинку с области экрана
{
param (
[Parameter (Mandatory = $true)]
[int] $PointX,
[Parameter (Mandatory = $true)]
[int] $PointY,
[Parameter (Mandatory = $true)]
[int] $width,
[Parameter (Mandatory = $true)]
[int] $height
)
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Position = New-Object System.Drawing.Point($PointX, $PointY)
$bitmap = New-Object System.Drawing.Bitmap($width, $height)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($Position,[Drawing.Point]::Empty, $bitmap.size)
$graphics.Dispose()
return $bitmap
}
#$img = getscreen 300 200
Function Resize-Image
{
param(
$image,
[int]$Width,
[int]$Height
)
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$ResizedImage = New-Object System.Drawing.Bitmap($Width, $Height)
$graphics = [Drawing.Graphics]::FromImage($ResizedImage)
$graphics.DrawImage($image, 0, 0, $Width, $Height)
$graphics.Dispose()
return $ResizedImage
}
function writescreentofile
{
param (
[Parameter (Mandatory = $true)]
$img,
[Parameter (Mandatory = $true)]
[string] $path
)
$img.Save($path,[System.Drawing.Imaging.ImageFormat]::jpeg)
}
#$img = getscreen 300 200
#writescreentofile $img "F:\Test\test.jpg"
function readscreenfromfile
{
param (
[Parameter (Mandatory = $true)]
[string] $path
)
$BitMap = [System.Drawing.Bitmap]::FromFile((Get-Item $path).fullname)
return $BitMap
}
#readscreenfromfile "F:\Test\test.jpg"
function getcolorpixelxy
{
param (
[Parameter (Mandatory = $true)]
[int] $X,
[Parameter (Mandatory = $true)]
[int] $Y,
[Parameter (Mandatory = $true)]
$img
)
$Pixel = $img.GetPixel($X,$Y)
$R = $Pixel | select -ExpandProperty R
$G = $Pixel | select -ExpandProperty G
$B = $Pixel | select -ExpandProperty B
$A = $Pixel | select -ExpandProperty A
return $Pixel.Name
}
#$img = getscreen 300 200
#getcolorpixelxy 102 118 $img
function getcolorcount #Получить количество пикселей определенного цвета
{
param (
[Parameter (Mandatory = $true)]
[string] $color,
[Parameter (Mandatory = $true)]
$BitMap
)
$countcolor = 0
Foreach($y in (1..($BitMap.Height-1)))
{
Foreach($x in (1..($BitMap.Width-1)))
{
$Pixel = $BitMap.GetPixel($X,$Y)
if($color -eq $Pixel.Name)
{
$countcolor = $countcolor + 1
}
}
}
return $countcolor
}
#$img = readscreenfromfile "F:\Test\test.jpg"
#getcolorcount "fffd5f11" $img
function findpixcolor #Найти пиксель определенного цвета
{
param (
[Parameter (Mandatory = $true)]
[string] $color,
[Parameter (Mandatory = $true)]
$BitMap
)
$Position = New-Object PsObject –Property @{
X = 0
Y = 0
}
Foreach($y in (1..($BitMap.Height-1)))
{
Foreach($x in (1..($BitMap.Width-1)))
{
$Pixel = $BitMap.GetPixel($X,$Y)
if($color -eq $Pixel.Name)
{
$Position.X = $X
$Position.Y = $Y
break
}
}
}
return $Position
}
#$img = readscreenfromfile "F:\Test\test.jpg"
#$position = findpixcolor "fffd5f11" $img
#$position.X
#$position.Y
function getimghash #Получить хеш области екрана
{
param (
[Parameter (Mandatory = $true)]
$bitmap
)
$tempfile = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
$bitmap.Save($tempfile, [System.Drawing.Imaging.ImageFormat]::jpeg)
$hash = Get-FileHash $tempfile -Algorithm MD5
remove-item $tempfile
return $hash.Hash
}
#getimghash 100 200
function windowsactivate #Активация окна по id процесса
{
param (
[Parameter (Mandatory = $true)]
[string] $procid
)
$shell = New-Object -com wscript.shell
$shell.AppActivate($procid)
}
#windowsactivate "11276"
function movecursor #Переместить курсор в координаты
{
param (
[Parameter (Mandatory = $true)]
[int] $X,
[Parameter (Mandatory = $true)]
[int] $Y
)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($X, $Y)
}
#movecursor 300 500
function ClickMouseButton #Нажатие кнопок мыши (left, right, middle)
{
param (
[Parameter (Mandatory = $true)]
[string] $button
)
$signature=@'
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@
$SendMouseClick = Add-Type -memberDefinition $signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru
if($button -eq "left")
{
$SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
}
if($button -eq "right")
{
$SendMouseClick::mouse_event(0x00000008, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x00000010, 0, 0, 0, 0);
}
if($button -eq "middle")
{
$SendMouseClick::mouse_event(0x00000020, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x00000040, 0, 0, 0, 0);
}
}
#[System.Windows.Forms.SendKeys]::SendWait({LEFT})
#sleep -Seconds 5
#ClickMouseButton left
#ClickMouseButton right
function findprocessid
{
param (
[Parameter (Mandatory = $true)]
[string] $name
)
$process = get-process |
where-object {$_.mainwindowhandle -ne 0 -and $_.MainWindowTitle -like "*$name*"} |
select-object id, name, mainwindowtitle
return $process.id
}
#findprocessid "android "
function WindowParam
{
param (
[Parameter (Mandatory = $true)]
[int] $id
)
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
}
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
"@
$Proc = Get-Process -id $id
$mainWindowHandle = $Proc.MainWindowHandle
$rcWindow = New-Object RECT
[Win32]::GetWindowRect($mainWindowHandle, [ref]$rcWindow)
return $rcWindow
}
#$Window = WindowParam 10432
#$Window.Left
#$Window.Top
function WebRequest
{
param (
[Parameter (Mandatory = $true)]
[string] $Url,
[Parameter (Mandatory = $true)]
$Metod,
[Parameter (Mandatory = $true)]
$postParams
)
$Result = Invoke-WebRequest -Uri $Url -Method $Metod -Body $postParams
return $Result
}
#$postParams = @{user='Admin'; password='monolit'; uid=101; confirm=1}
#$result = WebRequest "http://kdo.zzz.com.ua/confirm.php" POST $postParams
#$result.Content[0]
function vmsendkeycode
{
param (
[Parameter (Mandatory = $true)]
[string]$vmname,
[Parameter (Mandatory = $true)]
[string]$keycode
)
$ComputerSystem = Get-WmiObject -Query "select * from Msvm_ComputerSystem where ElementName = '$vmname'" -Namespace "root\virtualization\v2"
$Keyboard = Get-WmiObject -Query "ASSOCIATORS OF {$($ComputerSystem.path.path)} WHERE resultClass = Msvm_Keyboard" -Namespace "root\virtualization\v2"
$Keyboard.InvokeMethod("TypeKey", $keycode)
}
#VirtualKeyCode: https://www.indigorose.com/webhelp/ams/Program_Reference/Misc/Virtual_Key_Codes.htm
#vmsendkeycode "android" "13"
function vmsendtext
{
param (
[Parameter (Mandatory = $true)]
[string]$vmname,
[Parameter (Mandatory = $true)]
[string]$text
)
$ComputerSystem = Get-WmiObject -Query "select * from Msvm_ComputerSystem where ElementName = '$vmname'" -Namespace "root\virtualization\v2"
$Keyboard = Get-WmiObject -Query "ASSOCIATORS OF {$($ComputerSystem.path.path)} WHERE resultClass = Msvm_Keyboard" -Namespace "root\virtualization\v2"
$Keyboard.InvokeMethod("TypeText", "$text")
}
function vmsendtext_alternative
{
param (
[Parameter (Mandatory = $true)]
[string]$vmname,
[Parameter (Mandatory = $true)]
[string] $text
)
$ComputerSystem = Get-WmiObject -Query "select * from Msvm_ComputerSystem where ElementName = '$vmname'" -Namespace "root\virtualization\v2"
$Keyboard = Get-WmiObject -Query "ASSOCIATORS OF {$($ComputerSystem.path.path)} WHERE resultClass = Msvm_Keyboard" -Namespace "root\virtualization\v2"
$chars = $text.ToCharArray()
foreach($char in $Chars)
{
$keycode = [int][char]$char
$Keyboard.InvokeMethod("TypeKey", $keycode)
sleep -Milliseconds 30
}
}
#vmsendtext_alternative "android" "Text 123" |
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.
Последнее редактирование: от Дмитрий.
|
PowerShell 6 года 8 мес. назад #46
|
Это наверно производный пост от предыдущего
Пока я собирал скрипты в один файл функций то подумал, а зачем я вообще мучаюсь с разного рода Бот-программами, когда под рукой есть действительно мощный язык сценариев как PowerShell. Ах, ну да, в них есть (худо бедный) интерфейс для получения, в реальном времени, координат, цвета пикселя области экрана и тд. Но немного (в очередной раз) погуглив, я понял что и это не является проблемой для PowerShell, он тоже умеет GUI. Ну и собрал по быстрому небольшое GUI-интерфейс для написания бот программ. Работает оно совместно с файлом функций. Вот оно:
ВНИМАНИЕ: Спойлер!
[ Нажмите, чтобы развернуть ]
[ Нажмите, чтобы скрыть ]
$path = $PSScriptRoot
try {
.("$path\function.ps1")
}
catch {
Write-Host "Error while loading supporting PowerShell Scripts"
}
function StopScan
{
$hash.flag = $true
$button.Enabled = $true
}
$hash = [hashtable]::Synchronized(@{})
$hash.flag = $false
Add-Type -assembly System.Windows.Forms
$main_form = New-Object System.Windows.Forms.Form
$main_form.Text="Settings"
$main_form.Size = New-object System.Drawing.Size(300, 300)
$main_form.AutoSize = $true
$main_form.AutoSizeMode =[System.Windows.Forms.AutoSizeMode]::GrowOnly
$TextBox = New-Object System.Windows.Forms.TextBox
$TextBox.Location = New-Object System.Drawing.Point(5,5)
$TextBox.Size = New-object System.Drawing.Size(100, 30)
$TextBox.Text = $TextBox.BackColor.Name
$main_form.Controls.Add($TextBox)
$button = New-Object System.Windows.Forms.Button
$button.Text = 'StartScan'
$button.Location = New-Object System.Drawing.Point(($TextBox.Left + $TextBox.Width + 5), 5)
$button.Size = New-object System.Drawing.Size(80, $TextBox.Height)
$main_form.Controls.Add($button)
$buttonStop = New-Object System.Windows.Forms.Button
$buttonStop.Text = 'StopScan'
$buttonStop.Location = New-Object System.Drawing.Point(($button.Left + $button.Width + 5), 5)
$buttonStop.Size = New-object System.Drawing.Size(80, $button.Height)
$main_form.Controls.Add($buttonStop)
$PictureBox = New-Object System.Windows.Forms.PictureBox
$PictureBox.Location = New-Object System.Drawing.Point(5, ($TextBox.Top + $TextBox.Height + 5))
$PictureBox.BackColor = 'White'
$PictureBox.Width = 100
$PictureBox.Height = 100
$main_form.Controls.add($PictureBox)
$ComboBox = New-Object System.Windows.Forms.ComboBox
$ComboBox.DataSource = @(2,4,6,8,10)
$ComboBox.Width = 40
$ComboBox.Location = New-Object System.Drawing.Point(($PictureBox.Left + $PictureBox.Width + 5), $PictureBox.Top)
$main_form.Controls.Add($ComboBox)
#-------------------------------------------------------------------
$Label_Width = New-Object System.Windows.Forms.Label
$Label_Width.Text = "Width: "
$Label_Width.Location = New-Object System.Drawing.Point(5, ($PictureBox.Top + $PictureBox.Height + 5))
$Label_Width.AutoSize = $true
$main_form.Controls.Add($Label_Width)
$TextBox_Width = New-Object System.Windows.Forms.TextBox
$TextBox_Width.Location = New-Object System.Drawing.Point(($Label_Width.Left + $Label_Width.Width + 5),($PictureBox.Top + $PictureBox.Height + 5))
$TextBox_Width.Size = New-object System.Drawing.Size(50, 30)
$TextBox_Width.Text = '100'
$main_form.Controls.Add($TextBox_Width)
$Label_Height = New-Object System.Windows.Forms.Label
$Label_Height.Text = "Height: "
$Label_Height.Location = New-Object System.Drawing.Point(5, ($Label_Width.Top + $Label_Width.Height + 5))
$Label_Height.AutoSize = $true
$main_form.Controls.Add($Label_Height)
$TextBox_Height = New-Object System.Windows.Forms.TextBox
$TextBox_Height.Location = New-Object System.Drawing.Point(($Label_Width.Left + $Label_Width.Width + 5),($Label_Width.Top + $Label_Width.Height + 5))
$TextBox_Height.Size = New-object System.Drawing.Size(50, 30)
$TextBox_Height.Text = '100'
$main_form.Controls.Add($TextBox_Height)
$Label_left = New-Object System.Windows.Forms.Label
$Label_left.Text = "Left: "
$Label_left.Location = New-Object System.Drawing.Point(5, ($Label_Height.Top + $Label_Height.Height + 5))
$Label_left.AutoSize = $true
$main_form.Controls.Add($Label_left)
$TextBox_left = New-Object System.Windows.Forms.TextBox
$TextBox_left.Location = New-Object System.Drawing.Point(($Label_Width.Left + $Label_Width.Width + 5), ($Label_Height.Top + $Label_Height.Height + 5))
$TextBox_left.Size = New-object System.Drawing.Size(50, 30)
$TextBox_left.Text = '100'
$main_form.Controls.Add($TextBox_left)
$Label_top = New-Object System.Windows.Forms.Label
$Label_top.Text = "Top: "
$Label_top.Location = New-Object System.Drawing.Point(5, ($TextBox_left.Top + $Label_left.Height + 5))
$Label_top.AutoSize = $true
$main_form.Controls.Add($Label_top)
$TextBox_top = New-Object System.Windows.Forms.TextBox
$TextBox_top.Location = New-Object System.Drawing.Point(($Label_Width.Left + $Label_Width.Width + 5), ($Label_left.Top + $Label_left.Height + 5))
$TextBox_top.Size = New-object System.Drawing.Size(50, 30)
$TextBox_top.Text = '100'
$main_form.Controls.Add($TextBox_top)
$button_region = New-Object System.Windows.Forms.Button
$button_region.Text = 'GetRegion'
$button_region.Location = New-Object System.Drawing.Point(5, ($TextBox_top.Top + $TextBox_top.Height + 5))
$button_region.Size = New-object System.Drawing.Size(95, 20)
$main_form.Controls.Add($button_region)
$PictureBox_xy = New-Object System.Windows.Forms.PictureBox
$PictureBox_xy.Location = New-Object System.Drawing.Point(($TextBox_Width.Left + $TextBox_Width.Width + 5), ($PictureBox.Top + $PictureBox.Height + 5))
$PictureBox_xy.BackColor = 'White'
$PictureBox_xy.Width = 175
$PictureBox_xy.Height = 110
$main_form.Controls.add($PictureBox_xy)
$Label_hash = New-Object System.Windows.Forms.Label
$Label_hash.Text = "ImageHash: "
$Label_hash.Location = New-Object System.Drawing.Point(5, ($PictureBox_xy.Top + $PictureBox_xy.Height + 5))
$Label_hash.AutoSize = $true
$main_form.Controls.Add($Label_hash)
$TextBox_hash = New-Object System.Windows.Forms.TextBox
$TextBox_hash.Location = New-Object System.Drawing.Point(($Label_hash.Left + $Label_hash.Width + 5), ($PictureBox_xy.Top + $PictureBox_xy.Height + 5))
$TextBox_hash.Size = New-object System.Drawing.Size(202, 60)
$textbox_hash.WordWrap = $true
$TextBox_hash.Text = ''
$main_form.Controls.Add($TextBox_hash)
#----------------------------------------------------------------------
$TextBox2 = New-Object System.Windows.Forms.TextBox
$TextBox2.Location = New-Object System.Drawing.Point(5, ($main_form.Height - 5))
$TextBox2.Size = New-object System.Drawing.Size(100, 30)
$TextBox2.Text = 'Title name'
$main_form.Controls.Add($TextBox2)
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "X:0|Y:0"
$Label.Location = New-Object System.Drawing.Point(($TextBox2.Left + $TextBox2.Width + 5), ($TextBox2.Top + 5))
$Label.AutoSize = $true
$main_form.Controls.Add($Label)
$button_region.Add_Click({
if($TextBox2.Text -eq '')
{
$image = getscreen $TextBox_left.Text.ToInt32($Null) $TextBox_top.Text.ToInt32($Null) $TextBox_Width.Text.ToInt32($Null) $TextBox_Height.Text.ToInt32($Null)
}
else
{
$name = $TextBox2.Text
$processid = findprocessid "$name "
$windowParam = WindowParam $processid
$image = getscreen ($TextBox_left.Text.ToInt32($Null) + $windowParam.left) ($TextBox_top.Text.ToInt32($Null) + $windowParam.top) $TextBox_Width.Text.ToInt32($Null) $TextBox_Height.Text.ToInt32($Null)
}
$PictureBox_xy.Image = $image
$TextBox_hash.Text = getimghash $image
})
$button.Add_Click({
$hash.flag = $false
$button.Enabled = $false
$runspace = [runspacefactory]::CreateRunspace()
$runspace.Open()
$runspace.SessionStateProxy.SetVariable('Hash',$hash)
$runspace.SessionStateProxy.SetVariable('label',$label)
$runspace.SessionStateProxy.SetVariable('TextBox',$TextBox)
$runspace.SessionStateProxy.SetVariable('TextBox2',$TextBox2)
$runspace.SessionStateProxy.SetVariable('PictureBox',$PictureBox)
$runspace.SessionStateProxy.SetVariable('ComboBox',$ComboBox)
$runspace.SessionStateProxy.SetVariable('path',$path)
$powershell = [powershell]::Create()
$powershell.Runspace = $runspace
$powershell.AddScript({
try {
.("$path\function.ps1")
}
catch {
Write-Host "Error while loading supporting PowerShell Scripts"
}
While($true)
{
if($hash.flag -eq $true)
{
break
$powershell.Runspace.close()
$powershell.Dispose()
}
$Pos = [System.Windows.Forms.Cursor]::Position
if($TextBox2.Text -eq '')
{
$Label.Text = "X:" + $Pos.X + "|Y:" + $Pos.Y
}
else
{
$name = $TextBox2.Text
$processid = findprocessid "$name "
$windowParam = WindowParam $processid
$Label.Text = "X:" + ($Pos.X - $windowParam.Left) + "|Y:" + ($Pos.Y - $windowParam.Top)
}
$zoom = $ComboBox.SelectedValue
$zoomimg = (100 / $zoom)
$bitmap = getscreen ($Pos.X - ($zoomimg / 2)) ($Pos.Y - ($zoomimg / 2)) $zoomimg $zoomimg
$img = Resize-Image $bitmap ($bitmap.Width * $zoom) ($bitmap.Height * $zoom)
for($i=0; $i -lt 5; $i++)
{
$img.SetPixel((($img.Width / 2) - $i), ($img.Height / 2), [System.Drawing.Color]::FromArgb(000, 000, 000))
$img.SetPixel((($img.Width / 2) + $i), ($img.Height / 2), [System.Drawing.Color]::FromArgb(000, 000, 000))
$img.SetPixel(($img.Width / 2), (($img.Height / 2) - $i), [System.Drawing.Color]::FromArgb(000, 000, 000))
$img.SetPixel(($img.Width / 2), (($img.Height / 2) + $i), [System.Drawing.Color]::FromArgb(000, 000, 000))
}
$PictureBox.Image = $img
$color = getcolorpixelxy ($bitmap.Width / 2) ($bitmap.Height / 2) $bitmap
$TextBox.BackColor = '#' + $color
$TextBox.Text = $TextBox.BackColor.Name
Start-Sleep -Milliseconds 100
}
})
$AsyncResult = $powershell.BeginInvoke()
})
$buttonStop.Add_Click({StopScan})
$main_form.ShowDialog() |
Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе. |
Модераторы: Дмитрий