Freitag, 7. Oktober 2016

SIDs and account names - a handy function for this

A handy function to get account names from SIDs and SIDs from account name, receiving local SIDs from remote machine will follow.

function Get-SID_NAME(
    [Parameter(Position=2)][string]$domain=$env:userdomain,
    [Parameter(Mandatory=$True,Position=1)][string]$search,
    [switch]$Local)
{
 if($search -match '\\'){
    $domain=$search.Split('\')[0]
    $search=$search.Split('\')[1]
    }
 if($search -match '^S-1-5-21-'){
    $objSID = New-Object System.Security.Principal.SecurityIdentifier($search)
    $objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
    return $objUser.Value
    }else{
        if($Local){
            $objUser = New-Object System.Security.Principal.NTAccount($search)
            $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
            return $strSID.Value
        } else {
            $objUser = New-Object System.Security.Principal.NTAccount($domain, $search)
            $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
            return $strSID.Value
        }
    }
}


Source from most of the code :

https://technet.microsoft.com/en-us/library/ff730940.aspx

Mittwoch, 1. Juni 2016

Powershell reporting and fixing up IPv4 Subnet masks in a Windows Enviroment

Here have some Powershell for fixing up a "wrong" static set Subnetmask, like you have after resizing a Subnet - or got the wrong mask reported from the network guys.

So you heard about some wrong set up Subnets, uups this can happen. So first i would like to report all my windows servers in my ActiveDirectory and their setup Subnet mask on the IP address which is in DNS. Observing the report before fixing maybe nice, thatswhy DO NOT just copy&paste this code in one Script and run, maybe put it in ISE and run just selected code.

#How to Report 

Import-Module ActiveDirectory

$reportfilename = c:\Report-SRVs_SubNets.csv

Function Get-DnsEntry($iphost)
{
 If($ipHost -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
  {
    [System.Net.Dns]::GetHostEntry($iphost).HostName
  }
 ElseIf( $ipHost )#-match "^.*\.\.*")
   {
    [System.Net.Dns]::GetHostEntry($iphost).AddressList[0].IPAddressToString
   } 
 ELSE { Throw "Specify either an IP V4 address or a hostname" }
}


$Servers = Get-ADComputer -Server $DCSRV -Filter {OperatingSystem -Like "*Server*"} -Properties *

$OutputReport = @()
[int64]$IntCounter=0
foreach ($Server in $Servers){
    $IntCounter+=1
    Write-Host $Server.Name " :  $IntCounter von " $Servers.Count
    $MYSRVInfo = '' |Select DNSHostname,DHCP,IPAddress,IPSubnet,Pingable,PWAge,OperatingSystemVersion,
    $MYSRVInfo.DNSHostname = $Server.DNSHostName
    if ($Server.DNSHostName) {$MYSRVInfo.IPAddress = Get-DnsEntry($Server.DNSHostName)}
    $MYSRVInfo.PWAge = $(New-TimeSpan -Start $([datetime]::FromFileTime($Server.pwdLastSet)) -End (get-date)).Days
    $MYSRVInfo.OperatingSystemVersion = $Server.OperatingSystemVersion
    $MYSRVInfo.Service_Pack = $Server.OperatingSystemServicePack
    try {
$IPCFG=Get-WmiObject -ComputerName $MYSRVInfo.IPAddress Win32_NetworkAdapterConfiguration -Properties IPAddress,IPSubnet,DHCPEnabled -ErrorAction Stop|?{$_.IPAddress -match $MYSRVInfo.IPAddress}
$MYSRVInfo.IPSubnet=$IPCFG.IPSubnet[$IPCFG.IPAddress.IndexOf($MYSRVInfo.IPAddress)]
$MYSRVInfo.DHCP=$IPCFG.DHCPEnabled
} catch {
$MYSRVInfo.IPSubnet='NOWMI'
$MYSRVInfo.DHCP='NOWMI'
}
    $MYSRVInfo.IPSubnet = 
    $OutputReport +=$MYSRVInfo
    if ($IntCounter % 20 -eq 0) {
        $OutputReport|Export-Csv -NoTypeInformation -Delimiter ';' -Path $reportfilename
        }
}

$OutputReport|Export-Csv -NoTypeInformation -Delimiter ';' -Path $reportfilename

# How To Fix now a certain Subnet from the Report

$ipscopetofixregex='10.1.2.*'
$rightsubnet='255.255.254.0'

# Filter now your Report 

$srvkaputt=Import-Csv -Delimiter ';' $reportfilename|?{($.IPAddress -match $ipscopetofixregex) -and ($_.IPSubnet -ne $rightsubnet) -and ([int]$_.DHCP -ne 1) -and ($_.DHCP -ne 'NOWMI')}

# Use WMI to fix it up - but be aware this code kills fixed IPv6 addresses and interrupt network traffic "slightly"

$srvkaputt|%{
    $ip=$_.IPAddress
    start-job -Args $_.IPAddress,$rightsubnet -scriptblock {
        param($ip,$sub)
        $IPCFG=(Get-WmiObject -ComputerName $ip Win32_NetworkAdapterConfiguration|?{$_.IPAddress -match $ip})
        $IPSUBNET=[string[]]($IPCFG.IPSubnet.Clone()|?{$_ -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"})
        $IPADDRES=[string[]]($IPCFG.IPAddress.Clone()|?{$_ -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"})
        $IPSUBNET[$IPADDRES.IndexOf($ip)]='$sub'
        $IPCFG.EnableStatic($IPADDRES,$IPSUBNET)
        }
    }

# Check with Get-Job maybe hunged jobs after a while and Kill them Get-Job|Remove-Job -f 

Montag, 2. Mai 2016

Delete huge folder structures where 260 character limit will stops you


Get annoyed by this fricking stupid path length limit of 260 characters when you just want a huge Folder send down the digital Jordan.
I needed this script to kill a folder structure on a Netapp FAS over CIFS with alot of personal folders (old profiles) with alot messed up ACLs. Be sure that you run it with a user which is in Administrator group.

https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath

This PS script walk recursivly through huge folder structures and rename them beginning from top to down 0-9999 before delete them in reverse order.

function Kill-FilePathLimit ([string]$fatpath)
{
    $list=Get-ChildItem -Directory $fatpath
    if ($list) {
        0..$($list.count - 1)|%{
            try{
                Rename-Item $list[$_].FullName $("{0:D4}" -f $_) -ErrorAction Stop
            } catch {
                $AccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name,"FullControl","Allow")
                $ICH = New-Object System.Security.Principal.NTAccount([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
                $ACL=Get-Acl $list[$_].FullName
                $acl.SetOwner($ICH)
                Set-Acl $list[$_].FullName -AclObject $acl
                $acl.SetAccessRule($AccessRule)
                Set-Acl $list[$_].FullName
                Rename-Item $list[$_].FullName $("{0:D4}" -f $_) -ErrorAction Stop
            }
        }
        Get-ChildItem -Directory $fatpath|%{
            Kill-FilePathLimit $_.FullName
        }
    } else {
        Remove-Item -Recurse $fatpath -Force -Confirm:$false
    }
}

Freitag, 22. Januar 2016

Netapp snapmirror from 7-mode to c-mode (cdot) fails with 'Source volume "7modefiler:vol_X" contains 32-bit data'

Imagine you have to snapmirror volumes from a old 7-mode filer to a new cDot one, off-course you read all the Blog-Posts, KBs and documents about. You know you have to convert any 32bit aggregates to 64bit first by adding disks (because your Ontap is below 8.1.4P4 where you can do this without).

About 32bit to 64bit conversion read here ..
https://kb.netapp.com/support/index?id=1014790

If your imagination is not ready - here the commands to create a snapmirror between 7-mode and cdot.

On 7modefiler:

wrfile -a /etc/snapmirror.allow cmodefiler-svm

On cmodefiler:

vserver peer transition create -local-vserver cmodefiler-svm -src-filer-name 7modefiler

network interface modify cmodefiler-svm_cifs_lif1 -vserver cmodefiler-svm -firewall-policy intercluster

network ping -lif cmodefiler-svm_cifs_lif1 -lif-owner cmodefiler-svm -destination 7modefiler

volume create -volume cmodefiler-svm_7mode_vol_X -aggregate cmodefiler-N_aggr_SATA -size 2048GB -type DP -vserver cmodefiler-svm

snapmirror create -source-path 7modefiler:vol_X -destination-path cmodefiler-svm:cmodefiler-svm_7mode_vol_X -type TDP

snapmirror initialize -destination-path cmodefiler-svm:cmodefiler-svm_7mode_vol_X

snapmirror modify -destination-path cmodefiler-svm:cmodefiler-svm_7mode_vol_X -schedule daily

According documentation it should work - but it fails and 'log show' on your c-mode filer show this,

Time                Node             Severity      Event
------------------- ---------------- ------------- ---------------------------
1/22/2016 15:30:03  cmodefiler-N ERROR         smc.snapmir.init.fail: Initialize from source volume '7modefiler:vol_X' contains 32-bit data' to destination volume 'cmodefiler-svm:cmodefiler-svm_7mode_vol_x' failed with error 'Source volume "7modefiler:vol_X" contains 32-bit data. Data transfer from a volume containing 32-bit data is not supported.'. Relationship UUID 'c0a9b225-c113-11e5-9430-xxxxxxxxx'.

while your 7-mode 'vol status' show this

7modefiler*> vol status
         Volume State           Status            Options
           vol0 online          raid_dp, flex     root, create_ucode=on, maxdirsize=73379
                                32-bit
   vol_X       online          raid_dp, flex     create_ucode=on, maxdirsize=73379
                                sis
                                64-bit

I had the luck that 1 of 4 aggregates on 7modefiler allready was 64bit, and the volumes on this aggregate worked fine. I thought with a beer on my sofa about the issue and i remembered that this aggregate was converted by myself some months ago. So what was the difference, the snapshots on the working volumes where already cycled since the conversion.

Rarely known FunFact : 32bit Snapshots were not converted to 64bit while the aggregate and volume itself were converted - they stay 32bit data - you have to delete all older snapshots.


Luckily i 
didn't had to care because i still have the older snapshots on the previous snapmirror destination - if someone would need a backup of his file ndmpcopy would bring it back.

7modefiler*> snap delete -a vol_X

To preserve the in between created 64bit snapshots do it per Powershell

Get-NAVolume|Get-NaSnapshot|?{$_.created -le [datetime]$('01.21.2016')}|Remove-NaSnapshot -Confirm:$false

The failed Snapmirror attempt leave the destination volume in a "unusable" state, so i had to destroy it and recreate again.

volume offline -volume cmodefiler-svm_7mode_vol_X -vserver cmodefiler-svm

snapmirror delete -destination-path cmodefiler-svm:cmodefiler-svm_7mode_vol_X 

volume destroy -volume cmodefiler-svm_7mode_vol_X -vserver cmodefiler-svm -force true

volume create -volume cmodefiler-svm_7mode_vol_X -aggregate cmodefiler-N_aggr_SATA -size 2048GB -type DP -vserver cmodefiler-svm

snapmirror create -source-path 7modefiler:vol_X -destination-path cmodefiler-svm:cmodefiler-svm_7mode_vol_X -type TDP

snapmirror initialize -destination-path cmodefiler-svm:cmodefiler-svm_7mode_vol_X

et voila Snapmirror does finaly what it should do.

cmodefiler-N::> snapmirror show
                                                                       Progress
Source            Destination Mirror  Relationship   Total             Last
Path        Type  Path        State   Status         Progress  Healthy Updated
----------- ---- ------------ ------- -------------- --------- ------- --------
7modefiler:vol_X
            TDP  cmodefiler-svm:cmodefiler-svm_7mode_vol_X
                              Uninitialized
                                      Transferring   22.30GB   true    01/22 16:27:42

If this article helped you - leave a comment.