- Для старых Windows(7 / 8) установить обновление.
Можно писать одновременно как на lua, так и на PoSh внутри одного скрипта.
PoSh очень гибкий и компактный язык. Все его возможности доступны без необходимости установки дополнительных модулей (за исключением, кончено, специфических потребностей).
Примеры компактности языка:
№1
задача
Вот еще задачка. нужно найти все комментарии однострочные и многострочные, но данная регулярка не совсем корректно находит многострочные комментарии. Всего комментариев 7(для наглядности в тексте примера их пронумеровал и отметил жиром) из них: 5 однострочных и 2 многострочных
Вот рег: <!--(.+|(.|\s)*)-->
Вот пример текста:
<!--1 однострочный коментарий-->
текст <!-- 2 Это -- комментарий -->
текст
<!-- 3 многострочный
коментарий
текст какой-то--> текст
Эт0
к0д
какой-то
<!-- 4
это еще один
ногострочный
коментарий
--> текст
<!-- 5 это считается коментарием <!-- и это коментарием --> а этот текст уже нет-->
<!-- 6 --><!--7-->Решение на Pilot (только для Ansi, так как с utf pilot не работает вовсе)Кодlog clear_current
log mode compact
load_array %a C:\1.txt
for #i 1 size(%a)
set $a %a[#i]
while regexp(#p $r $a <!--.*?(-->|$))
log $r
while copy($r eval(size($r)-2) 3) != -->
set #i #i + 1
set $a %a[#i]
if regexp(#p $r $a ^.*?-->)
log $r
break
end_if
log %a[#i]
end_while
set $a string_replace($a $r "")
end_while
end_for
log save_current C:\2.txt
end_scriptРешение на luaКод--lua
log "clear" log "mode compact"
package.path = "LuaPlugins\\winapi\\?.lua;" .. package.path
package.path = "LuaPlugins\\?.lua;" .. package.path
setfenv(1, require'winapi')
require'utf8'
local s = readfile([[C:\1.txt]])
local f2 = io.open([[C:\2.txt]], "wb")
if s and f2 then
for w in s:gmatch("<%!%-%-.-%-%->") do
log (w .. "\r\n")
f2:write(w .. "\r\n")
end
f2:close()
end
exec ("notepad.exe", [[C:\2.txt]])
end_script ()
Решение на LuaPoSh. Сам код на ps занимает всего одну строку.
Исходная кодировка текста может быть как юникод, так и Ansi.--lua
require "LuaPoSh";PScode('void',{[[#}
#
[regex]::Matches((Get-Content C:\1.txt), '<!--.+?-->').value > C:\2.txt;C:\2.txt
#
]]})
№2
задача
Hello everyone. I have a problem with showwindow() state commands.
In the wiki page are given only these states:КодHIDE: спрятать окно
MAXIMIZE: развернуть во весь экран
MINIMIZE: свернуть
RESTORE: развернуть
SHOW: показать
TOP: вытащить на поверхность.
My question is: Are there any other states which I can use, because none of these worked for my problem?
I am trying to minimize and restore given window in windows 10 virtual desktops, without switching between the desktops automatically. I need more like a popup state. When I use RESTORE or MAXIMIZE state, it switches to the virtual desktop where the window is located automatically.Решение на luaКод--lua
package.path = "LuaPlugins\\winapi\\?.lua;" .. package.path
package.path = "LuaPlugins\\glue\\?.lua;" .. package.path
setfenv(1, require'winapi')
require[[winapi.winuser]]
local ffi = require("ffi")
ffi.cdef[[
BOOL ShowWindow(int hWnd, int nCmdShow);
]]
local SW_SHOWNOACTIVATE = 4
hndl=findwindow ("Калькулятор")
C.ShowWindow(hndl[1][1], SW_SHOWNOACTIVATE)
Решение на LuaPoSh. Сам код на ps занимает всего одну строку.--lua
require "LuaPoSh";PScode('void',{[[#}
#
WinApi ShowWindow([int]$input, 4)
#
]]}, findwindow("Калькулятор")[1][1])
№3
задача
в папке D\3 находятся папки с фото,нужно оставить только файлы jpg которые больше 100х100 пиксРешение на luaКод--lua
local ffi = require('ffi')
local gdip = ffi.load('Gdiplus.dll')
local CP_ACP = 0
ffi.cdef[[
typedef unsigned int UINT;
typedef unsigned long DWORD;
typedef struct {UINT GdiplusVersion; int DebugEventCallback; bool SuppressBackgroundThread; bool SuppressExternalCodecs;} GdiplusStartupInput, *pGdiplusStartupInput;
bool DeleteFileA(const char *lpFileName);
int GdiplusStartup(int *token, pGdiplusStartupInput GdiplusStartupInput, int *output);
int GdiplusShutdown(int token);
int GdipDisposeImage(int image);
int GdipLoadImageFromFile(const wchar_t *filename, int *image);
int GdipGetImageWidth(int image, UINT *width);
int GdipGetImageHeight(int image, UINT *height);
int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, const char *lpMultiByteStr, int cbMultiByte, wchar_t *lpWideCharStr, int cchWideChar);
]]
function image_size(path)
local buf = ffi.new('wchar_t[?]', #path+1)
local StartupInput = ffi.new('GdiplusStartupInput', {1, 0, 0, 0})
local token, image, w, h = ffi.new('int[1]'), ffi.new('int[1]'), ffi.new('int[1]'), ffi.new('int[1]')
ffi.C.MultiByteToWideChar(CP_ACP, 0, path, #path, buf, ffi.sizeof(buf))
gdip.GdiplusStartup(token, StartupInput, nil)
gdip.GdipLoadImageFromFile(buf, image)
gdip.GdipGetImageWidth(image[0], w)
gdip.GdipGetImageHeight(image[0], h)
gdip.GdipDisposeImage(image[0])
gdip.GdiplusShutdown(token[0])
return w[0], h[0]
end
log 'clear' log 'mode compact'
local path = [[D:\3]] -- путь к папке
local resultarray, count = dir (path, "*.bmp;*.jpg") -- получить список всех файлов в формате bmp и jpg
log ("Найдено файлов: " .. count)
if count then -- если файлы найдены
for i=1, #resultarray do
local width, height = image_size( resultarray[i][1] )
log(resultarray[i][1].. '\tШирина: ' .. tostring(width) .. '\t'.. 'Высота: ' .. tostring(height)) -- размеры картинки
if width < 100 and height < 100 then -- если ширина и высота меньше 100
ffi.C.DeleteFileA( resultarray[i][1] ) -- удалить файл
end
end
end
local resultarray, count = dir (path, "*.?*") -- получить список всех файлов
log ("Найдено файлов: " .. tostring(count))
if count then -- если файлы найдены
for i=1, #resultarray do
if resultarray[i][4] ~= '.jpg' then -- если не jpg
log('Удаление файла: ' .. resultarray[i][1])
ffi.C.DeleteFileA( resultarray[i][1] ) -- удалить файл
end
end
end
Решение на LuaPoSh. Сам код на ps в 5 раза короче и проще, чем на lua.--lua
require "LuaPoSh";PScode('void',{[[#}
#
$path = 'D:\3'
function Check-PicSize($p){#}
$img = [Drawing.Image]::FromFile( $p.fullname )
if($img.width -gt 100 -and $img.Height -gt 100)
{$img.Dispose(); $true}else{$img.Dispose(); $false}
}
Get-ChildItem $path -file -rec|ForEach{#}
if(!($_.Extension -eq '.jpg' -and (Check-PicSize $_)))
{ri $_.FullName}
}
#
]]})
Также на PoSh можно создавать задачи в планировщике, редактировать word/excel документы, читать excel по строкам, столбцам, книгам, менять значения в реестре, можно использовать классы и методы .Net, писать в нем на c#...в общем всего не перечислить, а большинство повседневных задач решаются в паре строчек кода.