понедельник, 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'])



пятница, 5 февраля 2016 г.

test service presence  in computers from dhcp leases file
проверяем наличие сервиса на компах из лиза dhcp


clear
$ping = new-object System.Net.NetworkInformation.Ping
function Test-Host ($Name)
{
try
{
     if ($ping.send($Name).Status -eq "Success" ) { $True }
}
    catch{ $False }
}

$hashimported=@{}
import-csv c:\temp\dhcp-leases-18.01.16.csv | sort-object name | where {$_.name -like "COMP-*"} | %{$hashimported[$_.name]=$_.ip}

foreach($computer in $hashimported.keys|sort)
{
 if(test-host($computer))
 {
  try{
  $getservice=get-wmiobject -query "select * from win32_service where name like '%zservice%'" -computername $computer -ErrorAction Stop
  }
  catch {($computer)+" "+$error[0].exception.message}

  if(!$getservice)
    {
($computer)+" Сервис не обнаружен!"
    }
  }
  else
  {
  ($computer)+" PING не прошел!"
  }
 }

среда, 27 января 2016 г.

Function for view directory/es access rights
Функция возвращает хэш в котором ключ - имя директории, значение - массив AccessRights

function get-diraccess
{
 param(
  [string]$path, 
  [switch] $recurse,
  [switch] $verbose
  )
if($recurse){
 $dirs=get-childitem $path -Recurse | ?{ $_.PSIsContainer }}
else{$dirs=get-childitem $path | ?{ $_.PSIsContainer }}

if(!$dirs){return}
$result=@{}
foreach($dir in $dirs)
 {
  $result.add($dir.fullname,@($dir.getAccessControl().Access))
 }

 if($verbose)
 {
  foreach($i in $result.keys)
   {$msg+=$i+"`n";
   foreach($j in $result[$i]){
   $msg+="`t"+($j.IdentityReference)+" - "+($j.filesystemrights)+"`n"}
   }
   Write-Host $msg
 }

 return $result
}

С возвращенным хэшем удобно работать используя Enumerator поша


$a=get-diraccess -path "c:\temp\" -verbose
$enum=$a.keys.getenumerator()
$enum.movenext()
$enum.key
$enum.value

четверг, 14 января 2016 г.

Узнать кто сейчас залогинен на удаленном компе (logged user)
(gwmi Win32_ComputerSystem -ErrorAction SilentlyContinue -ComputerName COMPNAME001).UserName

Старт службы
(get-wmiobject win32_service -filter "name='WinRM'" -computername COMPNAME001).StartService()

Если вылетает ошибка WinRM
$winrmservice=Get-WmiObject Win32_Service -ComputerName COMPNAME001 -filter "name='winrm'"
$winrmservice.startservice()

wbemtest  --- отличная утилита windows для WMI