08 October 2015

How to increase Exchange 2010 rules size limit

verify rules size quota:

Get-Mailbox username | Select-Object RulesQuota 


Set rules quota to 256kb (default value is 64kb):

Get-Mailbox username | Set-Mailbox -RulesQuota 256kb


01 October 2015

Powershell data types

Variable type
Description
Example
[array]
An array

[bool]
Yes-no value
[boolean]$flag = $true
[byte]
Unsigned 8-bit integer, 0...255
[byte]$value = 12
[char]
Individual unicode character
[char]$a = "t"
[datetime]
Date and time indications
[datetime]$date = "12.Nov 2004 12:30"
[decimal]
Decimal number
[decimal]$a = 12
$a = 12d
[double]
Double-precision floating point decimal
$amount = 12.45
[guid]
Globally unambiguous 32-byte identification number
[guid]$id = [System.Guid]::NewGuid()
$id.toString()
[hashtable]
Hash table

[int16]
16-bit integer with characters
[int16]$value = 1000
[int32], [int]
32-bit integers with characters
[int32]$value = 5000
[int64], [long]
64-bit integers with characters
[int64]$value = 4GB
[nullable]
Widens another data type to include the ability to contain null values. It can be used, among others, to implement optional parameters
[Nullable``1[[System.DateTime]]]$test = Get-Date
$test = $null
[psobject]
PowerShell object

[regex]
Regular expression
$text = "Hello World"
[regex]::split($text, "lo")
[sbyte]
8-bit integers with characters
[sbyte]$value = -12
[scriptblock]
PowerShell scriptblock

[single], [float]
Single-precision floating point number
[single]$amount = 44.67
[string]
String
[string]$text = "Hello"
[switch]
PowerShell switch parameter

[timespan]
Time interval
[timespan]$t = New-TimeSpan $(Get-Date) "1.Sep 07"
[type]
Type

[uint16]
Unsigned 16-bit integer
[uint16]$value = 1000
[uint32]
Unsigned 32-bit integer
[uint32]$value = 5000
[uint64]
Unsigned 64-bit integer
[uint64]$value = 4GB
[xml]
XML document


28 September 2015

Powershell enum type

Add-Type -TypeDefinition @"
    public enum MyEnum{
        Paper,
        Rock,
        Scisor
    }
"@

[MyEnum]$abc = [MyEnum]::Rock

01 September 2015

LDAP syntax filters


=
Equality
>=
Greater than or equal to (lexicographical)
<=
Less than or equal to (lexicographical)
&
AND, all conditions must be met
|
OR, any of the conditions must be met
!
NOT, the clause must evaluate to False


all user object filter:  (&(objectCategory=person)(objectClass=user)) 

a more efficient all user object filter: (sAMAccountType=805306368)

11 August 2015

Send-MailMessage -Encoding parameter


Send-MailMessage -From 'some.address@domain.com' -To 'some.address@domain.com' -Subject 'test' -Encoding ([System.Text.Encoding]::Unicode)

06 August 2015

Autosave files location when powershell ISE crash


%LocalAppData%\Microsoft_Corporation\powershell_ise.exe_StrongName_lw2v2vm3wmtzzpebq33gybmeoxukb04w\3.0.0.0\AutoSaveFiles

05 August 2015

Converting ASCII codes to characters and characters to ASCII codes


ASCII to character:

[char]65

characters to ASCII code

[int][char]'A'


to covert an entire word:

[int[]][char[]]'word'

18 July 2015

Remove empty entries from split array


$a = 'Surname        GivenName1  GivenName2'
$a = $a.Split(' ',[System.StringSplitOptions]::RemoveEmptyEntries) -join ' '

result: 'Surname GivenName1 GivenName2'

10 July 2015

Using the Import-FIMConfig cmdlet

In ImportObject has:

  • a state
    • Create - create a new object
    • Put - update the object TargetObjectIdentifier with the attribute changes
    • Delete - delete the object TargetObjectIdentifier
    • Resolve - resolves an object in FIM by using the information in AnchorPairs as search criteria
    • None - operation is ignored
  • a list of attributes changes
When updating existing objects, you must define the specific attribute changes.
Each change is an ImportChange that represents a specific attribute value change.
An ImportChange includes an Operation, which informs the web service about the type of change to make on the specific attribute.

Operations are:
  • Add - attribute value should be added to multivalued attribute
  • Replace - attribute value should replace a single valued attribute
  • Delete - attribute value should be removed from the multivalued attribute
  • None - attribute value is included in a Create


The FullyResolved flag indicates whether the Import-FIMConfig cmdlet should search the AttributeValue for instances of SourceObjectIdentifier GUIDs.
 
If true, the cmdlet assumes that all references are correct and submits the AttributeValue verbatim. 
If false, the cmdlet assumes that there exists at least one reference to either a Create or Resolve state. 

The cmdlet replaces all GUIDs with values retrieved from previous Create or Resolve states. 
If a GUID is found but cannot be matched, then the cmdlet aborts, executing this ImportObject as 
not all references are correct.


06 July 2015

Verify exchange database witespace


Get-MailboxDatabase  -Status |Select-Object AdminDisplayName,AvailableNewMailboxSpace, DatabaseSize


03 June 2015

Reset Internet Explorer browser settings command


rundll32 inetcpl.cpl ResetIEtoDefaults

! - command argument is case sensitive

21 May 2015

Find available (unique) username in Active Directory

function test{
    for($i=0; $i -le $prenume.Split(' ').Length - 1; $i++){
        for($j=0; $j -le $nume.Split(' ').Length - 1; $j++){
                $TestName = $prenume.Split(' ')[$i].Trim() + '.' + $nume.Split(' ')[$j].Trim()
                if($TestName.Length -gt 20){ $TestName = $TestName.Substring(0,20) }
                $aduser = (Get-ADUser -LDAPFilter "(SamAccountName=$TestName)")
                if(!$aduser){
                    $TestName = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ToTitleCase($TestName.ToLower())
                    return $TestName
                }
                Clear-Variable aduser
        }
    }

    # a unique username is was not found - try by appending numbers
    $i = 0
    while(!$aduser){
            $i++
            $TestName = $nume.Split(' ')[0].Trim() + $i + '.' + $prenume.Split(' ')[0].Trim()
            if($TestName.Length -gt 20){ $TestName = $TestName.Substring(0,20) }
            $aduser = (Get-ADUser -LDAPFilter "(SamAccountName=$TestName)")
            if(!$aduser){
                $TestName = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ToTitleCase($TestName.ToLower())
                return $TestName
            }
    }
}

03 April 2015

Splunk CLI search


#!/bin/sh
inputfile=/root/criptocardlist
logfile=/root/splunksearchresult.log

if [ -e $inputfile ]; then
        cat $inputfile | while read cryptocard
        do
        result=$(/opt/splunk/bin/splunk search "vpn="ive" "$cryptocard"" -maxout 1)
        echo $cryptocard, $result >> $logfile
        done
else
        echo "Input file does not exists"
fi


splunk search command return only one result (maxout 1).

31 March 2015

Fix "System.Object[]" output when exporting to csv

export data to csv is sometimes broken because everything that is passed to Export-Csv cmdlet is casted as a string before the export.

one solution is to create a pscustomobject and use -Join operator on the troubeling property:


$user = Get-ADUser username -Properties memberof
[pscustomobject]@{
    DN = $user .DistinguishedName
    GivenName = $user .GivenName
    MemberOf = $user .MemberOf -Join ','
    Name = $user .Name
    SamAccountName = $user .SamAccountName
    UserPrincipalName = $user .UserPrincipalName
} | Export-Csv -NoTypeInformation .\user.csv





for a better arrangment Out-String cmdlet can be use in replace of Join operator

$user = Get-ADUser user  -Properties memberof
[pscustomobject]@{
    DN = $user.DistinguishedName
    GivenName = $user.GivenName
    MemberOf = ($user.MemberOf | Out-String).Trim()
    Name = $user.Name
    SamAccountName = $user.SamAccountName
    UserPrincipalName = $user.UserPrincipalName
} | Export-Csv -NoTypeInformation .\user.csv


Find domain controller with user replicated

When i'm creating a new user at the same time i'm trying to modify different properties on him like setup a manager, job title, include him in some groups ...and so on.

Sometimes the user is not replicated on all domain controllers in domain fast enough and any command after the New-ADUser will fail (with ADIdentityNotFoundException).

To overcome this problem i created a function that will find a domain controller on witch the user was replicated and used in the next commands as an argument for the Server parameter.


function Find-ReplicatedDC{
    param([string]$UserName)

    $AllDCinDomain = Get-ADDomainController -Filter *

    do{
        foreach( $DC in $AllDCinDomain){
                try{
                    $ADUser = Get-ADUser -Identity $username -Server $DC.HostName
                    $ReplicatedDC = $DC.HostName
                    break
                }
                catch{
                    Start-Sleep -Seconds 1
                }
        }
    }
    while(!$ReplicatedDC)

    return $ReplicatedDC
}

18 March 2015

Show tcp connections

netsh interface ipv4 show tcpconnections

16 February 2015

Variable scope

declare a variable in script scope

$Script:text  = 'text'


alternative to scope is synchronized collections

$hash = [hashtable]::Synchronized(@{})
$hash.text = "text"

15 February 2015

Workflow

Powershell workflow is part of .NET Windows Workflow Foundation.


  • survive reboots and recover automatically from failures
  • state can be saved; checkpoints can be set
  • parallelizable
  • activities run independently of one another
  • uses the same syntax as a powershell function

Workflow script activity keywords:
  • InlineScript - run standard cmdlets as an activity
  • Sequence - control the order of execution of multiple activities
  • Parallel - run multiple activities in parallel - command execution runs in arbitrary order.
  • Foreach -parallel - iterate through a collection in parallel. Command in the scriptblock run sequentially.
  • Checkpoint-Workflow - create an on disk representation of workflow state
  • Suspend-Workflow - allow a workflow to be suspended (can be resumed)

12 February 2015

ISE script debugging


F9   - set line breakpoint - the script will pause when the designated line must be executed

F10 - step over - executes the current statement and then stop at the next statement. If the current statements is a function or script call then the debugger executes the whole function or script, and it stops at the next statement.

F11 - step into - executes the current statement and then stops at the next statement. If the current statement is a function or script call, then the debugger steps into that function or script.

SHIFT + F11 - step out - steps out of the current function and up one level if the function is nested. If in the main body, the script is executed to the end, or to the next breakpoint.

F5 - continue - continues execution to the end, or to the next breakpoint.

09 February 2015

Motherboard model and manufacturer

Get-CimInstance Win32_BaseBoard | Select-Object Manufacturer, Product

Get-WmiObject Win32_BaseBoard | Select-Object Manufacturer, Product


Use wmic:

wmic baseboard get product, manufacturer

26 January 2015

Active Directory schema attribute details

$schema =[DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema()

$schema.FindClass('user').optionalproperties | Where-Object {$_.name -eq 'employeeid'}

11 January 2015

Scheduled jobs in powershell v3

PSScheduledJob is the module name.

Scheduled jobs can be viewed in Task Scheduler GUI.

Scheduled jobs cmdlet can only be used for the path: Microsoft\Windows\PowerShell\ScheduledJobs

SheduledTask module can be used to manage all other scheduled tasks (available only in Windows 8 and Server 2012).

Job definition and output is stored on disk in different files that can be found on:

%UserProfile%\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs\JobName

09 January 2015

About modules in powershell v3

Powershell have two default location in which it search for modules: one for the system and one for the user currently logged on:

  • system: %windir%\System32\WindowsPowerShell\v1.0\Modules
  • user: %UserProfile%\Documents\WindowsPowerShell\Modules
these values are stored in a environment variable $ENV:PSModulePath

Modules from this location will be automatically imported in powershell v3.

Get-Command cmdlet will return commands from imported or modules available in the two paths.

In powershell v3, modules can be imported (or listed) from another computer trough a cimsession or powershell session:

Import-Module -CimSession $session -Name ModuleName

Get-Module -CimSession $session -ListAvailable

PowerShell Web Access

PSWA (PowerShell Web Access) emulates a powershell console in a web browser.

PSWA is a feature (not a role) available only on Windows Server 2012.
It requires web server role (IIS).

Setup steps:

  • install PSWA windows feature
  • install the PSWA web application 
  • add PSWA authorization rules to control and secure access.

06 January 2015

Out-GridView enhancement in powershell v3

In powershell v3 cmdlet Out-GridView had a great enhancement with OutputMode parameter.

When used, this parameter instructs the cmdlet to send the items from the interactive window down the pipeline as input to another command.

By default, this cmdlet does not generate any output bat by using this OutputMode parameter, the user can select one or more items that will be send down the pipeline.

OutputMode can be set to:

  • None - no items.
  • Single - zero or one item can be selected.
  • Multiple - zero, one or more items can be selected to be send down the pipeline to the next cmdlet.
Example (will try to stop selected processes):

Get-Process | Out-GridView -OutputMode Multiple | Stop-Process

CIM cmdlets in powershell v3

In powershell v3 WMI cmdlets are replaced by CIM cmdlet which are used a little bit different then WMI cmdlets.

On example is the method invocation which cannot be done by referencing the object that contain the WMI data:

$wmi_object.method_name

CIM objects don't have all the relevant and useful methods that WMI objects have.

To discover methods that can be used for a specific class name we use:

Get-CimClass -ClassName Win32_Process | Select-Object -ExpandProperty CimClassMethods

after discovering the methods available we can invoke a method by using the Invoke-CimMethod cmdlet:

$CIMProcess | Invoke-CimMethod -MethodName Terminate

04 January 2015

Powershell v3 features



  • Ordered hash tables can be created by casting with [ordered] keyword:

    $hash = [ordered]@{firstname = 'John' ; lastname = 'Smith'}
  • Custom objects can be created more easy as hash table by casting with [PSCustomObject]
    it will be automatically ordered.

    $a = [PSCustomObject]@{firstname = 'John' ; lastname = 'Smith'}
  •  default parameters values can be set for cmdles.

    $PSDefaultParameterValues['Get-ADUser:Properties']='EmployeeID'

    will only be available in current session but can be added to profile and be loaded at start up.
    one disadvantage is that if you use that parameter in your comdlets the default value that was setup will be overwritten.
      
  • Count and Length property is available for all objects (even if the object is not an array).
    All objects can be indexed into with [ ]
    If the object already have an Count or Length property, they will remain unchanged,
  • ISE have now tabs - can be used for different remote sessions.

    tabs can be renamed: $psise.PowerShellTabs[0].DisplayName = 'Production Scripts'
    new tab can be opened: $PSISE.PowerShellTabs.Add()
  • in ISE explicit code regions can be used to allow collapsing between any two points

    #region some region description can be inserted here
    #endregion
  • ISE automatically highlight matching braces ( ) { } [ ] when cursor is in front of them.
  • current object in pipeline that use to be referred with $_ can also be referred with $PSItem variable.

02 January 2015

Update poweshell help for computers not connected to internet


Starting with powershell v3 the help files must be downloaded as separate files an can also be updated in case something has changed.

if the computer have a internet connection available Update-Help cmdlet will download and install the help or just update it if is allready installed.

if the computer does not have an internet connection available then the help files can be downloaded on a computer that have an internet connection available and then transferred to an internal network share or directly to the computer that need to update the help files.

to save the help files from the internet use:

Save-Help -DestinationPath c:\temp\PowershellHelpFiles

destination path can also be a network location \\fileserver\FolderName

After that, on the computer that need to be updated run a powershell console with elevated rights (RunAs Administrator) and type:

Update-Help -SourcePath c:\temp\PowershellHelpFiles

source path can also be a network location \\fileserver\FolderName