This is a sample of powershell code I used today at add functionality from a text file to AD while crossing the data to an SQL Server.
This script does a few useful things that I like, Starting with refreshing the Debug Environment, then opening an SQL connection, Parsing a textfile that’s ‘|’ pipe delimited then comparing with row’s returned from an SQL Query.

Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host

$ConnectionString = "Server=MYVM;Database=Mydatabase;Trusted_Connection=yes;"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection $ConnectionString 
$sqlConnection.Open()

$ActiveFeed = @{}
foreach($line in get-content "\\MYVM\d$\MyFeed.txt")
{
    $recipients = $line -split [RegEx]::Escape("|")
    $samAccountName = [string]
    $samAccountName = $recipients[0].trim()
        $WWW = $recipients[0].trim()
        $ActiveFeed.Add($samAccountName,$WWW) 
}

$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "select DISTINCT * FROM dbo.AppRights WHERE (AppName='ActiveDirectory' and RightsItem='DIR_SecurityGroup') and ((Dept = '0') and (Jobcode = '0') and (Entity = '0')) order by Dept, JobCode"
$DirectorTags = $sqlCommand.ExecuteReader()
try
{
    while ($DirectorTags.Read()) 
    {
        $ADTags.GetEnumerator() | ForEach-Object {
            if ($_.value -eq "DIR")
            {
                $message = '{0} is a {1}, it gets {2}!' -f $_.key, $_.value, $DirectorTags.GetValue(4)
                Write-Output $message
            }
        }
    }
}
catch
{
}
$DirectorTags.Close()

Leave a Reply

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

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax