Резервное копирование баз MS SQL с помощью PowerShell Сергей Горбановский msbp.exe backup "db(database=model)" "zip64(level=9;filename=model.bak)" "local(path=D:\SQL_Backup\model.zip)" Get-WMIObject -Class "Win32_PerfFormattedData_MsSqlServer_SqlServerDatabases" –Computer 'ServerName' $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=ServerName; Database=Master;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = "SELECT name FROM master..sysdatabases" $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet) $SqlConnection.Close() $DataSet.Tables[0] SELECT name FROM master..sysdatabases Invoke-Sqlcmd -Query "SELECT name FROM master..sysdatabases" -ServerInstance "ServerName" Get-ChildItem SqlServer:\SQL\ServerName\Default\Databases cd SqlServer:\SQL\ServerName\Default\Databases dir [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') $SqlSmo = New-Object ('Microsoft.SqlServer.Management.SMO.Server') 'ServerName\InstanceName' $SqlSmo.Databases Param( [string]$iniFile ) if ($script:IniFile) { $script:defIniFile = NormalizePath $script:IniFile } else { $script:defIniFile = Join-Path -Path $script:SDirPath -ChildPath $SBaseFileName".ini" } function LoadAssembly ([string]$Assembly) { Write-Log "Загружаем сборку $Assembly" # Загружаем указанную сборку, вызывая метод из .Net $Asm = [Reflection.Assembly]::LoadWithPartialName($Assembly) # Проверяем загрузку сборки if ($Asm) { Write-Log "Сборка загружена: $($Asm.GetName().Name), версия $($Asm.GetName().Version)" return $Asm } else { Write-Log "Не удалось загрузить сборку $Assembly" return $false } } if (!(LoadAssembly "Microsoft.SqlServer.Smo")) { Write-Log "Не удалось загрузить SQL System Management Objects" Write-Log "Общее время выполнения: $($ElapsedTime.Elapsed.ToString())" Exit } $SqlServer = New-Object ("Microsoft.SqlServer.Management.SMO.Server") $Instance $DbList = $SqlServer.Databases | Select-Object Name, Status, IsSystemObject [array]$Preload ="Status", "IsSystemObject" $StrCol = New-Object System.Collections.Specialized.StringCollection $StrCol.AddRange($Preload) $SqlServer.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Database], $StrCol) $SqlServer= Get-Item SqlServer:\SQL\ServerName\Default [array]$Preload ="Status", "IsSystemObject" $StrCol = New-Object System.Collections.Specialized.StringCollection $StrCol.AddRange($Preload) $SqlServer.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Database], $StrCol) $SqlServer.Databases | Select Name, Status, IsSystemObject $BackupJob = Start-Process -FilePath $script:BackupExe -ArgumentList $LaunchString -NoNewWindow -Wait –PassThru if ($BackupJob.ExitCode) { Write-Log "Произошла ошибка при бэкапе $DbName" } else { Write-Log "Бэкап базы $DbName занял $BackupTime" } [Backup] Instance= BackupPath=C:\SQL_Backup\Backup MaxBackupsActive=3 MaxBackupsInactive=3 BackupMode=List DbListFile=.\DB_List.txt CompType=zip64 CompLevel=9 LazyMode=1 OfflineDb=1 BackupExe=.\MSSQLCB\msbp.exe [Email] SendEmail=1 Sender=SqlBackup@mycompany.ru Receipt=admin@mycompany.ru Server=mail.mycompany.ru Login=sqlbackup Password=password Port=25 SSL=0 TrustAnyCert=0 ----------------------------------------------------------------------------------------------------------------- PowerShell – управление Exchange Server. Несколько полезных советов для сомневающихся Сергей Барамба Get-Command -Noun *Mailbox* Get-Mailbox | Get-Member Get-Help Get-Mailbox – Examples Get-Help <имя командлета> с ключом Detailed Get-Mailbox admin | fl *quo* Get-Item -Path alias: Test-ServiceHealth -Server [SERVER_FQDN] Start-Service IISAdmin Get-MailboxDatabase -Server | ft name,*mou* Get-MailboxDatabase -Server -Status | ft name,*mou* Set-Mailbox -Identity [username] -RulesQuota 256Kb Get-Mailbox | Measure | FT Count –auto Set-UserPhoto username -PictureData([System.IO.File]::ReadAllBytes("x:\username.png")) Set-UserPhoto username -Save @{expression={$_.FolderSize.ToMB()};label="FolderSize (MB)"} ) get-mailbox | Get-MailboxFolderStatistics | sort FolderSize -descending | select Name, FolderPath, ItemsInFolder, (@{expression={$_.FolderSize.ToMB()}; label="FolderSize (MB)"} ) | Export-Csv c:\report.csv -Encoding utf8 -NoTypeInformation Set-Executionpolicy -ExecutionPolicy Unrestricted -NonInteractive -WindowStyle Hidden -command ". 'C:\Program Files\Microsoft\Exchange Server\V15\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto;X:\.ps1" -version 2.0 -NonInteractive -WindowStyle Hidden -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; <Команда или Скрипт>" Get-Mailbox | Out-GridView -PassThru | Set-Mailbox -ProhibitsendQuota 1GB Get-Mailbox | select identity,alias,*quota* | Out-GridView -PassThru | Set-Mailbox -ProhibitsendQuota 1GB Get-Process | Out-GridView -PassThru | Export-Csv -Path .\ProcessLog.csv Get-ExchangeServer | Select identity, serverrole, site, networkaddress | Out-GridView -PassThru | Get-Mailboxdata | fl FQD ----------------------------------------------------------------------------------------------------------------- Pluggable Authentication Modules. Использование для ваших нужд Рашид Ачилов <тип модуля> <флаг результата> <путь и имя модуля> <аргументы> auth required pam_unix.so no_warn try_first_pass account required pam_unix.so auth required pam_unix.so no_warn try_first_pass auth required pam_group.so group=staff luser account required pam_unix.so auth sufficient pam_unix.so no_warn try_first_pass local_pass debug auth required pam_ldap.so use_first_pass account sufficient pam_unix.so auth required pam_group.so group=staff luser auth sufficient pam_unix.so no_warn try_first_pass local_pass debug auth required pam_group.so group=winstaff luser auth required pam_ldap.so use_first_pass account sufficient pam_unix.so auth sufficient pam_unix.so no_warn try_first_pass local_pass debug auth required pam_ldap.so use_first_pass account sufficient pam_unix.so account required pam_mkhome.so mode=0700 session required pam_mkhome.so mode=0700 ----------------------------------------------------------------------------------------------------------------- Инвентаризация ПК с помощью MS SCCM 2012 SP1 Сергей Болдин Листинг 1. Запрос на выборку SELECT T1.ResourceID, T1.Name0 AS [PC Name], (SELECT T2.Name0 AS 'data()' FROM dbo.v_GS_PC_BIOS T2 WHERE T2.ResourceID=T1.ResourceID FOR xml path('')) AS BIOS, //…и т.д. //Добавляю редактируемые поля (SELECT T20.[Inv Nom PC] AS 'data()' FROM dbo.v_INVENTORY_HARD_EDIT T20 WHERE T20.ResourceID=T1.ResourceID FOR xml path('')) AS [Inv Nom PC], (SELECT T21.Garantiya AS 'data()' FROM dbo.v_INVENTORY_HARD_EDIT T21 WHERE T21.ResourceID=T1.ResourceID FOR xml path('')) AS Garantiya FROM dbo.v_INVENTORY_HARDWARE T1 Листинг 2. Подключение библиотек и файлов Inventory PC Листинг 3. Код PHP для связи с запросом в БД Листинг 4. PHP-код для обновления данных ----------------------------------------------------------------------------------------------------------------- Готовимся к «1С:Эксперт Олег Филиппов Create Database TestDB CREATE TABLE TestTable( ID int NOT NULL, Value nvarchar(10)) insert into TestTable values(1, 'str1') use TestDB; set transaction isolation level Serializable begin transaction update TestTable set Value = 'str2' where ID = 1 commit use TestDB; set transaction isolation level Serializable begin transaction Select * from TestTable Commit exec sp_lock ----------------------------------------------------------------------------------------------------------------- Основы Node.js – Node Core Кирилл Сухов > global.foo = 2 > console.log(global) > bar = 7 > console.log('Price: %d', bar); console.time('items'); for (var i = 0; i < 1000000000; i++) { // что-нибудь делаем } console.timeEnd('1000000000-items'); for (var i = 0; i < 100; i++) { console.trace() } console.log(process.execPath); console.log(process.version); console.log(process.platform); console.log(process.arch); console.log(process.title); console.log(process.pid); C:\Users\Geol>node process.js C:\Program Files\nodejs\node.exe process.argv.forEach(function(val, index, array) { console.log(index + ' - ' + val); }); C:\Users\Geol>node process.js foo bar 1 process.on('exit', function () { setTimeout(function() { // Этот код никогда не запустится! console.log('This will not run'); },0); console.log('Exit.'); }); process.stdin.resume(); process.on('SIGTSTP', function() { console.log('Interrupted'); process.exit(1); }); process.on('SIGHUP', function() { console.log('Got a SIGHUP'); }); setInterval(function() { console.log('Running'); }, 10000); console.log('PID:', process.pid); kill -s SIGHUP 5772 process.stdin.resume(); process.on('SIGINT', function() { console.log('Got a SIGINT!'); process.exit(1); }); console.log(process.memoryUsage()); process.nextTick(function () { console.log('Test'); }); console.log(process.memoryUsage()); C:\Users\Geol>node process.js process.nextTick(function() { console.log('nextTick callback'); }); buf = new Buffer(256, 'utf8'); text = '\u00bd + \u00bc = \u0D75'; len = buf.write(text , 0, text.length); console.log(len + " bytes: " + buf.toString('utf8', 0, len)); C:\Users\Geol\node>node ts1.js buf = new Buffer('test'); console.log(buf.toJSON()); buf = new Buffer([01,02,03,04,05]); console.log(buf); console.log(buf[4]); buffer1 = new Buffer(24); buffer2 = new Buffer(16 ); for (var i = 0 ; i < 24 ; i +=4) { buffer1[i] = 78; buffer1[i+1] = 111; buffer1[i+2] = 100; buffer1[i+3] = 101; } for (var i = 0 ; i < 16 ; i++) { buffer2[i] = 42; // ASCII * } buffer1.copy(buffer2, 6, 16, 20); console.log(buffer2.toString('ascii')); var buffer2 = buffer1.slice(0, 3); console.log(buffer2.toString('ascii', 0, buffer2.length)); buffer2[0] = 33; console.log(buffer1.toString('ascii', 0, buffer1.length)); var tid; function toConsole(n) { console.log(n); tid = setTimeout(toConsole, 1000, n+1); if(n > 5){ clearTimeout(tid); } } toConsole(0); C:\Users\Geol\node>node newNode1.js var tid; function toConsole() { console.log(n); n++; if(n > 5){ clearInterval(tid); } } var n = 0; tid = setInterval(toConsole, 1000); ----------------------------------------------------------------------------------------------------------------- Искусство создания сценариев на PowerShell. Часть 2 Иван Коробко Листинг 1. Чтение данных из XML-файла $ScriptName=$null $XMLName=$null if ($Host.Name -like "ConsoleHost") { [string]$ScriptName=$MyInvocation.InvocationName [string]$XMLName=$ScriptName -replace "ps1", "xml" Write-Host $XMLName [xml]$objXML=Get-Content .\$ScriptName #Чтение XML-файла Write-host $obj.root.enable ... } else { Write-Host "Ошибка: Некорректное имя хоста." } Листинг 2. Пример функции автоматической замены значений Function Freplace{ #Имя пользователя в сети $ReplaceUserLogin = (Get-Item env:USERNAME).value #Имя текущего домена $ReplaceUserDomain = (Get-Item env:USERDOMAIN).value #Определение списка групп, членом которых является #пользователь. Фильтрация по префиксу (LABEL) $root=[ADSI]'LDAP://RootDSE' $objUser = New-Object DirectoryServices.Directorysearcher("LDAP://{0}" -f $root.defaultNamingContext) $objUser.filter=("(&(samaccountname={0}) ↵ (objectclass=person))" -f $ReplaceUserLogin) $result=$objUser.findone() $ReplaceUserFIO=[string]$result.properties.description $dnpath=([string]$result.properties.distinguishedname).split(",") $ReplaceUserdepartment = $dnpath[2] -replace("OU=", "") foreach ($a in $args) { $args $temp= New-Object System.Text.StringBuilder $ArFrom = '$fio', '$domain', '$department', '$login' $ArTo = $ReplaceUserFIO,$ReplaceUserDomain, $ReplaceUserdepartment,$ReplaceUserLogin for ($i=0; $i -lt ($ArFrom.length); $i++) { try{ if ($a -like ("*"+$ArFrom[$i]+"*")) { $temp=$a.toupper() $a=$temp.Replace($ArFrom[$i].toupper(),$ArTo[$i]) } } catch{} }} return $a.tolower() #Возвращаемое значение } [xml]$objXML=Get-Content .\$ScriptName #Чтение XML-файла … Freplace | objXML.root.Department Листинг 3. Пример формирования простейшего PSObejct $b=@() $c = 1,2,3 foreach ($e in $c) { $g = New-Object PSObject Add-Member -InputObject $g -value $e -name ([string]"столбец-1") -MemberType "noteproperty" Add-Member -InputObject $g -value ($e+1) -name ([string]"столбец-2") -MemberType "noteproperty" $b+=$g } $b | Out-GridView Листинг 4а. Чтение и обработка данных учетной записи пользователя #Обращение к учетной записи пользователя по GUID $uGUID="71 F1 8A 66 58 89 C4 4F AD 46 CE 5D 4F 30 2C 69".replace(" ","") $user = [ADSI]("LDAP://" -f $uGUID) #Чтение данных учетной записи в переменные $name = "{0} {1}" -f [string]$user.sn, [string]$user.givenName $login = $user.sAMAccountName $department = $user.department $title = $user.title $mail = $user.mail $tlf = $user.telephoneNumber $room = $user.physicalDeliveryOfficeName Листинг 4б. Формирование списка пользователей и PSObject #Поиск учетных записей пользователей в контейнере $oGUID="C9 DB E6 E7 6C C3 1B 46 A8 0E 27 F2 B7 2A 57 23".replace(" ","") $ou = [ADSISEARCHER]'' $ou.SearchRoot = [ADSI]("LDAP://" -f $oGUID) $ou.Filter = "(&(objectclass=person)(!(objectclass=computer)))" $results = $ou.FindAll() # Результаты поиска $obj=@() #Чтение данных из массива foreach ($result in $results) { #Чтение данных учетной записи в переменные $user = $result.GetDirectoryEntry() $name = "{0} {1}" -f [string]$user.sn, [string]$user.givenName $login = $user.sAMAccountName $department = $user.department $title = $user.title $mail = $user.mail $tlf = $user.telephoneNumber $room = $user.physicalDeliveryOfficeName #Создание PSObject $ps = New-Object PSObject #Запись данных в объект Add-Member -InputObject $ps -MemberType NoteProperty -Name "Имя" -Value ([string]$name) Add-Member -InputObject $ps -MemberType NoteProperty -Name "Имя в сети" -Value ([string]$login) Add-Member -InputObject $ps -MemberType NoteProperty -Name "Должность" -Value ([string]$title) Add-Member -InputObject $ps -MemberType NoteProperty -Name "Подразделение" -Value ([string]$department) Add-Member -InputObject $ps -MemberType NoteProperty -Name "Почта" -Value ([string]$mail) Add-Member -InputObject $ps -MemberType NoteProperty -Name "Телефон" -Value ([string]$tlf) Add-Member -InputObject $ps -MemberType NoteProperty -Name "Комната" -Value ([string]$room) $obj+=$ps } Листинг 4в. Вывод данных в выбранный источник #Форматирование данных $tmp = $obj | Sort-Object -Property "имя" #| Format-Table -Property "Имя", "Должность", "Подразделение" #Вывод данных Clear-Host Write-Host ("Выберите способ вывода:{0}0 - консоль; {0}1 - GUI;{0}2 - файл (c:\report.txt); {0}3 - принтер (по умолчанию)." -f "`n") switch (Read-Host) { 0 {$tmp | Format-Table } 1 {$tmp | Out-GridView -Title "Информация"} 2 {$filename = "c:\report.txt"; $tmp | Out-File -FilePath $fileName; Write-Host ('Данные выведены в файл "{0}"' -f $fileName) } 3 {$tmp | Out-Printer} default {Write-Host "Невозможно вывести информацию."} } Листинг 5. Вывод ошибок в текстовый файл #Очистка содержимого сценария $error.clear <#текст сценария … #> if($error -ne $null){ $error | out-file $fileName -Force -ErrorVariable +bugs -ErrorAction silentlycontinue } Листинг 6. Вывод ошибок в журнал событий #Очистка содержимого сценария $error.clear <#текст сценария … #> #Проверка на существование ошибок if($error -ne $null) { #Проверка на существование источника в журнале событий $source="Power Shell Script" if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {[System.Diagnostics.EventLog]::CreateEventSource($source, "Application")} #Анализ полученных ошибок foreach ($r in $error) { #Формирование текста ошибок $errMsg = '{1}{0}Ошибка в строке {4}(Строка {2}, символ {3})' -f "`n", [string]$R.Exception.Message, [string]$R.InvocationInfo.ScriptLineNumber, [string]$R.InvocationInfo.OffsetInLine, [string]$R.InvocationInfo.Line #Контроль текста ошибки #$errMsg #Запись в журнал событий Write-EventLog –LogName Application –Source $source –EntryType Information –EventID 1 –Message $errMsg } } ----------------------------------------------------------------------------------------------------------------- Декораторы в Ruby Иван Шихалев def log(f): def wrapped(*args, **kwargs): print(f) return f(*args, **kwargs) return wrapped @log def test(): print("Test") test() def show x, &block puts block.call(x) end def alpha x x + 1 end a = method(:alpha) puts a.inspect puts a.call(0) b = proc { |x| x + 2 } puts b.inspect Object.send :define_method, :beta, &b puts beta(0) show 10, &a show 10, &b show 10 do |x| x + 3 end $ ruby deco2.rb def wrap &block proc do |*args, &blk| begin result = block.call *args, &blk $stderr.puts "OK: #{args.inspect}" + " => #{result.inspect}" result rescue Exception => e $stderr.puts "ERROR! #{args.inspect} => #{e.inspect}" raise end end end alpha = proc { |x, y| x / y } a = wrap &alpha z1 = a.call 4, 2 z2 = a.call 4, 0 $ ruby deco2.rb def wrap_method name Object.send :define_method, name, &(wrap &(method name)) End def alpha x, y x / y end wrap_method :alpha alpha 4, 2 alpha 4, 0 class Object private def wrap meth = nil, &block func = meth || block name = (meth && meth.name) || '' proc do |*args, &blk| if UnboundMethod === func func = func.bind self end begin result = func.call *args, &blk $stderr.puts "OK: #{self.inspect}.#{name}" + " #{args.inspect} => #{result.inspect}" result rescue Exception => e $stderr.puts "ERROR! #{self.inspect}.#{name}" + " #{args.inspect} => #{e.inspect}" raise end end end def wrap_singleton_method *names names.each do |name| define_singleton_method name, &wrap(method name) end end end class Module def wrap_method *names names.each do |name| define_method name, &wrap(instance_method name) end end end class Fixnum wrap_method :+, :- end z0 = 4 + 2 z1 = 4 - 2 def mul x, y x * y end wrap_singleton_method :mul z2 = mul 4, 2 $ ruby deco4.rb def wrap_method *names if names.length != 0 @ignore_wrap = true names.each do |name| define_method name, &wrap(instance_method name) end @ignore_wrap = false else ma = method :method_added define_singleton_method :method_added do |name| wrap_method name unless @ignore_wrap ma.call name if ma end end end class Alpha class << self def method_added name puts "method_added: #{name}" end end def alpha p :alpha end wrap_method def beta p :beta end def gamma p :gamma end end a = Alpha.new a.alpha a.beta a.gamma $ ruby deco5.rb class Module def decorator name, &wrapper define_singleton_method name do |*names, **opts| if names.length != 0 @ignore_wrap = true names.each do |nm| define_method nm, &wrapper.call(instance_method(nm), **opts) end @ignore_wrap = false else ma = method :method_added define_singleton_method :method_added do |nm| send name, nm, **opts unless @ignore_wrap ma.call nm if ma end end end end end $: << '.' require 'deco' class Alpha decorator :echo do |unbound, prefix: 'echo: ', **opts| proc do |*args, &blk| puts prefix + 'name = ' + unbound.name.inspect if opts[:name] puts prefix + 'args = ' + args.inspect if opts[:args] result = unbound.bind(self).call *args puts prefix + 'result = ' + result.inspect if opts[:result] result end end def alpha :alpha end echo :alpha, prefix: '', result: true end class Beta < Alpha def beta x "BETA: " + x.to_s end echo :beta, args: true, result: true echo args: true, name: true, result: true, prefix: '[*] ' def gamma a, b, c a * b * c end end b = Beta.new b.alpha b.beta 1 b.gamma 1, 2, 3 $ ruby demo.rb class Fixnum alias :mul :* def * x result = mul x $stderr.puts "#{self} * #{x} = #{result}" result end end ----------------------------------------------------------------------------------------------------------------- SpiderMonkey: расширяем возможности приложений Михаил Ушаков mkdir ~/SoftwareDevelopment/OpenSourceLibs/mozilla && cd ~/SoftwareDevelopment/OpenSourceLibs/mozilla wget http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz tar xzf js185-1.0.0.tar.gz mkdir ~/SoftwareDevelopment/OpenSourceLibs/mozilla && cd ~/SoftwareDevelopment/OpenSourceLibs/mozilla git clone https://github.com/mozilla/mozilla-central.git mkdir ~/SoftwareDevelopment/OpenSourceLibs/mozilla && cd ~/SoftwareDevelopment/OpenSourceLibs/Mozilla.hg clone http://hg.mozilla.org/mozilla-central/ cd js-1.8.5/js/src autoconf-2.13 mkdir build-release && cd build-release ../configure && make mkdir build-debug && cd build-debug ../configure --enable-debug && make ./configure –help mkdir ~/SoftwareDevelopment/OpenSourceLibs/mozilla/nspr && cd ~/SoftwareDevelopment/OpenSourceLibs/mozilla/nspr wget https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.10/src/nspr-4.10.tar.gz tar xzf nspr-4.10.tar.gz autoconf-2.13 mkdir build-release cd build-release ../configure && make sudo mkdir /usr/local/lib/nspr && sudo cp –R build-release /usr/local/lib/nspr mkdir build-threadsafe && cd build-threadsafe ../configure --disable-shared-js --enable-threadsafe --with-nspr-cflags="-I/usr/local/lib/nspr/build-release/dist/include" --with-nspr-libs="/usr/local/lib/nspr/build-release/dist/lib/libnspr4.a /usr/local/lib/nspr/build-release/dist/lib/libplds4.a /usr/local/lib/nspr/build-release/dist/lib/libplc4.a" make mkdir /usr/local/lib/libjs cp –R ../../src /usr/local/lib/libjs enum jsFunctionIndex {ProcessFiles = 1, SendEMail = 2}; JSBool processFiles(JSContext *context, uintN argc, jsval *rval) { return JSProcessorProxy::routeJSCalls(ProcessFiles, context, argc, rval); } JSBool sendEmail(JSContext *context, uintN argc, jsval *rval) { return JSProcessorProxy::routeJSCalls(SendEMail, context, argc, rval); } bool JSProcessorProxy::routeJSCalls(int functionCode, JSContext *context, uintN argc, jsval *rval) { if(jsProcessor!=NULL) return jsProcessor->processScript(functionCode, context, argc, rval); return false; } runtime = JS_NewRuntime(jsGarbageCollectorLimit); jsGarbageCollectorLimit : const unsigned int jsGarbageCollectorLimit = 10000000; JSFunctionSpec function = {"processFiles", processFiles, 0, 0}; jsUserFunctions.push_back(function); function = {"sendEmail", sendEmail, 0, 0}; jsUserFunctions.push_back(function) int index = scripts.size()>0 ? scripts.rbegin()->first + 1 : 1; scripts.insert(pair (index, jScript)); contexts.insert(pair (index, JSStruct())) struct JSStruct { JSContext *context; JSObject *globalObj; JSObject *compiledScript; jsval *outData; }; map::iterator it = find_if(scripts.begin(), scripts.end(), bind2nd(ScriptName(), jScript)); if(it==scripts.end())return false; map::iterator it2 = find_if(contexts.begin(), contexts.end(), bind2nd(ScriptContext(), (*it).first)); if(it2==contexts.end())return false; class ScriptName : public binary_function , string, bool> { public: bool operator() (pair element, string scriptName) const { return element.second.compare(scriptName.c_str()) == 0; } }; class ScriptContext : public binary_function , int, bool> { public: bool operator() (pair element, int scriptId) const { return element.first == scriptId; } }; if(it2==contexts.end())return false; (*it2).second.context = JS_NewContext(runtime, defaultChunkSize); if((*it2).second.context==NULL) return false; JS_BeginRequest((*it2).second.context); (*it2).second.globalObj = JS_NewCompartmentAndGlobalObject((*it2).second.context, &global_class, NULL); JS_InitStandardClasses((*it2).second.context, (*it2).second.globalObj); static JSClass global_class = { "global",JSCLASS_NEW_RESOLVE | JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; JS_SetErrorReporter((*it2).second.context, reportError); void reportError(JSContext *context, const char *message, JSErrorReport *report) { fprintf(stderr, "%s:%u:%s\n", report->filename ? report->filename : "[no filename]", (unsigned int) report->lineno, message); } JS_DefineFunctions((*it2).second.context, (*it2).second.globalObj, jsUserFunctions.data()); (*it2).second.compiledScript = JS_CompileFile((*it2).second.context, (*it2).second.globalObj, (*it).second.c_str()); if((*it2).second.compiledScript == NULL)// bad script! return false; bool result = JS_ExecuteScript((*it2).second.context, (*it2).second.globalObj, (*it2).second.compiledScript, (*it2).second.outData); JS_EndRequest((*it2).second.context); -----------------------------------------------------------------------------------------------------------------