Showing posts with label Networking. Show all posts
Showing posts with label Networking. Show all posts

POWERSHELL: List DL <> User Memberships (with a one-to-one mapping)

$dist = ForEach ($group in (Get-DistributionGroup -ResultSize Unlimited -Filter {name -like "*"})) 
   { Get-DistributionGroupMember $group -ResultSize Unlimited | Select @{Label="Group";Expression={$Group.Name}},@{Label="User";Expression={$_.Name}},SamAccountName,@{Label="Organizational Unit";Expression={$_.OrganizationalUnit}}  
   }
$dist | Sort Group,User | Export-CSV User2DL_Inventory.csv -NoTypeInformation

POWERSHELL: Update DNS Settings On Remote Systems

#------------begin script-----------------------------

$TimeStamp = Get-Date -UFormat "%Y%m%d-%H%M"               # Get date/time stamp of script runtime
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path      # Path of the script
$oldDNS     = "192.168.1.21"                               # DNS Server to replace
$newDNS     = "192.168.1.41"                               # replacement DNS Server
$List       = $ScriptPath + "\servers.txt                  # Input File containing the list of servers
$log        = New-Item -ItemType file -Path $ScriptPath -name change_DNS_$TimeStamp.csv -Force        # Log File

Add-Content -Path $log -Value "Servers,State"

[array]$List = get-content $List 
for($i=0; $i -lt $List.Length; $i++) 
{
    $Server = $List[$i]
    Write-Progress -Activity "Changing the DNS entries for " -Status "Server: $Server"
    if (Test-Connection -ComputerName $Server -Quiet) 
    {
        $colItems = get-wmiobject -class "Win32_NetworkAdapterConfiguration" -namespace "root\cimv2" -computername $Server | Where-Object {$_.IPEnabled -eq "True"}
            foreach ($objItem in $colItems)
            {
                $strDNSServerSearchOrder = $objItem.DNSServerSearchOrder
                $dnsexists = $strDNSServerSearchOrder -Contains $oldDNS
                if ($dnsexists -eq "True")
                {
                    $newArrDNS = $strDNSServerSearchOrder -replace ($oldDNS,$newDNS)
                    $objItem.setDNSServerSearchOrder($newArrDNS) | out-null
                    Add-Content -Path $log -Value "$($Server),OK"
                }
                else 
                {
                     Add-Content -Path $log -Value "$($Server),No concerns"
                }
            }
    }
    else 
    {
        Add-Content -Path $log -Value "$($Server),Offline"
    }
}

#------------End script--------------------------

POWERSHELL: Query Network Settings On Remote Systems

#------------begin script--------------------#------------begin script-----------------------------

$TimeStamp  = Get-Date -UFormat "%Y%m%d-%H%M"               # Get date/time stamp of script runtime
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path       # Path of the script
$List       = $ScriptPath + "\servers.txt"                  # Input File containing the list of servers
$log        = New-Item -ItemType file -Path $ScriptPath -name query_DNS_$TimeStamp.csv -Force            # Log File
$dnsexists  = "empty"

Add-Content -Path $log -Value "Servers,DNSHostName,MacAddress,IpAddress,IpSubnet,DefaultIpGateway,DNSServerSearchOrder,FullDNSREgistrationEnabled,DHCPEnabled"

[array]$List = get-content $List 
for($i=0; $i -lt $List.Length; $i++) 
{
    $Server = $List[$i]
    Write-Progress -Activity "Querying DNS for " -Status "Server: $Server"
    if (Test-Connection -ComputerName $Server -Quiet) 
    {
        $colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $Server -filter "IpEnabled = TRUE"
            foreach ($objItem in $colItems)
            {
                $strDNSServerSearchOrder = $objItem.DNSServerSearchOrder
                $dnsexists = $strDNSServerSearchOrder
                if ($dnsexists -ne "empty")
                    {
                        Add-Content -Path $log -Value `
                        "$($Server),$($objItem.DNSHostName),$($objItem.MacAddress),`
                        $($objItem.IpAddress),$($objItem.IpSubnet),$($objItem.DefaultIpGateway),`
                        $($objItem.DNSServerSearchOrder),$($objItem.FullDNSREgistrationEnabled),`
                        $($objItem.DHCPEnabled)"
                    }
                else 
                    {
                        Add-Content -Path $log -Value "$($Server),No comments"
                    }
                $dnsexists = "empty"
            }
    }
    else 
    {
        Add-Content -Path $log -Value "$($Server),Offline"
    }
}

#------------End script--------------------------

HOWTO: Scheduled Tasks and Powershell

Today I am going to fix a small creature comport (I use Google Drive to backup a drive that is not available to me 24 hours/day - as such, Google Drive errors when the drive cannot be found...and requires the application be restarted once the drive is online to resync). Easy-cheesy...use a scheduled task to run a Windows PowerShell command. Why blog about it? I have found the syntax of the command that can be a pain to work with. BONUS: Use the Start / Run command to test out your command prior to going to all the trouble to schedule it. HOWTO: call PowerShell, specify the command parameter, use the ampersand, a pair of curly brackets and the Windows PowerShell command I wish to run. Example syntax here:

Stop Google Drive Sync:
PowerShell -Command "& {Stop-Process -ProcessName googledrivesync}"
Start Google Drive Sync:
PowerShell -Command "& {Start-Process -ProcessName googledrivesync}"

Powershell: Retrieve Data from SQL database (placing data in a local CSV file)

Concern: I have a database that has near real-time data and I would like to use this data within PowerShell. How do I retreive this data and consume this within Powershell?

Example: You have a domain environment with ever changing server counts. You also use a network polling solution (example: LanSweeper) to audit your environment.

Note: To use the below, replace >>values<< with real world values.
#-------------------------Variables----------------------------
$SqlConnString = "Data Source=>>server<<;Database=>>database<<;User Id=>>username<<;Password=>>user password<<;" $CsvFile = ("file.csv") #-------------------------Functions---------------------------- Function RunServerQuery() { $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = $SqlConnString $SqlConnection.Open() $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandType = [System.Data.CommandType]'Text' $SqlCmd.CommandText = 'SELECT * FROM >>tablename<<' $SqlCmd.Connection = $SqlConnection $SqlCmd.CommandTimeout = 0 $da = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmd) $dt = New-Object System.Data.Datatable [void]$da.fill($dt) $SqlConnection.Close() #wrap the function result in an array because PowerShell automatically #unravels any enumerable object sent through the pipeline into an array return @(,$dt) } Clear-Host $dt = RunServerQuery #$dt | Format-Table -autosize $dt | Export-CSV $CsvFile -NoType -ErrorAction SilentlyContinue

Powershell: Obtain System Uptime

$operatingSystem = Get-WmiObject Win32_OperatingSystem
$lastboottimedate = `
[Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)
$currentdate = `
[Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.localDateTime)
$up = $currentdate-$lastboottimedate
$uptime = "System has been up for " + $up.Days + " Days " + $up.Hours + `
" Hours " + $up.Minutes + " Minutes " + $up.Milliseconds + " Milliseconds"
$uptime

Education: Cryptography Course

Take the World's Best Courses, Online, For Free

I have signed up for a free Cryptography course offered by Stanford University (learn about the inner workings of cryptographic primitives and how to apply this knowledge in real-world applications!) which begins this week.
Started on: 27 August 2012 (6 weeks long)
Workload: 5-7 hours/week
Computer Science: Theory
Computer Science: Systems, Security, Networking
https://www.coursera.org/course/crypto