Tuesday, December 9, 2014

add-QADGroupMember : Cannot resolve directory object for the given identity

When the script (variables formed in progress) powershell encountered an unexpected error:

$Group_DN = "CN=MyGroup1,OU=MyOU1,DC=hq,DC=contoso,DC=com"
add-QADGroupMember -identity $Group_DN -member hq\MyUser1

add-QADGroupMember : Cannot resolve directory object for the given identity:

And in a separate window powershell commands are processed normally. First decided to add quotes received a new error:

add-QADGroupMember : Cannot bind parameter 'Identity'. Cannot convert the "" value of type

Then drew attention to the following line in error:

value of type "Microsoft.PowerShell.Commands.MatchInfo" to type "Quest.ActiveRoles.ArsPowerShellSnapIn.Data.IdentityParameter"

And I realized that you just have to convert the variable type



$Group_DN = "CN=MyGroup1,OU=MyOU1,DC=hq,DC=contoso,DC=com"
[string]$Group_DN2 = $Group_DN
add-QADGroupMember -identity $Group_DN2 -member hq\MyUser1

Monday, December 8, 2014

Self Service Password Reset Web Site

In a complex network with some trusted and untrusted forests, where users can use the accounts of various woods, there are problems with changing the password, the article http://www.kovanev.net/faq/vbs/164-vbs-3 describes a good script to reset your password. In my version redesigned with a request to WINNT LDAP to view subdomains, and adds the ability to work without authentication for users from untrusted forests.

On the Web server, do the following:
1. Create a folder, eg C:\ChangePass
2. In the folder create a file containing index.html (download index.html)

<html>
<head>
<title>Change User Password</title>
<!--BEGIN CALLOUT A-->
<HTA:APPLICATION
BORDER="thin"
BORDERSTYLE="sunken"
CAPTION="yes"
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SCROLL="no"
SHOWINTASKBAR="no"
SYSMENU="yes"
WINDOWSTATE="normal" />

<!--END CALLOUT A-->
<script language=javascript>
var sampleWidth = 300;
var sampleHeight = 420;
window.resizeTo(sampleWidth,sampleHeight);
var screenPosX = screen.Width/2 - sampleWidth/2;
var screenPosY = screen.Height/2 - sampleHeight/2;
window.moveTo(800, 300);
</script>
</head>

<body>
    <form action="cp.asp" method="post">
        <!--BEGIN CALLOUT C-->
        <p><font size="3">Specify your username: </font></p><input type="text" name="T1" size="20">
        <!--END CALLOUT C-->
        <p><font size="3">Enter your current password: </font></p><input type="password" name="T2" size="20"></p>
        <p><font size="3">Enter a new password: </font></p><input type="password" name="T3" size="20"></p>
        <p><font size="3">Re-enter new password: </font></p><input type="password" name="T4" size="20"></p>
        <!--BEGIN CALLOUT D-->
        <p><input type="Submit" value="Change password" name="B3" >
        <input type="button" value="Cancel" name="B6" onclick=self.close()></p>
        <!--END CALLOUT D-->
    </form>
</body>
</html>

3. Create user for impersonate authentication, add user to NULL group, exclude from Domain Users
4. In the folder create a file containing cp.asp (download cp.asp), add user login, password, domain

<%@ language="VBScript" %>
<%
Dim objLogon
Set objLogon = Server.CreateObject("LoginAdmin.ImpersonateUser")
objLogon.Logon "youruser", "yourpassword", "youruserdomain"

Set WShell = CreateObject("WScript.Shell")
on error resume next
Dim UserName
UserName = Request.Form("T1")
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 10000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = _
   "SELECT distinguishedName FROM 'LDAP://hq.contoso.com' WHERE objectCategory='user' " & _ "AND samaccountname = '" & username &"'" &""
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    strDN = objRecordSet.Fields("distinguishedName").Value
    objRecordSet.MoveNext
Loop

Set User = GetObject("LDAP://" & strDN)

objLogon.Logoff
     Set objLogon = Nothing

Dim NewPassword
Dim NewPassword2
Dim OldPassword

OldPassword = Request.Form("T2")
NewPassword = Request.Form("T3")
NewPassword2 = Request.Form("T4")

If Request.Form("T1") = "" Then
    Response.Write("Username can't be empty!")
end if

If NewPassword<>NewPassword2 Then
    Response.Write("ERROR. New passwords do not match.")
end if

if NewPassword=NewPassword2 then
    Err.Clear
    Call user.CHANGEPASSWORD (OldPassword, NewPassword)

If err.number = 0 Then
    Response.Write("SUCCESS. New password has been saved.")
end if

If err.number = "-2147024810" Then
    Response.Write("ERROR. Wrong password!")
end if

If err.number = "-2147022651" Then
    Response.Write("ERROR. The new password does not meet the policy complexity and frequency of passwords!")
end if
end if
 %>

5. Download LoginAdmin.dll or create your own article: "How to impersonate a user from Active Server Pages"
6. Register the dll, eg regsvr32.exe C:\ChangePass\LoginAdmin.dll
7. In IIS console to create a website "ChangePass", specify the folder "C:\ChangePass", configure Bindings, configure https, anonymous authentication
8. When you open the page, you will see:
UPD: In some cases, the need to provide for Identity "youruser" application pool

Monday, November 17, 2014

Remote diagnostics brief Windows server using Powershell

In this article I want to share Powershell script that quickly collects data from the server:
1. Service not running, but with the type of start automatic
2. Errors and warnings from the Application event log and System
3. The disk space
4. The average CPU load
In most cases, this is sufficient information to verify the server.

Download BriefCheck.ps1

Use the script as follows:
1. Powershell run as an administrator of the domain or a specific server
2. Run .\BriefCheck.ps1 <servername>

[CmdletBinding()]
Param (
    [Parameter(Mandatory = $True, Position = 0)]
    [string]$pc
)

write-host "...Service error:" -fore Green
$pc_s = Get-wmiobject win32_service -Filter "startmode = 'auto' AND state != 'running'" -ComputerName $pc | select DisplayName, name, startname, exitcode
if ($pc_s) { Out-Host -InputObject $pc_s }
else { write-host "no errors" }

write-host "...Eventlog Application,System warnings, errors:" -fore Green
$pc_e = Get-WinEvent -computername $pc -Logname Application, System -MaxEvents 100 -EA silentlycontinue | where-object { $_.timecreated -gt [datetime]::Now.AddHours(-1) -and (($_.LevelDisplayName -eq "Error") -or ($_.LevelDisplayName -eq "Warning")) }
if ($pc_e) { Out-Host -InputObject $pc_e }
else { write-host "no errors" }

write-host "...Disk space:" -fore Green
$TotalGB = @{ Name = "Capacity(GB)"; expression = { [math]::round(($_.Capacity/ 1073741824), 2) } }
$FreeGB = @{ Name = "FreeSpace(GB)"; expression = { [math]::round(($_.FreeSpace / 1073741824), 2) } }
$pc_v = Get-WmiObject -computer $pc win32_volume
$pc_v | Select Name, Label, $TotalGB, $FreeGB | Format-Table -AutoSize

write-host "...CPU Average Load:" -fore Green
Get-WmiObject win32_processor -computer $pc | Measure-Object -property LoadPercentage -Average | Select Average

Monday, October 27, 2014

Steps to migrate the configuration Exchange 2010 Edge to Exchange 2013 Edge

In this article I want to share powershell commands with which you can quickly import a basic configuration Exchange 2013 Edge server. First, export the configuration from the source server Exchange Edge 2010, before each command is written which configuration is exported:

New-Item -ItemType directory -Path C:\ex-config -ea 0
## IP Allow list
Get-IPAllowListEntry | Select IPRange | Export-Csv c:\ex-config\ip-allow.csv
## IP Block list
Get-IPBlockListEntry | Select IPRange | Export-Csv c:\ex-config\ip-block.csv
## Bypassed Recipients (whitelist to)
Get-ContentFilterConfig | select BypassedRecipients -expand BypassedRecipients | 
select local, domain | export-csv c:\ex-config\BypassedRecipients.csv -notypeinformation
## Bypassed Senders  (whitelist from)
Get-ContentFilterConfig | select BypassedSenders -expand BypassedSenders | 
select local, domain | export-csv c:\ex-config\BypassedSenders.csv -notypeinformation
## Blocked Senders  (blacklist from)
Get-SenderFilterConfig | select BlockedSenders -expand BlockedSenders | 
select local, domain | export-csv c:\ex-config\BlockedSenders.csv -notypeinformation
## Blocked Senders domain (blacklist from)
Get-SenderFilterConfig | select BlockedDomains -expand BlockedDomains | 
select domain | export-csv c:\ex-config\BlockedDomains.csv -notypeinformation
## Blocked Senders domain and sub (blacklist from)
Get-SenderFilterConfig | select BlockedDomainsAndSubdomains -expand BlockedDomainsAndSubdomains | 
select domain | export-csv c:\ex-config\BlockedDomainsAndSubdomains.csv -notypeinformation
## Blocked Recipients (blacklist to)
Get-RecipientFilterConfig | select BlockedRecipients -expand BlockedRecipients | 
select local, domain | export-csv c:\ex-config\BlockedRecipients.csv -notypeinformation
## Transport rules
$file = Export-TransportRuleCollection
Set-Content -Path "C:\ex-config\Ex2010TransportRules.xml" -Value $file.FileData -Encoding Byte

Then you need to copy a folder c:\ex-config with configuration files to the destination server and execute commands powershell:

## IP Allow list
$IPList = Import-Csv c:\ex-config\ip-allow.csv
ForEach ($SingleIP in $IPList) { Add-IPAllowListEntry -IPRange $SingleIP.IPRange }
## IP Block list
$IPList = Import-Csv c:\ex-config\ip-block.csv
ForEach ($SingleIP in $IPList) { Add-IPBlockListEntry -IPRange $SingleIP.IPRange }
## Bypassed Recipients (whitelist to)
$MList2 = (Get-ContentFilterConfig).BypassedRecipients
$MList = Import-Csv c:\ex-config\BypassedRecipients.csv
ForEach ($mail in $MList)
{
    $mail2 = $mail.local + "@" + $mail.domain
    $Mlist2.add($mail2)
}
Set-ContentFilterConfig -BypassedRecipients $Mlist2
## Bypassed Senders  (whitelist from)
$MList2 = (Get-ContentFilterConfig).BypassedSenders
$MList = Import-Csv c:\ex-config\BypassedSenders.csv
ForEach ($mail in $MList)
{
    $mail2 = $mail.local + "@" + $mail.domain
    $Mlist2.add($mail2)
}
Set-ContentFilterConfig -BypassedSenders $Mlist2
## Blocked Senders  (blacklist from)
$MList2 = (Get-SenderFilterConfig).BlockedSenders
$MList = Import-Csv c:\ex-config\BlockedSenders.csv
ForEach ($mail in $MList)
{
    $mail2 = $mail.local + "@" + $mail.domain
    $Mlist2.add($mail2)
}
Set-SenderFilterConfig -BlockedSenders $Mlist2
## Blocked Senders domain (blacklist from)
$MList2 = (Get-SenderFilterConfig).BlockedDomains
$MList = Import-Csv c:\ex-config\BlockedDomains.csv
ForEach ($mail in $MList)
{
    $Mlist2.add($mail.domain)
}
Set-SenderFilterConfig -BlockedDomains $Mlist2
## Blocked Senders domain and sub (blacklist from)
$MList2 = (Get-SenderFilterConfig).BlockedDomainsAndSubdomains
$MList = Import-Csv c:\ex-config\BlockedDomainsAndSubdomains.csv
ForEach ($mail in $MList)
{
    $Mlist2.add($mail.domain)
}
Set-SenderFilterConfig -BlockedDomainsAndSubdomains $Mlist2
## Blocked Recipients (blacklist to)
$MList2 = (Get-RecipientFilterConfig).BlockedRecipients
$MList = Import-Csv c:\ex-config\BlockedRecipients.csv
ForEach ($mail in $MList)
{
    $mail2 = $mail.local + "@" + $mail.domain
    $Mlist2.add($mail2)
}
Set-RecipientFilterConfig -BlockedRecipients $Mlist2
## Transport rules
[Byte[]]$Data = Get-Content -Path "C:\ex-config\Ex2010TransportRules.xml" -Encoding Byte -ReadCount 0
Import-TransportRuleCollection -FileData $Data

You also need to perform general configuration commands, here are some examples:

New-ReceiveConnector -Name Inet -Bindings <your ip eg 1.1.1.1>:25 -RemoteIPRanges 0.0.0.0-255.255.255.255 
-Fqdn <your server fqdn eg mx1.blogspot.com> -AuthMechanism none -MaxMessageSize <your limit eg 60Mb>

-PermissionGroups AnonymousUsers -ProtocolLoggingLevel Verbose
Set-ReceiveConnector <your internal server connector> -Bindings <your ip eg 10.1.1.1>:25 -MaxMessageSize <your limit eg 60Mb> -ProtocolLoggingLevel Verbose

Add-IPBlockListProvider -Name Spamhaus -LookupDomain zen.spamhaus.org 
-AnyMatch $true -Enabled $true -RejectionResponse "Your message was rejected because the IP address of the sending server {0} is blacklisted by {1} Lookup Domain {2}"
Add-IPBlockListProvider -Name "Dul Sorbs" -LookupDomain dul.dnsbl.sorbs.net 
-AnyMatch $true -Enabled $true -RejectionResponse "Your message was rejected because the IP address of the sending server {0} is blacklisted by {1} Lookup Domain {2}"
Add-IPBlockListProvider -Name Spamcop -LookupDomain bl.spamcop.net 
-AnyMatch $true -Enabled $true -RejectionResponse "Your message was rejected because the IP address of the sending server {0} is blacklisted by {1} Lookup Domain {2}"

Set-ContentFilterConfig -QuarantineMailbox junk@blogspot.com -SCLRejectEnabled $False -SCLQuarantineThreshold 7 -SCLQuarantineEnabled $True

Set-TransportServer <your server name> -ConnectivityLogPath "D:\TransportRoles\Logs\Connectivity" 
-MessageTrackingLogPath "D:\TransportRoles\Logs\MessageTracking" -ReceiveProtocolLogPath "D:\TransportRoles\Logs\ProtocolLog\SmtpReceive" 
-SendProtocolLogPath "D:\TransportRoles\Logs\ProtocolLog\SmtpSend" -AgentLogPath "D:\TransportRoles\Logs\ProtocolLog\AgentLog"

Thursday, October 23, 2014

CMD title %userdomain%\%username%

When administering multiple domains, forests often have to run a command line CMD from different users. Previously, I always confused: what CMD from which user is running? Then came the idea to sign the title of the CMD command line username and domain. This can be done as follows:
1. Create or modify a registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor" AutoRun (REG_SZ)
2. Add to the value of the command @title %userdomain%\%username%

for example, this can be done by running the command
reg add "HKLM\SOFTWARE\Microsoft\Command Processor" /v AutoRun /t REG_SZ /d "@title "%""userdomain%\%""username%"" /f


Tuesday, October 14, 2014

Creating a address list for users of MS Lync

With the introduction of Lync in the company is very convenient to give users a ready-address list, grouped by such organizational structure. This can be done in the following ways:
1. If your company has Exchange server, you need to create a Exchange distribution group to include users and add to Lync these groups. Member List will be updated in accordance with changes in the distribution group. Then extended to other users http://charlesulrich.blogspot.ru/2013/03/lync-server-2013-bulk-updating-contact.html eg on Lync server
- Create a folder C:\Scripts, copy the folder script "contact_import.ps1"
- Install 7 zip
- Take a standard user, create a user address list
- In Lync powershell run command: Export-CsUserData -PoolFqdn <yourpool> -UserFilter <sipofstandartuser> -FileName "c:\temp\ExportedUserData.zip"
- Copy from "c:\temp\ExportedUserData.zip" the desired line in more detail in the article http://charlesulrich.blogspot.ru/2013/03/lync-server-2013-bulk-updating-contact.html to "contact_import.ps1"
- Run the script "contact_import.ps1" (before running the script recommend commenting out the last line to deleting files and delete files manually)
- Address list will appear after restarting the client Lync
2. If the company does not Exchange server - you can not add no Exchange distribution group in Lync, then you can use the following script https://gallery.technet.microsoft.com/office/Bulk-Import-Contacts-for-8e3c614f eg on Lync server
- Create a folder C:\Scripts, copy the folder script "Add-CsContact.ps1", file users.csv
- Take a standard user, create a user address list
- To make a file users.csv users for whom this list should be extended (More in the article https://gallery.technet.microsoft.com/office/Bulk-Import-Contacts-for-8e3c614f)
- Run the script ".\Add-CsContact.ps1 -userCsv C:\Scripts\users.csv -tplpath <sipofstandartuser> -poolfqdn <yourpool> -folder C:\Scripts"
- Address list will appear after restarting the client Lync

Monday, September 29, 2014

Balon file for reservation disk space

Often there are situations when the free space on the disk runs out and we miss this moment :) So I suggest to use Balon file occupies 1 GB, and in the event of a critical situation with free space, delete the file. To do this, create a folder on the target disk RESERVE, in the folder, create and run a CMD file:

@echo off
IF NOT EXIST "%~dp0\safesize.rez" fsutil file createnew "%~dp0\safesize.rez" 1024000000
Download rezerve.cmd

Sunday, September 28, 2014

AO configuration null already exist on System HP_3PAR

An unexpected error may occur when you attempt to change the AO configuration storage system HP 3PAR: AO configuration null already exist on System HP_3PAR. This error leads to different thoughts about the need to re-create the AO configuration, but the solution is simple - you need to change the Name field, for example, add 1. It's just a mistake of web-interface.

Sunday, August 31, 2014

How to remove unnecessary users and groups from the local Administrators group, with a VBS script.

There are times when you want to restrict access to your computer at work. Disposable cleaning group will not help, because in the future membership of a group can change the domain group policy. Therefore, it may help a scheduled task, the task can be performed every 5 minutes. With "net localgroup" I was not able to remove the group from the group, so I propose to use the following VBS script to remove users and groups from the local Administrators group:

Download clear_adm.vbs

Set objGroup = GetObject("WinNT://./Administrators,group")

For Each Member in objGroup.members
 if not ((Member.name = "Administrator") or (Member.name = "myAccount1") or (Member.name = "myAccount2") or (Member.name = "myAccount3")) then objGroup.Remove(Member.ADSPath)
Next

Tuesday, August 26, 2014

Quick release system disk windows 2008 by "System queued Windows Error Reporting" and "Service Pack Backup Files"

In Windows 2008 quickly running out of space on the system drive. Servers Windows 2003 was a wonderful tool Disk Cleanup, but unfortunately in Windows 2008, you must additionally install this utility as components Desktop Experience and restart the server after installation, what happens is unacceptable. This gave the idea to create a small script for the prompt release of the system drive. In this scenario, removed "System queued Windows Error Reporting" and "Service Pack Backup Files". Running this script will free the system drive without restarting the server!

Download sys_disk_cleanup.cmd

@Echo off

if exist "%programdata%\microsoft\windows\wer\reportqueue" RD /S /Q "%programdata%\microsoft\windows\wer\reportqueue\" && MD "%programdata%\microsoft\windows\wer\reportqueue\"

dism /online /cleanup-image /spsuperseded

Sunday, July 13, 2014

Reset DSRM password on domain controller

There are unexpected situations when a domain controller fails and you want to boot using the DSRM mode but the password is lost. Actually DSRM password domain controller is local administrator password. Reset your password easy enough to boot (http://home.eunet.no/~pnordahl/ntpasswd/) and reset such as the local administrator password.


In this video I show you how to reset the password for DSRM mode domain controller. To do this, first set the password for DSRM mode, reboot and enter the password in DSRM mode, then reset the password from the boot disk (http://home.eunet.no/~pnordahl/ntpasswd/) and enter without a password on a domain controller in DSRM mode.

Friday, July 11, 2014

How delete lingering objects in Active Directory

In multi-domain environment, there are often problems with replication, caused by the loss of communication, time differences which resulted in an Active Directory assets appear Ghosts (lingering objects), which in turn also inhibit replication. In this article, I show an example of how to create an cmd file for cleaning Ghosts (lingering objects).

Download create_lingering_cmd.ps1

1. Go to root DNS Server and on zone property Allow zone transfers to any server
2. Open cmd nslookup tool and type command "ls -t cname youtdomain.com"
3. Go to root DNS Server and on zone property Only to servers listed on the Name Servers tab
4. Copy result where line contain _.msdcs to notepad and replace (Ctrl - H) text "._msdcs CNAME "
5. Save file with name "guids.csv"
6. Copy "guids.csv" to PC with powershell and create powershell csript

$guids = import-csv -header dcguid, dcname ".\guids.csv" -delimiter " "
$path_cmd_file = ".\lingering.cmd"
Clear-Content -path $path_cmd_file
$cmd_file = "@echo off"
Add-Content -path $path_cmd_file -value "@echo off"
foreach ($guid in $guids)
{
    $guid.dcname -match '^([^.]+).(.+)' > $nul
    $parts = $matches[2].Split(".")
    $dcname_dn = "dc="
    $i = 1
    foreach ($part in $parts)
    {
        if ($i -ne $parts.count) { $dcname_dn += $part + ",dc=" }
        else { $dcname_dn += $part }
        $i++
    }
    $comm = "repadmin /removelingeringobjects * " + $guid.dcguid + " " + $dcname_dn
    $cmd_file += "`n$comm"
    Add-Content -path $path_cmd_file -value $comm
}
$cmd_file += "`npause"
Add-Content -path $path_cmd_file -value "pause"
$cmd_file

7. Powershell script create cmd file "lingering.cmd". Now you you can copy this cmd file, repadmin tool to Domain Controller and run

Tuesday, July 8, 2014

Find using PowerShell, who use the CPU on Microsoft SQL Server

In solving problems with a high load on the server CPU Microsoft SQL Server saw the article "How to find out how much CPU a SQL Server process is really using" but when a large number of processors is not possible to identify problem processes. So the idea came from a script to automate powershell. With this script you can quickly identify problematic processes on the database Microsoft SQL Server:

Download script cpu_spid


$ServerInstance = "YourSQLServer\SQLServerInstanceName"
$CpuThreshold = "90"
$Database = "master"
$ConnectionTimeout = 30
$QueryTimeout = 120
$sql_spid = $null
$QueryBase = "SELECT top 1 spid FROM sysprocesses WHERE kpid="

$proc_time_counters = (get-counter -listset thread).PathsWithInstances | where { ($_ -like "*sqlservr*") -and ($_ -like "*Processor Time") }
$proc_time_values = (get-counter -counter $proc_time_counters).countersamples | sort CookedValue
foreach ($proc_time_value in $proc_time_values)
{
    if ($proc_time_value.CookedValue -gt $CpuThreshold)
    {
        $thread_id_counter = "\" + $proc_time_value.path.split("\")[3] + "\" + "ID Thread"
        $thread_id_value = (get-counter $thread_id_counter).readings.split(":")[1]
        write-host "ID Processor Counter:" $proc_time_value.path
        write-host "Processor Time, %:" $proc_time_value.CookedValue
        write-host "ID Thread Counter:" $thread_id_counter
        write-host "Thread:" $thread_id_value.trim()
        $Query = $QueryBase + $thread_id_value.trim()
        $conn = new-object System.Data.SqlClient.SQLConnection
        $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance, $Database, $ConnectionTimeout
        $conn.ConnectionString = $ConnectionString
        $conn.Open()
        $cmd = new-object system.Data.SqlClient.SqlCommand($Query, $conn)
        $cmd.CommandTimeout = $QueryTimeout
        $ds = New-Object system.Data.DataSet
        $da = New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
        [void]$da.fill($ds)
        $conn.Close()
        $sql_spid = ($ds.Tables[0] | select -first 1).spid
        if ($sql_spid)
        {
            write-host "SQL spid:" $sql_spid
            $conn.ConnectionString = $ConnectionString
            $conn.Open()
            $Query2 = "sp_who2 " + $sql_spid
            $cmd2 = new-object system.Data.SqlClient.SqlCommand($Query2, $conn)
            $cmd2.CommandTimeout = $QueryTimeout
            $ds2 = New-Object system.Data.DataSet
            $da2 = New-Object system.Data.SqlClient.SqlDataAdapter($cmd2)
            [void]$da2.fill($ds2)
            $conn.Close()
            $conn.ConnectionString = $ConnectionString
            $conn.Open()
            $Query3 = "DBCC inputbuffer($sql_spid)"
            $cmd3 = new-object system.Data.SqlClient.SqlCommand($Query3, $conn)
            $cmd3.CommandTimeout = $QueryTimeout
            $ds3 = New-Object system.Data.DataSet
            $da3 = New-Object system.Data.SqlClient.SqlDataAdapter($cmd3)
            [void]$da3.fill($ds3)
            $conn.Close()
            write-host "@@@@@@ SQL session begin @@@@@"
            $ds2.Tables[0]
            $ds3.Tables[0]
            write-host "@@@@@@ SQL session end @@@@@"
        }
    else { write-host "SQL spid: no found" }
    write-host "--------------------------"
    }
}

Sunday, June 29, 2014

Instructions for creating Dial-in conference in Lync

This manual describes how to setup your server Lync 2013 to prepare for the conference with analog abonent. Are also briefly Asterisk server setup. For a conference on the Lync 2013 and an Asterisk reserved extension 2000.
  1. Open Lync Topology Builder, download config, create a PSTN gateways



  2. Edit poll property, mark checkbox Dial-in (PSTN) conferencing
  3. Publish Topology and run “Lync Server Deployment Wizard – Install or Update lync Server System – Setup or Remove Lync Server Components” on servers
  4. Run Microsoft Lync Server 2013 Control Panel, go to conferencing – Dial-in Access Number and create New number

    Define ext number
  5. Go to Voice Routing – Dial Plan and configure Normalization rule for Global dial plan – name Local Extensions
  6. Edit Site dial plan – select Normalization rule Local Extensions, and press commit all
  7. Next edit Voice Routing – Voice Policy, create New Associated PSTN Usage
  8. Create Route, add Associated trunks

  9. Go to Asterisk to configure incoming calls:
               sip.conf:
    [general]
    context=incoming                 ; Default context for incoming calls
    allowguest=no                  ; Allow or reject guest calls (default is yes)
    allowoverlap=no                 ; Disable overlap dialing support. (Default is yes)
    allowtransfer=no               ; Disable all transfers (unless enabled in peers or users)
    bindport=5060                   ; UDP Port to bind to (SIP standard port is 5060)
    bindaddr=0.0.0.0                ; IP address to bind to (0.0.0.0 binds to all)
    srvlookup=yes                   ; Enable DNS SRV lookups on outbound calls
    disallow=all
    allow=ulaw
    allow=alaw
    localnet=x.x.x.x/x.x.x.x
    externalip=x.x.x.x
    canreinvite => no                                                                   

    [Lync_Trunk]                   ; Our Lync trunk
    type=friend
    port=5068                      ; This is the default Lync Server TCP listening port
    host=x.x.x.x             ; This should be the IP address of your Lync Server
    dtmfmode=rfc2833
    context=from-lync
    nat=yes
    qualify=yes
    transport=tcp

    extensions.conf:                                                                 
    [incoming]
    exten => s,1,Answer
    exten => s,n,Background(ent-target-attendant)
    exten => s,n,WaitExten(5)
    exten => s,n,Background(conf-placeintoconf)
    exten => s,n,Dial(SIP/Lync_Trunk/2000,20)
    exten => _200X,1,Dial(SIP/Lync_Trunk/${EXTEN},20)
    exten => i,1,Playback(pbx-invalid)
    exten => i,n,Goto(incoming,s,1)

    [from-lync]
    exten=>_.,1,Dial(${OUTBOUNDTRUNK}/${EXTEN},tT)
    exten=>_.,n,Congestion()
    exten=>_.,n,hangup()