How to find mac address in active directory - powershell

Can you get mac addresses from Active Directory using Powershell? I am looking for a way to search for mac addresses in specific OUs if this is possible. Overall, I would like a dynamic way to find mac addresses for computers connected to the domain even if they are turned off and I thought AD might be a good way to go if possible. Thanks in advance for any help.

As the comments have said, that information is not held in Active Directory.
Consider using a computer start-up script to populate a field in AD with the mac address.
Also consider that many devices can have multiple mac addresses, some laptops may have 3 even.
This is an example based on a script I use (its in VBScript):
Option Explicit
Dim objRootDSE, objNetwork, objWMIService, objComputer
Dim strComputer, strMacAddresses
Dim colNetworkAdapterConfiguration, objNetworkAdapterConfiguration
Dim adoConnection, adoRecordset
strComputer = "."
strMacAddresses = ""
Set objRootDSE = GetObject("LDAP://RootDSE")
Set objNetwork = WScript.CreateObject("WScript.Network")
Set objWMIService = GetObject("Winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetworkAdapterConfiguration = objWMIService.ExecQuery("Select * From Win32_NetworkAdapter Where AdapterType = 'Ethernet 802.3' OR AdapterType = 'Wireless'")
strMacAddresses = ""
If Not colNetworkAdapterConfiguration Is Nothing Then
For Each objNetworkAdapterConfiguration in colNetworkAdapterConfiguration
If strMacAddresses <> "" Then
strMacAddresses = strMacAddresses & " "
End If
strMacAddresses = strMacAddresses & Trim(objNetworkAdapterConfiguration.MACAddress)
Next
End If
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
If Err.Number <> 0 Then
WScript.Quit
End If
Set adoRecordset = adoConnection.Execute("<LDAP://" & objRootDSE.Get("defaultNamingContext") & ">;(&(objectCategory=Computer)(name=" & objNetwork.Computername & "));adspath;subtree")
If Err.Number <> 0 Then
WScript.Quit
End If
If Not adoRecordset.EOF Then
Set objComputer = GetObject(adoRecordset.Fields(0).Value)
objComputer.Put "extensionAttribute1", strMacAddresses
objComputer.SetInfo
End If
If Err.Number <> 0 Then
WScript.Quit
End If

Related

Printers object in VB 6 not returning printer with special character in name

VB6 (not VB.Net or VBScript)
I'm using the Printer object and recently found that some printers
are not being returned if the name has certain characters.
In VB6 it would be something like:
Dim pr As Printer
For Each pr In Printers
MsgBox pr.DeviceName
Next pr
I can easily rename any printer in Windows (any OS version) and
make it fail.
I suspect it's related to a UTF-8/Unicode issue, but I don't know how to resolve it.
For example, this printer name works fine: "MyPrinter 1", but this does not: "MyPrinter 1 ę".
How can I get the Printer when the name has a non-standard (for US English anyway) character?
EDIT:
I've found this code to access the printers, and it will correctly return all of them, even with special characters.
However, I don't know how to either:
1) Use the object for printing (as I would with a Printers object)
2) Or set a Printer object to the returned object from WMI
(FYI - The InkEdit control will correctly show the special characters without any Unicode wrangling - I'm using for display purposes only.)
Dim strComputer As String
Dim objWMIService As Object
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters = objWMIService.ExecQuery ("Select * from Win32_Printer")
Dim myPrinter As Printer
Dim junk As String
For Each objprinter In colInstalledPrinters
List1.AddItem objprinter.Name & " --- " & objprinter.ShareName & " --- " & objprinter.ServerName
InkEdit1.Text = InkEdit1.Text & objprinter.Name & " --- " & objprinter.ShareName & " --- " & objprinter.ServerName & vbNewLine
If InStr(1, objprinter.Name, "HP") > -1 Then
myPrinter = objprinter.
End If
Next

Scan a subnet for an application that is NOT installed

I have been trying to come up with a script that will scan a specific subnet for an application not having been installed yet. I need to see if Lync is installed on some remote subnets before we turn up the sites live next month.
I have been running this as a logon script but it doesn't tell me what subnet they are in and it's not populating fast enough as users don't logoff.
On Error Resume Next
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objSysInfo = CreateObject("ADSystemInfo")
Set objNetwork = WScript.CreateObject("WScript.Network")
strValue = objShell.RegRead("HKCU\Software\MRC Custom\Skype_Audit")
If strValue <> "Gathered 1.0" Then
objShell.RegWrite "HKCU\Software\MRC Custom\Skype_Audit", "Gathered 1.0"
x86 = objShell.ExpandEnvironmentStrings("%PROGRAMFILES(x86)%")
skypePath = x86 & "\Microsoft Office\Office15\lync.exe"
If objFSO.FileExists(skypePath) Then
version = objFSO.GetFileVersion(skypePath)
Else
version = "not installed"
End If
'Bind to the users DN
strUserPath = "LDAP://" & objSysInfo.UserName
set objUser = GetObject(strUserPath)
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
'Write Data to Log File
Const ForAppending = 8
strPath = "\\mcjunkinredman\data\userpub\Skype_Audit\Log.txt"
Set objTextFile = objFSO.OpenTextFile(strPath, ForAppending, True)
objTextFile.WriteLine objUser.samAccountName & "|" & objNetwork.ComputerName & "|" & version
End If
VBScript or PowerShell is fine, any help would be appreciated.
I wrote an article a while back that provides a script that connects to remote computers and retrieves the applications that are installed:
Windows IT Pro: Auditing 32-Bit and 64-Bit Applications with PowerShell

VBscript - Body of text file into Email

i m using the following script to send a few emails during the day, it takes one or more parameters (there are a few versions) and is called by a .bat file. The script is :
Const schema = "http://schemas.microsoft.com/cdo/configuration/"
Const cdoBasic = 2
Const cdoSendUsingPort = 2
Dim oMsg, oConf
Dim sDateTimeStamp
Set args = WScript.Arguments
arg1 = args(0)
' E-mail properties
Set oMsg = CreateObject("CDO.Message")
oMsg.From = "myemail#gmail.com" ' or "Sender Name <from#gmail.com>"
oMsg.To = "otheremail#gmail.com" ' or "Recipient Name <to#gmail.com>"
oMsg.Subject = "System Message"
oMsg.BodyPart.Charset = "Windows-1253"
oMsg.Textbody = "Attached files." & vbcrlf & _
"This on a new line" & vbcrlf & _
"This on yet another"
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const FileToBeUsed = "DIRTEST.TXT"
Dim fso, f, g
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(FileToBeUsed, ForReading)
g = f.ReadAll
f.Close
Set f = Nothing
Set fso = Nothing
' GMail SMTP server configuration and authentication info
Set oConf = oMsg.Configuration
oConf.Fields(schema & "smtpserver") = "gmail.com" 'server address
oConf.Fields(schema & "smtpserverport") = 587 'port number
oConf.Fields(schema & "sendusing") = cdoSendUsingPort
oConf.Fields(schema & "smtpauthenticate") = cdoBasic 'authentication type
oConf.Fields(schema & "smtpusessl") = False 'use SSL encryption
oConf.Fields(schema & "sendusername") = "mymy#gmail.com" 'sender username
oConf.Fields(schema & "sendpassword") = "XXXXXX" 'sender password
oConf.Fields.Update()
'base64
' send message
oMsg.Send()
' Return status message
If Err Then
resultMessage = "ERROR " & Err.Number & ": " & Err.Description
Err.Clear()
Else
resultMessage = "Success Notification Message sent succesfully."
End If
Wscript.echo(resultMessage)
Right now the text body is set to :
Attached Files
This is a new line
This is yet another
I would like to interject a directory listing between line 1 and 2, either directly or by saving the directory listing in a text file, then putting the contents of said file in the email body, like so :
Attached Files
06/10/2016 <TIME> 13.000 Name1.txt
06/10/2016 <TIME> 300.000 Name2.pdf
06/10/2016 <TIME> 150.000 Name3.pdf
06/10/2016 <TIME> 5.000.000 Name4.pdf
This is a new line
This is yet another
EDIT : The above code succesfully appends the dir list to the mail subject, but also appends a batch of gibberish characters at the top.
The script is self explanatory
Edit: Formated size. Also note it give the size of folders. This can be slow, you may want to omit for folders. For instance the first time you run above code (on c:\ folder) windows has to read every folder into memory. That takes a while. Second time you run it all folders will be in the disk cache and it will be super fast.
Edit2 The VBS help file has recently been taken down at MS web site. It is available on my skydrive at https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw It's called script56.chm.
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set fldr = fso.GetFolder("c:\")
Set Fls = fldr.files
Set Fldrs = fldr.subfolders
For Each thing in Fls
A= A & vbtab & thing.name & vbtab & thing.attributes & vbtab & FormatNumber(thing.size, 0) & vbtab & Thing.DateLastModified & vbcrlf
Next
For Each thing in Fldrs
A= A & vbtab & thing.name & vbtab & thing.attributes & vbtab & FormatNumber(thing.size, 0) & vbtab & Thing.DateLastModified & vbcrlf
Next
msgbox a
msgbox a

vbscript with outdated MS Access and Outlook

I have a VBscript that I wrote for someone that access their Microsoft Access Database and sends an email, via Outlook, to people in the database if they fit a certain criteria. I have the script run every day via Task Manager. The important part of the script is to run completely in the background
I developed this script on Windows 7 with the 2013 version of Access and Outlook, but when I went to set up the code on the person's computer, they had an out-dated version of Microsoft Office (I'm pretty sure it's 2010 or 2007, but I'm not familiar with any Office products earlier than 2013). Everything worked fine on Windows 7 with Office 2013
When I ran the script I came across two errors:
Outlook prompted the user saying that a script is trying to automatically send an email and to allow it to do so.
The email wasn't went strait to the outbox and wouldn't send (although I'm pretty sure that's because I didn't set up the Outlook account right)
How can I fix this?
Here is the code:
Dim connStr, objConn, getNames
connStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\source\to\database.accdb"
Set objConn = CreateObject("ADODB.Connection")
objConn.open connStr
Set rs = objConn.execute("SELECT Fname, Email, VolunteerDate, ID, VolunteerTime FROM people")
DO WHILE NOT rs.EOF
getNames = getNames + rs.Fields(1) & ","
Dim diff
diff = DateDiff("d",Date,rs.Fields(2))
Select Case diff
Case 0
Call sendTodayEmail(rs.Fields(1),rs.Fields(2),rs.Fields(0), rs.Fields(4))
Case 7
Call sendWeekEmail(rs.Fields(1),rs.Fields(2),rs.Fields(0), rs.Fields(4))
Case else
End Select
rs.MoveNext
Loop
Sub sendTodayEmail(a,b,c,d)
dim objOutlk
dim objMail
dim strMsg
const olMailItem = 0
set objOutlk = createobject("Outlook.Application")
set objMail = objOutlk.createitem(olMailItem)
objMail.To = a
objMail.subject = "Automatic Email"
strMsg = "Hello " & c & ", this is a reminder that you are scheduled to help today at " & d
objMail.body = strMsg
objMail.Send
End Sub
Sub sendWeekEmail(a,b,c,d)
dim objOutlk
dim objMail
dim strMsg
const olMailItem = 0
set objOutlk = createobject("Outlook.Application")
set objMail = objOutlk.createitem(olMailItem)
objMail.To = a
objMail.subject = "Automatic Email"
strMsg = "Hello " & c & ", this is a reminder that you are scheduled to help one week from today at " & d & "." & vbCrLf & "Scheduled date: " & b & vbCrLf & "Scheduled time: " & d
objMail.body = strMsg
objMail.Send
End Sub
Set objConn = Nothing
Newer versions of Outlook will not display security prompts if an up-to-date version of an anti-virus app is installed.
Otherwise your options are either Extended MAPI (C++ or Delphi only), Redemption (any language - I am its author) or products like ClickYes.
See http://www.outlookcode.com/article.aspx?id=52 for more details.

Excel will not close processes

So, I'm using (after modification) this code, from here: How to set recurring schedule for xlsm file using Windows Task Scheduler
My error: Runtime error: Unknown runtime error.
I've searched far and wide to find an way to close the Excel process, but almost everybody uses .Quit sadly it gives the above error. I've also tried .Close, but that is not recognized
' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Tell Excel what the current working directory is
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = "C:\Users\hviid00m\Desktop"
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\Status Report (Boxplots) TEST.xlsm"
Set oWorkBook = myExcelWorker.Workbooks.Open (strWorkerWB, , , , , , True)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "Refresh"
on error resume next
myExcelWorker.Run strMacroName
if err.number <> 0 Then
WScript.Echo "Fejl i macro"
End If
err.clear
on error goto 0
oWorkBook.Save
' Clean up and shut down
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
myExcelWorker.Quit <--- ERROR
Set oWorkBook = Nothing
Set myExcelWorker = Nothing
Set WshShell = Nothing
Found some code on a different side.
The reason why (as far as I understood) is that .Quit and .Close is for VBA not VBS.
' Clean up and shut down
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
Dim objWMIService, objProcess, colProcess
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = " & "'EXCEL.EXE'")
For Each objProcess in colProcess
objProcess.Terminate()
Next`
Set oWorkBook = Nothing
Set myExcelWorker = Nothing
Set WshShell = Nothing