четверг, 15 февраля 2018 г.

PRTG sensor secrets/examples
example for grace period windows terminal server

poweshell script sensor for prtg:
Get-Content -LiteralPath "C:\scripts\scriptout.txt"

windows sheduler contains everyday task:
powershell -windowstyle minimized -c "powershell -c c:\scripts\grace-period-ts.ps1 > c:\scripts\scriptout.txt"

powershell script for non-domain host:
prepare password:
$pass = "MYP@SSW0RD" | ConvertTo-SecureString -AsPlainText -Force
ConvertFrom-SecureString -SecureString $pass

* Attention, can be reverse unsecured:
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

copy output for variable $pass for script below
SCRIPT:
$hostname = "ts01"
$prtg = '<?xml version="1.0" encoding="Windows-1252" ?> 
<prtg>'

$username="$hostname\Administrator"
$pass="01000ac0d08c9ddf0115d1118c7a00c04fc297eb01000000af5d5e1acfacf44fb3e6da2b3bb6c12d0000000002000000000003660000c000000010000000ce6f9d71d1da7703458f899c695f4a220000000004800000a000000010000000f26cf27ef25096d4b56c2634b9167fb61800000038f442cef9a1a121ef4238bd21f84b6bf0958f7de57e201914000000aeb56a8714f507a453186e4151614953734b5a35"
$cryptpass=$pass | ConvertTo-SecureString
$cred=New-Object System.Management.Automation.PSCredential -ArgumentList $username, $cryptpass


$gp = [int](Invoke-WmiMethod -Credential $cred -PATH (gwmi -ComputerName $hostname -Credential $cred -namespace root\cimv2\terminalservices -class win32_terminalservicesetting).__PATH -name GetGracePeriodDays).daysleft

$prtg+="
<result> 
   <channel>TS Grace Period Channel</channel>
   <unit>Custom</unit>
   <customUnit>Days</customUnit> 
   <float>0</float>
   <value>"+$gp+"</value> 
   <showChart>1</showChart> 
   <showTable>1</showTable> 
   <Limitmode>1</Limitmode>
   <LimitMinError>14</LimitMinError>
   <LimitErrorMsg>ATTENTION! Grace period less or equal 14 days!($gp)</LimitErrorMsg>
</result>
</prtg>"

$prtg

exit 0


For domain autentication we may use native wmi or winrm
example for winrm:
$s = New-PSSession -Computername $hostname
$gp = Invoke-Command -Session $s -ScriptBlock{[int](Invoke-WmiMethod -PATH (gwmi -namespace root\cimv2\terminalservices -class win32_terminalservicesetting).__PATH -name GetGracePeriodDays).daysleft}
Remove-PSSession $s
etc...



четверг, 21 декабря 2017 г.

powershell. Get host uptime remote:

$OS = Get-WmiObject win32_operatingsystem -ComputerName COMPNAME
$BootTime = $OS.ConvertToDateTime($OS.LastBootUpTime)
$Uptime = $OS.ConvertToDateTime($OS.LocalDateTime) - $boottime

by https://gallery.technet.microsoft.com/scriptcenter/Get-Uptime-PowerShell-eb98896f

$wmi = Get-WmiObject -Class Win32_OperatingSystem -ComputerName COMPNAME
$wmi.ConvertToDateTime($wmi.LocalDateTime) – $wmi.ConvertToDateTime($wmi.LastBootUpTime)

среда, 13 декабря 2017 г.

Показать все сервисы, запущенные не от локальных системных учёток.

Get-WmiObject win32_service | ?{-not (($_.StartName -match "LocalService") -or ($_.StartName            -match "LocalSystem") -or ($_.StartName -match "NetworkService"))} | select name,Startname

четверг, 30 ноября 2017 г.

Show all computer with old lastlogondate

get-adcomputer -filter {Enabled -eq $True} -searchbase "ou=Computers,dc=domain,dc=net" -properties lastlogondate, lastlogon | where{(get-date $_.LastLogonDate) -lt (get-date 2017-11-01)} |    sort-object lastlogondate | select name, lastlogondate

вторник, 28 ноября 2017 г.

ManageEngine ServiceDesk moving from linux to windows attachments problem: can't find attachment.

use servicedesk;
SET SQL_SAFE_UPDATES = 0;
update sdeskattachment set ATTACHMENTPATH = replace(ATTACHMENTPATH, "/", "\\") WHERE 1=1;

пятница, 29 сентября 2017 г.

powershell script for set some ad attributes
in data - csv file

#by alex
import-module activedirectory
clear
$path = 'c:\scripts\users-info-update.csv'

$csv = Import-Csv $path

foreach($usercsv in $csv){
 $usercsv.DisplayName
 if($usercsv.mobile){
  Set-ADUser $usercsv.sAMAccountName -mobile $usercsv.mobile
  "set mobile "+$usercsv.mobile
  }

 if($usercsv.description){
  Set-ADUser $usercsv.sAMAccountName -Description $usercsv.description
  "set description "+ $usercsv.description
  }

if($usercsv.title){
  Set-ADUser $usercsv.sAMAccountName -Title $usercsv.title
  "set title "+$usercsv.title
  }

 Set-ADUser $usercsv.sAMAccountName -Company "Company"
 if($usercsv.ipPhone){
  try{
   Set-ADUser $usercsv.sAMAccountName -Add @{'ipPhone'=[string]$usercsv.ipPhone}
   "add ipPhone "+$usercsv.ipPhone
   }
  catch{
    Set-ADUser $usercsv.sAMAccountName -Replace @{'ipPhone'=[string]$usercsv.ipPhone}
    "replace ipPhone "+$usercsv.ipPhone
    }
 }

 if($usercsv.telephoneNumber){
    Set-ADUser $usercsv.sAMAccountName -OfficePhone $usercsv.telephoneNumber
   "replace telephoneNumber "+$usercsv.telephoneNumber
  try{
   Set-ADUser $usercsv.sAMAccountName -Add @{'HomePhone'=[string]$usercsv.telephoneNumber}
   }
  catch{
    Set-ADUser $usercsv.sAMAccountName -Replace @{'HomePhone'=[string]$usercsv.telephoneNumber}
    }

 }

if($usercsv.facsimileTelephoneNumber){
  try{
   Set-ADUser $usercsv.sAMAccountName -Add @{'facsimileTelephoneNumber'=[string]$usercsv.facsimileTelephoneNumber}
   "add facsimileTelephoneNumber "+$usercsv.facsimileTelephoneNumber
   }
  catch{
    Set-ADUser $usercsv.sAMAccountName -Replace @{'facsimileTelephoneNumber'=[string]$usercsv.facsimileTelephoneNumber}
   "replace facsimileTelephoneNumber"+$usercsv.facsimileTelephoneNumber
    }
 }
}

среда, 14 июня 2017 г.

Trigger for ManageEngine Servicedesk Plus. example
Триггер для ManageEngine Servicedesk Plus. пример

SD trigger string:
powershell -file c:\scripts\cancelrequest.ps1 отклонена $WORKORDERID

code:

#powershell script for manageengine SDP trigger
#by *me
Param ([string] $txt, [string]$WORKORDERID)
$TECHNICIAN_KEY='XXXXXX-XXXXXXX-XXXXXX-XXXXXX'
$SDEMAIL="sd@domain.com"
$SUBJECT = "Ваша заявка ##{0}## была {1}" -f $WORKORDERID, $txt  
$LOGFILE="c:\scripts\cancelrequest.log"
$MAILSERVER="mail.domain.com"
$SDHOST="https://localhost"

#errorcodes
$REQUESTERNOTFOUNDERROR=-101


function sendrequest($uri)
{
 $response = Invoke-RestMethod -Uri $uri
 if($response.operation.result.status -ne "Success"){
   $message = "function {0} returns non success result:`n{1}" -f $MyInvocation.MyCommand.Name, $response.operation.result  
   throw $message}
 return $response
}

function getrequest([string]$id)
{
 $uri=$SDHOST+'/sdpapi/request/'+$id+'?OPERATION_NAME=GET_REQUEST&TECHNICIAN_KEY='+$TECHNICIAN_KEY+'&format=json'
 Invoke-RestMethod -Uri $uri -Method Get
 return $response
}


function getresolution([string]$id)
{
 $uri=$SDHOST+'/sdpapi/request/'+$id+'?OPERATION_NAME=GET_RESOLUTION&TECHNICIAN_KEY='+$TECHNICIAN_KEY+'&format=json'
 $response = sendrequest($uri) 
 return $response.operation.Details.RESOLUTION
}

function getrequester($r)
{
 $uri=$SDHOST+'/sdpapi/requester?OPERATION_NAME=GET_ALL&TECHNICIAN_KEY='+$TECHNICIAN_KEY+'&INPUT_DATA={"operation":{"details":{"name":"'+$r+'"}}}&format=json'
 #log("uri="+$uri)
 $response = sendrequest($uri)
 return $response.operation.details
}

function log([string]$txt)
{
 add-content $LOGFILE $txt 
}

function main(){
  log(Get-Date -format "dd.MM.yyyy H:m")
  log("WORKORDERID="+$WORKORDERID)
  $request = getrequest($WORKORDERID)
  $REQUESTER = $request.REQUESTER
  log("REQUESTER="+$REQUESTER) 

  $requesterdata=getrequester($REQUESTER)
  if(![boolean]$requester){
   log("Requester not found. Abnormal oO")
   return $REQUESTERNOTFOUNDERROR}

  $to = @($requesterdata.emailid)[0] 
  $from = $SDEMAIL 
  $body = getresolution($WORKORDERID) 
  log("Sending mail to:"+$to)
  log("="*40)
  $encoding = [System.Text.Encoding]::UTF8
  send-MailMessage -SmtpServer $MAILSERVER -To $to -From $from -Subject $SUBJECT -Body $body -BodyAsHtml -Encoding $encoding
}

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    
    public class IDontCarePolicy : ICertificatePolicy {
        public IDontCarePolicy() {}
        public bool CheckValidationResult(
            ServicePoint sPoint, X509Certificate cert,
            WebRequest wRequest, int certProb) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = new-object IDontCarePolicy 

try{
 main}
catch{
   $ErrorMessage = $_.Exception.Message
   log("Exception detected!`n"+"Error message:"+$ErrorMessage+"`n"+'='*40)
   return -1}