четверг, 27 апреля 2017 г.

Устанавливаем роль RDS+CB+WA пошем

Import-module ServerManager -verbose
Get-WindowsFeature -Name *RDS*
Add-WindowsFeature -Name RDS-RD-Server,RDS-Web-Access,RDS-Connection-Broker -IncludeAllSubFeature -WhatIf
New-SessionDeployment -ConnectionBroker "servername.domain" -WebAccessServer "servername.domain" -SessionHost "servername.domain"

четверг, 30 марта 2017 г.

Убиваем неактивные терминальные сессии скриптом.

foreach ($i in qwinsta /server:terminal | select-string "Диск" | where{$_.tostring()}|where{$_  -notlike "*service*"}){$b=$i.tostring().split()|where{$_}|where{$_ -match "^\d+$"};reset session $b /server:terminal}

суббота, 11 февраля 2017 г.

Магия python.
Реальная задача из жизни. ManageEngine Servicedesk хранит аттачменты для coversations (ответов заявителей) в каталоге MESD homedir\fileAttachments\Conversations\
Но дальше внутри этого каталога он хранит их пачками по 5000 ConversationID.
Типа: 1_5000, 5001_10000, 10001_15000 и тд. Соотвественно ConversationID с номером 24990 попадет в каталог 20000_25000. Задача: напистать функцию определения имени директории наиболее коротким способом.

#ci - input ConversationID
#maxci - maximum of ConversationID (for example 1 million)
#returns dir name of ConversationID
def funcname(ci, maxci):
   a = [i for i in range(0,maxci,5000)]
   b = []
   b+=[str(a[i]+1)+'_'+str(a[i+1]) for i in range(0,len(a)-1)]
   return b[a.index(a[ci//5000 - 1 if ci%5000==0 else ci//5000])]

Результат:





понедельник, 15 августа 2016 г.

Exchange 2010/2013 set readonly rights for mailbox with automapping
Exchange 2010/2013 устанавливаем права только для чтения ящику с автомаппингом


Фишка: автомаппинг работает только для прав FullAccess. Чтобы обойти эту фигню делаем вот такой финт:

add-mailboxpermission -identity BOX -user USER -AccessRights ReadPermission
add-mailboxfolderpermission BOX@DOMAIN.DOM -user USER -AccessRights Reviewer
add-mailboxfolderpermission BOX@DOMAIN.DOM:\Inbox -user USER -AccessRights Reviewer
add-mailboxpermission -identity BOX -user USER -AccessRights FullAccess -Deny -Automap $true


Все. Перелогиниваемся и после запуска outlook видим приезд нового ящика. Прав на удаление писем из него нет. ЧТД

p.s. Чтобы письмо было в ящике "Отправленные" при предоставление доступа на "Оправить как" ----
Set-MailboxSentItemsConfiguration BOX -SendAsItemsCopiedTo:SenderAndFrom -SendOnBehalfOfItemsCopiedTo:SenderAndFrom

понедельник, 1 августа 2016 г.

Показать все ящики, в которые стучались пользователи  от 10.05.16

get-mailbox | Get-MailboxStatistics | Sort-Object LastLogontime | Select-Object DisplayName, LastLogonTime | where{$_.lastlogontime} | where{(get-date $_.lastlogontime) -gt (g
et-date 01.05.2016)} | ft

четверг, 2 июня 2016 г.

MS Exchange 2010 (RUS) delete mail from anywhere with two parameters "From:" and "Subject:"
MS Exchange 2010 (RUS) удаление письма отовсюду исходя из двух параметров "От:" и "Тема:"


[PS] R:\>Get-Mailbox -ResultSize Unlimited | Search-Mailbox -SearchQuery 'Тема:"НАШАТЕМАОЛОЛО" От=email@ourdomain.ru' -TargetMailbox "Adm_adm" -targetfolder "inbox" -deletecontent

Особое внимание следует уделить тому моменту что ребята из микрософта зачем-то сделали разный синтаксис для property  - "От=" вместо аналога на иглише "From:"  

вторник, 5 апреля 2016 г.

List all files in google drive. Google drive need special authorization process. 

# -*- coding: utf8 -*-
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from googleapiclient import errors
from googleapiclient.http import MediaFileUpload

def insert_file(service, title, description, parent_id, mime_type, filename):
    """Insert new file.

    Args:
      service: Drive API service instance.
      title: Title of the file to insert, including the extension.
      description: Description of the file to insert.
      parent_id: Parent folder's ID.
      mime_type: MIME type of the file to insert.
      filename: Filename of the file to insert.
    Returns:
      Inserted file metadata if successful, None otherwise.
    """
    media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
    body = {
        'title': title,
        'description': description,
        'mimeType': mime_type
    }
    # Set the parent folder.
    if parent_id:
        body['parents'] = [{'id': parent_id}]

    try:
        file = service.files().insert(
            body=body,
            media_body=media_body).execute()

        # Uncomment the following line to print the File ID
        # print 'File ID: %s' % file['id']

        return file
    except errors.HttpError, error:
        print 'An error occured: %s' % error
        return None

gauth = GoogleAuth()
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    gauth.Refresh()
else:
    gauth.Authorize()
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)

#print(insert_file(gauth.service,"ololo1","ololo-descriptipn","","text/plain","eng.txt"))
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
    print 'title: %s, id: %s, date: %s' % (file1['title'], file1['id'], file1['createdDate'])