Export Active Directory Computers to CSV

Quick power shell to run on a Domain Controller to export all Computers with last logged in time to a CSV file located in C:\Temp\ExportADComputers
Some code was based on a Technet example but improved for my use to get Extended details out.

Example of CSV output

name whenCreated IPv4Address OperatingSystem OperatingSystemVersion LastLogonDate Enabled
Computer-001 09/01/2017 18:05 10.x.x.x Windows 10 Pro 10.0 (14393) 09/01/2017 18:08 TRUE

###########################################################
# AUTHOR  : Darren Banfi
# CREATED : 11-04-2018 
# UPDATED : 
# COMMENT : This script exports Active Directory computers
#           to a a csv file.
###########################################################

#1.0 - First Release


# Created Folder automatically
New-Item -ItemType directory -Path C:\Temp\ExportADComputers

#Define location of my script variable
#the -parent switch returns one directory lower from directory defined. 
#below will return up to ImportADUsers folder 
#and since my files are located here it will find it.
#It failes withpout appending "*.*" at the end

$path = Split-Path -parent "c:\temp\ExportADComputers\*.*"

#Create a variable for the date stamp in the log file

$LogDate = get-date -f yyyyMMddhhmm

#Define CSV and log file location variables
#they have to be on the same location as the script

$csvfile = $path + "\ALLADComputers_$logDate.csv"

#import the ActiveDirectory Module

Import-Module ActiveDirectory


#Sets the OU to do the base search for all Computer accounts, change as required.

$OUpaths = GET-ADDomain | Select-Object -ExpandProperty ComputersContainer

#Get Admin accountb credential

$GetAdminact = Get-Credential

# loop though the array of OUs, adding the computers to a list ('Object' really)
foreach ($iOUpath in $OUpaths)
    {
        ($objComputers += Get-ADComputer -SearchBase $iOUpath -Properties * -Filter *)    #You might need to refine the query witha 'Filter' depending on your AD structure
    }


#Export CSV report

$objComputers | Select name, whenCreated,  IPv4Address, OperatingSystem, OperatingSystemVersion, LastLogonDate, Enabled | Export-Csv -LiteralPath  $csvfile -NoTypeInformation

#Open the folder on screen
ii C:\Temp\ExportADComputers

"Done"

GDPR – Encrypted Laptops

With the GDPR changes coming in to full swing, one part of the legislation is how Laptops and Remote devices should be encrypted.
Looking at solutions on how to do this, I decided to go with http://exo5.com to meet this requirement.

This system allows Windows 10 and Bitlocker to be controlled from a management page in the cloud by ways of an local agent sitting on the device.
This gives the benefit if the laptop is lost, The data cannot be accessed in a different device and the only way in would be by local password.

It also allows to lock the bootlocker down in case of a missing device prompting the finder to return it to us.

https://ico.org.uk/for-organisations/guide-to-data-protection/encryption/

Get files in folder and the date in vb.net

I’m using this in a project that monitor files on a server folder.
This folder contains any failures that have not processed on the server.
I then display this on a screen with the filename and date to make sure we know what it is and the time it happened.

           Dim files() As String = IO.Directory.GetFiles("X:\Path\To\Files")

            For Each file As String In files

                'Get the date and time modified of this file
                FDate = IO.File.GetLastWriteTime(file)
                'tidy the filename up by removing the .ext of the name
                file = Replace(file, ".ext", "")


                testBox.Text = testBox.Text + file + " " + FDate + Environment.NewLine

            Next

Windows 7 starting with a temporary profile

Ah the bane of many an IT Support Techie.

Try a restart or if that fails –
Quickest solution is to log in as a local admin / domain admin user and delete the users profile registry key out of HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Then log back in as the user and set there mail back up / desktop settings / other program settings.

Powershell w/ Exchange in vb.net – Work in Progress

I used this code to connect up to Exchange through Powershell with vb.net.

However this is not the release code used in my projects as thats went missing…. – so I’m sticking this here with a view to update if / when I find my code.

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim rsConfig As RunspaceConfiguration
        rsConfig = RunspaceConfiguration.Create()
        Dim snapInException As PSSnapInException = Nothing
        Dim info As PSSnapInInfo
        info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", snapInException)
        Dim myRunSpace As Runspace
        myRunSpace = RunspaceFactory.CreateRunspace(rsConfig)
        myRunSpace.Open()
        Dim pipeLine As Pipeline
        pipeLine = myRunSpace.CreatePipeline()
        Dim myCommand As New Command("Get-Command")
        pipeLine.Commands.Add(myCommand)
        Dim commandResults As System.Collections.ObjectModel.Collection(Of PSObject)
        commandResults = pipeLine.Invoke()
        For Each cmdlet As PSObject In commandResults
            Dim cmdletName As String
            cmdletName = cmdlet.Properties("Name").Value.ToString()

        Next

Get Current logged on Username – vb.net – using advapi32.dll

Note this codes about 6 years old as of 2014 – I’m sure there are better ways of doing this now but this worked at the time and is still live in one of my projects.

I needed to identify the currently logged on user running my application to make an audit file and also show only user options that the logged on user was setup for.

Here’s the code…

Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, _
ByRef nSize As Integer) As Integer

   Public Function GetUserName() As String
        'Gets currently logged on user - username
        Dim iReturn As Integer
        Dim userName As String
        'put the username in a string limit 50 chars
        userName = New String(CChar(" "), 50)
        'put the length of the username in an Integer iReturn
        iReturn = GetUserName(userName, 50)
        'Tidy up various formatting if required with the replace function like remove the .
        userName = userName.Replace("."c, " "c)
        
        'Return the username back
        GetUserName = userName.Substring(0, userName.IndexOf(Chr(0)))

    End Function

Using WMI Code Creator for projects

WMI Code Creator v1.0 – Download Here
Allows you to browse the available WMI classes and create query’s that can be used either through command-line through visual basic script or in your .NET projects.

Once you have your query you can then export the code for Visual C# or Visual Basic.

I used this program to create some code for a quick way of viewing installed printers on a remote print server in Visual C# by populating the results to a datagrid.

            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = userName.Text;
                connection.Password = password.Text;
                connection.Authority = "ntlmdomain:DOMAINNAME";
                ManagementScope scope = new ManagementScope(
                    "\\\\" + serverName.Text + ".FullyQualifiedDomainName\\root\\CIMV2", connection);
                scope.Connect();

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM Win32_Printer"); 

                ManagementObjectSearcher searcher =  new ManagementObjectSearcher(scope, query);

                    DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
                    row.Cells[0].Value = queryObj["DeviceID"];
                    row.Cells[1].Value = queryObj["DriverName"];
                    row.Cells[2].Value = queryObj["Location"];
                    row.Cells[3].Value = queryObj["Name"];
                    row.Cells[4].Value = queryObj["Comment"];
                    row.Cells[5].Value = queryObj["Portname"];
                    row.Cells[6].Value = queryObj["SystemName"];
                    dataGridView1.Rows.Add(row);
                    
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }

Fast and effective to what I needed – Instead of trying to copy all the printer details out in to excel.