Tuesday, August 4, 2015

Create symLinks to project data folders and add projects to data groups from csv file with Powershell

This script creates symlinks on data folders based on CSV File and  names and adds project security groups to correct data groups.

Customer had a linux based file server on a MS Remote Desktop environment. They replaced it with Windows server, but they wanted to have the Windows server to act just like the old linux server. RD farm is locked down, and users cannot browse network or map drives on their own.  I have few other post how to map drives with login script with powershell. To make things a bit more tricky, they are using project-001 syntax on group and OU names, but 001 on folder names.

<#.Synopsis
This script makes symLinks to project data folders and adds projects to data groups from csv file.

File Format:
Project,Data

.Description
Writen by Miikka Kallberg
.Parameter FilePath
Path to CSV File
.Parameter csvfile
CSV File name
.Example
.\projectdatalinks.ps1 -FilePath c:\temp\ -csvfile project.csv
This will make link to project folders from Project.csv file
#>
#Define script parameters
Param([String]
[Parameter(Mandatory=$true)]
$FilePath='',
[Parameter(Mandatory=$true)]
$csvfile='')

#Define funtion for creating SymLinks
Function New-SymLink ($link, $target)
{
    if (test-path -pathtype container $target)
    {
        $command = "cmd /c mklink /d"
    }
    else
    {
        $command = "cmd /c mklink"
    }

    invoke-expression "$command $link $target"
}

#Import CSV file 
$projectCSV = Import-Csv "$FilePath\$csvfile" 

#Look each line
foreach ($csv in $projectcsv)
{
    #Define variables
    $Project = $csv.project
    $Data = $csv.data
    $datapath    = "\\server\data\data"
    $projectpath = "d:\fileshare\data\projects"
    $link        = "$projectpath\$project\data\$data"
    $target      = "$datapath\$data"
    $Projectgroup= "Project-$Project"
    $DataGroup   =  "data-$Data"
           
    #Create Data, Output and Work Folders under projects
    New-Item -ItemType Directory -Force -Path $projectpath\$project\data\
    New-Item -ItemType Directory -Force -Path $projectpath\$project\output\
    New-Item -ItemType Directory -Force -Path $projectpath\$project\work\

    #Check if link already exists    
    If (Test-Path $link){Write-Host $link already exists}
    Else{
    #Create SymLinks
    New-SymLink $link $target
    }

   # Add projects security groups to data group based on CSV file
    Add-ADGroupMember -Identity $DataGroup -Members $Projectgroup
    }

#Clear variables
    $csv         = ""
    $Project = ""
    $Data = ""
    $datapath    = ""
    $projectpath = ""
    $link        = ""
    $target      = ""
    $command     = ""

No comments:

Post a Comment