PowerShell: Creating Clustered File Shares

# Define Destination Mount Points and UNC Paths
$arr=@{}
$arr["from"] = @{}; $arr["to"] = @{}    
$arr["from"] = @("Q:\ROLENAME\APPNAME"); $arr["to"]=@("\\ROLENAME-n\APPNAME")
$arr["from"] += "Q:\ROLENAME\APPNAME1"; $arr["to"] += "\\ROLENAME-n\APPNAME1"

# Specify the servers subnet to scan for available IPs
$serversCidrBlock="500.500.100.0/24"

<#
################################## Excuting Program as an Administrator ####################################
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
 
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
 
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
   {
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "Black"
   clear-host
   }
else
   {
   # We are not running "as Administrator" - so relaunch as administrator
   
   # Create a new process object that starts PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
   
   # Specify the current script path and name as a parameter
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
   
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
   
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
   
   # Exit from the current, unelevated, process
   exit
   }
 
Write-Host -NoNewLine "Running as Administrator..."
################################## Excuting Program as an Administrator ####################################
#>

<# If only requiring 1 set of variables
$regexServerName="\\\\(.{1,})\\"
$regexShareName="\\\\.+\\(.{1,})"
for ($i=0;$i -lt $arr.to.length;$i++){[void]($arr.to[$i] -match $regexServerName);$matches[1];}
for ($i=0;$i -lt $arr.to.length;$i++){[void]($arr.to[$i] -match $regexShareName);$matches[1];}
#>

# Extract variables from the provided array
$smbArray=@()
$regexServerNameAndShareName="\\\\(.{1,})\\(.{1,})"
for ($i=0;$i -lt $arr.to.length;$i++){[void]($arr.to[$i] -match $regexServerNameAndShareName);$smbArray+=,($arr.from[$i],$matches[1],$matches[2]);}

function scanForAvailableIPs{
    # This Get-IPrange function has been obtained at https://gallery.technet.microsoft.com/scriptcenter/List-the-IP-addresses-in-a-60c5bb6b
    # Snippet Author: BarryCWT
    function Get-IPrange{
      <# 
      .SYNOPSIS  
        Get the IP addresses in a range 
      .EXAMPLE 
       Get-IPrange -start 192.168.8.2 -end 192.168.8.20 
      .EXAMPLE 
       Get-IPrange -ip 192.168.8.2 -mask 255.255.255.0 
      .EXAMPLE 
       Get-IPrange -ip 192.168.8.3 -cidr 24 
        #> 
 
        param 
                            ( 
      [string]$start, 
      [string]$end, 
      [string]$ip, 
      [string]$mask, 
      [int]$cidr 
        ) 
 
        function IP-toINT64 () { 
          param ($ip) 
 
          $octets = $ip.split(".") 
          return [int64]([int64]$octets[0]*16777216 +[int64]$octets[1]*65536 +[int64]$octets[2]*256 +[int64]$octets[3]) 
        } 
 
        function INT64-toIP() { 
          param ([int64]$int) 

          return (([math]::truncate($int/16777216)).tostring()+"."+([math]::truncate(($int%16777216)/65536)).tostring()+"."+([math]::truncate(($int%65536)/256)).tostring()+"."+([math]::truncate($int%256)).tostring() )
        } 
 
        if ($ip) {$ipaddr = [Net.IPAddress]::Parse($ip)} 
        if ($cidr) {$maskaddr = [Net.IPAddress]::Parse((INT64-toIP -int ([convert]::ToInt64(("1"*$cidr+"0"*(32-$cidr)),2)))) } 
        if ($mask) {$maskaddr = [Net.IPAddress]::Parse($mask)} 
        if ($ip) {$networkaddr = new-object net.ipaddress ($maskaddr.address -band $ipaddr.address)} 
        if ($ip) {$broadcastaddr = new-object net.ipaddress (([system.net.ipaddress]::parse("255.255.255.255").address -bxor $maskaddr.address -bor $networkaddr.address))} 
 
        if ($ip) { 
          $startaddr = IP-toINT64 -ip $networkaddr.ipaddresstostring 
          $endaddr = IP-toINT64 -ip $broadcastaddr.ipaddresstostring 
        } else { 
          $startaddr = IP-toINT64 -ip $start 
          $endaddr = IP-toINT64 -ip $end 
        } 
 
 
        for ($i = $startaddr; $i -le $endaddr; $i++) 
        { 
          INT64-toIP -int $i 
        }

    }

    # Regex values
    $regexIP = [regex] "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
    $regexCidr=[regex] "\/(.*)"
    $regexFourthOctetValue=[regex] ".+\..+\..+\.(.+)"

    # Value Extractions
    $ip=$regexIP.Matches($serversCidrBlock).Value
    $cidr=$regexCidr.Matches($serversCidrBlock).Groups[1].Value
    [System.Collections.ArrayList]$allIPs=Get-IPrange -ip $ip -cidr $cidr

    # Remove fourth octet values matching 0,1, and 255
    if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 0){$first, $rest= $allIPs; $allIPs=$rest;}
    if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 1){$first, $rest= $allIPs; $allIPs=$rest;}    
    if($regexFourthOctetValue.Matches($allIPs[$allIPs.count-1]).Groups[1].Value -eq 255){$allIPs.RemoveAt($allIPs.count-1)}

    # Display sweep scanning output
    #$allIPs | ForEach-Object {if(!(Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*)){$_}}

    # Collect unpingable IPs
    "Collecting available IPs. Please wait awhile..."
    $GLOBAL:availableIPs=$allIPs|%{if(!(Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0"|select ProtocolAddress*)){$_}}
    
    # Return the Pingable IPs
    $GLOBAL:unavailableIPs=Compare-Object $allIPs $availableIPs -PassThru    
}

function createClusteredFileServers{
    # Extract server names
    $vFileServers=$smbArray | %{$_[1]} | Get-Unique

    # Proceed to create virtual file servers
    $i=0;
    foreach ($vServerLabel in $vFileServers){
        "Verify the accuracy of this statement. Press any key to commit.";
        "Add-ClusterFileServerRole -Name $vServerLabel -StaticAddress $($availableIPs[$i++]) -Storage $vServerLabel";
        pause;
        Add-ClusterFileServerRole -Name $vServerLabel -StaticAddress $($availableIPs[$i++]) -Storage $vServerLabel
        "$vServerLabel processed.";
    }
}

Function createShares{
    # Set PowerShell Gallery as Trusted to bypass prompts
    $trustPSGallery=(Get-psrepository -Name 'PSGallery' -ErrorAction SilentlyContinue).InstallationPolicy
    If($trustPSGallery -ne 'Trusted'){
        Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
        }

    # Add the required NTFS security module
    if (!(Get-InstalledModule -Name NTFSSecurity -ErrorAction SilentlyContinue)) {
	    Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -ErrorAction SilentlyContinue;
	    Install-Module -Name NTFSSecurity -Force -ErrorAction SilentlyContinue;
	    }
    
    # Add the required Microsoft Clustering PowerShell module
    if (!(get-module -Name "FailoverClusters" -ErrorAction SilentlyContinue)){
        #Install-WindowsFeature Failover-Clustering | out-null;
        Install-WindowsFeature RSAT-Clustering-MGMT | out-null;
        Install-WindowsFeature RSAT-Clustering-PowerShell | out-null;
        Import-Module FailoverClusters | out-null;
        }

    foreach ($smb in $smbArray){    
    # Assume variables
    $sharePath=$smb[0];
    $smbServer=$smb[1];
    $shareName=$smb[2];
    $domainadmins="$($env:USERDNSDOMAIN)`\Domain Admins";

    $statement="
    # Create directory and its parents if they do not exists
    New-Item -ItemType Directory -Force -Path $sharePath;

    # Set NTFS Permissions on folder
    Add-NTFSAccess –Path $sharePath –Account $identity –AccessRights Full -ErrorAction SilentlyContinue

    # Create the share
    New-SmbShare -ScopeName $smbServer -Name $shareName -Path $sharePath -FullAccess $identity -FolderEnumerationMode AccessBased
    "
    "Check these statements:`r`n $statement"
    pause;
    invoke-expression $statement
    }
}

"Run:
1. scanForAvailableIPs
2. createClusteredFileServers
3. createShares
"
pause;

Leave a Reply

Your email address will not be published. Required fields are marked *