Runas with Passthrough Credentials

email me

sPassword = InputBox(“Password”)’password could be here, but needs to be compiled if so
with CreateObject(“WScript.Shell”)
.Run “runas /user:domain\user \\unc\location\Install.bat”, 1, False
Do Until .AppActivate(“runas.exe”) : WSH.Sleep 100 : Loop
.Sendkeys sPassword& “~”
end with

* I have not tested this beyond the lab

Locked Library.itl iTunes.itl file when Opening iTunes

email me

Solution 1

This usually happens because, somehow the iTunes Library.itl file got set as read only. You can fix this by doing the following steps:

1. Open the My Documents folder.

2. Open the My Music folder.

3. Open the iTunes folder

4. Right-click the iTunes Library.itl file and select Properties.

5. Uncheck Read-only.

6. If you have a Security tab, select it. Ensure that your account has Full Control permissions to the file. If you don’t have this tab, ignore this step.

7. Click OK.

Now you should be able to start iTunes without the error. If not, your music files may actually be set to where you don’t have proper permissions. Check it with these steps.

1. Navigate to the location where the music files are located. For Windows 7 users, it’s normally in the C:\Users\username\Music\iTunes\iTunes Media folder.

2. Right-click the iTunes Media folder, then select Properties.

3. Ensure that the Hidden and Archive boxes aren’t checked. If you have a permissions tab, check to see that you have it set to “Full Control” and that nothing is set to “Deny”.

 

Solution 2

1. Back up/copy your “locked” iTunes (library files etc).

2. Move “iTunes Library”, “iTunes Library Extras.itdb”, “iTunes Library Genius.itdb” and “iTunes Music Library.xml” out of your “locked” iTunes folder to somewhere safe, you’ll need them again in a sec.

3. Now the only thing in the “locked” iTunes folder will be the “Album Artwork”, “iTunes Music” and “Previous iTunes Libraries” folders.

4. Create a new “blank” iTunes library, (hold option as you launch iTunes). Select “create library”. Make a new iTunes library elsewhere on your drive. Quit iTunes. You now have a blank iTunes with blank “iTunes Library”, “iTunes Library Extras.itdb”, “iTunes Library Genius.itdb” and “iTunes Music Library.xml” folders which you can put in a folder called “blank”. Keep this in your “Previous iTunes Libraries” folder for when this problem comes around again (which it will).

5. Copy all these blank iTunes files from the “blank” folder into your “locked” iTunes folder.

6. Start iTunes (option-launch to reselect your “locked” iTunes folder). It opens up empty. Quit iTunes.

7. Delete the new “blank” files from the “locked” iTunes folder.

8. Copy your old files from your back up folder, into your “locked” iTunes folder.

9. Start iTunes again. Everything should be back to normal!

 

Code Snippet

This is part of the code I used to automate this process.

strComputer = “.”

Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set objRegistry=GetObject(“winmgmts:\\” & strComputer & “\root\default:StdRegProv”)
strKeyPath = “SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\ProfileList”
objRegistry.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubkeys
For Each objSubkey In arrSubkeys
on error resume next
strValueName = “ProfileImagePath”
strSubPath = strKeyPath & “\” & objSubkey
objRegistry.GetExpandedStringValue HKEY_LOCAL_MACHINE,strSubPath,strValueName,strValue
Const POPUP_TITLE = “User To SID Conversion”
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set objAccount = objWMIService.Get(“Win32_SID.SID='” & objSubkey & “‘”)
strUser = objAccount.AccountName
‘strDomain = objAccount.ReferencedDomainName’returns referenced domain

‘DISPLAY PROFILE NAME & SID
objSubkey = trim(objSubkey)’trims whitespace
strUser = trim(strUser)’trims whitespace
‘msgbox “objSubkey: ” & objSubkey’returns SID
‘msgbox strUser’returns username

‘LOGIC TO DETERMINE IF REGISTRY ACCOUNT IS TO BE LOADED
if strUser = “SYSTEM” then strUser=””
if strUser = “LOCAL SERVICE” then strUser=””
if strUser = “NETWORK SERVICE” then strUser=””
‘if strUser = “ADMINISTRATOR” then strUser=””

if strUser <> “” then
on error resume next

‘prevents the library.itl error from appearing
objShell.Run “%comspec% /c del /q ” & chr(34) & “C:\users\” & strUser & “\Music\iTunes\iTunes Library.itl” & chr(34),0,false

Database Mail XPs Server Configuration Option

email me

Access the SQL Databases page

Use the Database Mail XPs option to enable Database Mail on this server. The possible values are:

  • 0 indicating Database Mail is not available (default).
  • 1 indicating Database Mail is available.

The setting takes effect immediately without a server stop and restart.

After enabling Database Mail, you must configure a Database Mail host database to use Database Mail.

Configuring Database Mail using the Database Mail Configuration Wizard enables the Database Mail extended stored procedures in the msdb database. If you use the Database Mail Configuration Wizard, you do not have to use the sp_configure example below.

Setting the Database Mail XPs option to 0 prevents Database Mail from starting. If it is running when the option is set to 0, it continues to run and send mail until it is idle for the time configured in the DatabaseMailExeMinimumLifeTime option.

The following example enables the Database Mail extended stored procedures.

sp_configure ‘show advanced options’, 1;
 GO
 RECONFIGURE;
 GO
 sp_configure ‘Database Mail XPs’, 1;
 GO
 RECONFIGURE
 GO

 

 EXECUTE msdb.dbo.sysmail_add_profile_sp
 @profile_name = ‘notifications’,
 @description = ‘profile for sending outgoing notifications’
 GO

 

 EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
 @profile_name = ‘notifications’,
 @principal_name = ‘public’,
 @is_default = 1;
 GO

 

 EXECUTE msdb.dbo.sysmail_add_account_sp
 @account_name = ‘Gmail’,
 @description = ‘Account for outgoing notifications’,
 @email_address = ‘mrnettek@gmail.com’,
 @display_name = ‘SQL Trigger Alert’,
 @mailserver_name = ‘smtp.gmail.com’,
 @port = 587,
 @enable_ssl = 1,
 @username = ‘mrnettektesting@gmail.com’,
 @password = ‘NotReallyMyPassword’
 GO

 

EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = ‘Notifications’,
@account_name = ‘Gmail’,
@sequence_number = 1
GO

 
Code to use to send email

EXEC msdb.dbo.sp_send_dbmail
@profile_name = ‘notifications’,
@recipients = ‘mrnettektesting@gmail.com’,
@body = ‘This is a test’, —- could also be contents of a change
@subject = ‘Change is product notification’
GO

 

Sample email

 

Further Information

Database Mail is an enterprise solution for sending e-mail messages from the SQL Server Database Engine. Using Database Mail, your database applications can send e-mail messages to users. The messages can contain query results, and can also include files from any resource on your network.


Database Mail is designed for reliability, scalability, security, and supportability.

Reliability

  • Database Mail uses the standard Simple Mail Transfer Protocol (SMTP) to send mail. You can use Database Mail without installing an Extended MAPI client on the computer that runs SQL Server.
  • Process isolation. To minimize the impact on SQL Server, the component that delivers e-mail runs outside of SQL Server, in a separate process. SQL Server will continue to queue e-mail messages even if the external process stops or fails. The queued messages will be sent once the outside process or SMTP server comes online.
  • Failover accounts. A Database Mail profile allows you to specify more than one SMTP server. Should an SMTP server be unavailable, mail can still be delivered to another SMTP server.
  • Cluster support. Database Mail is cluster-aware and is fully supported on a cluster.

Scalability

  • Background Delivery: Database Mail provides background, or asynchronous, delivery. When you call sp_send_dbmail to send a message, Database Mail adds a request to a Service Broker queue. The stored procedure returns immediately. The external e-mail component receives the request and delivers the e-mail.
  • Multiple profiles: Database Mail allows you to create multiple profiles within a SQL Server instance. Optionally, you can choose the profile that Database Mail uses when you send a message.
  • Multiple accounts: Each profile can contain multiple failover accounts. You can configure different profiles with different accounts to distribute e-mail across multiple e-mail servers.
  • 64-bit compatibility: Database Mail is fully supported on 64-bit installations of SQL Server.

Security

  • Off by default: To reduce the surface area of SQL Server, Database Mail stored procedures are disabled by default.
  • Mail Security:To send Database Mail, you must be a member of the DatabaseMailUserRole database role in the msdb database.
  • Profile security: Database Mail enforces security for mail profiles. You choose the msdb database users or groups that have access to a Database Mail profile. You can grant access to either specific users, or all users in msdb. A private profile restricts access to a specified list of users. A public profile is available to all users in a database.
  • Attachment size governor: Database Mail enforces a configurable limit on the attachment file size. You can change this limit by using the sysmail_configure_sp stored procedure.
  • Prohibited file extensions: Database Mail maintains a list of prohibited file extensions. Users cannot attach files with an extension that appears in the list. You can change this list by using sysmail_configure_sp.
  • Database Mail runs under the SQL Server Engine service account. To attach a file from a folder to an email, the SQL Server engine account should have permissions to access the folder with the file.

Supportability

  • Integrated configuration: Database Mail maintains the information for e-mail accounts within SQL Server Database Engine. There is no need to manage a mail profile in an external client application. Database Mail Configuration Wizard provides a convenient interface for configuring Database Mail. You can also create and maintain Database Mail configurations using Transact-SQL.
  • Logging. Database Mail logs e-mail activity to SQL Server, the Microsoft Windows application event log, and to tables in the msdb database.
  • Auditing: Database Mail keeps copies of messages and attachments sent in the msdb database. You can easily audit Database Mail usage and review the retained messages.
  • Support for HTML: Database Mail allows you to send e-mail formatted as HTML.

Database Mail is designed on a queued architecture that uses service broker technologies. When users execute sp_send_dbmail, the stored procedure inserts an item into the mail queue and creates a record that contains the e-mail message. Inserting the new entry in the mail queue starts the external Database Mail process (DatabaseMail.exe). The external process reads the e-mail information and sends the e-mail message to the appropriate e-mail server or servers. The external process inserts an item in the Status queue for the outcome of the send operation. Inserting the new entry in the status queue starts an internal stored procedure that updates the status of the e-mail message. Besides storing the sent, or unsent, e-mail message, Database Mail also records any e-mail attachments in the system tables. Database Mail views provide the status of messages for troubleshooting, and stored procedures allow for administration of the Database Mail queue.

 

msdb sends messages to an SMTP mail server


Database Mail consists of the following main components:

  • Configuration and security componentsDatabase Mail stores configuration and security information in the msdb database. Configuration and security objects create profiles and accounts used by Database Mail.
  • Messaging componentsThe msdb database acts as the mail-host database that holds the messaging objects that Database Mail uses to send e-mail. These objects include the sp_send_dbmail stored procedure and the data structures that hold information about messages.
  • Database Mail executableThe Database Mail executable is an external program that reads from a queue in the msdb database and sends messages to e-mail servers.
  • Logging and auditing componentsDatabase Mail records logging information in the msdb database and the Microsoft Windows application event log.

Configuring Agent to use Database Mail:

 

SQL Server Agent can be configured to use Database Mail. This is required for alert notifications and automatic notification when a job completes.

Caution note Caution
Individual job steps within a job can also send e-mail without configuring SQL Server Agent to use Database Mail. For example, a Transact-SQL job step can use Database Mail to send the results of a query to a list of recipients.

You can configure SQL Server Agent to send e-mail messages to predefined operators when:

  • An alert is triggered. Alerts can be configured to send e-mail notification of specific events that occur. For example, alerts can be configured to notify an operator of a particular database event or operating system condition that may need immediate action. For more information about configuring alerts.
  • A scheduled task, such as a database backup or replication event, succeeds or fails. For example, you can use SQL Server Agent Mail to notify operators if an error occurs during processing at the end of a month.

iTunes Deployment

email me

You will have to customize iTunes by creating an MST file.

1) Change the following Public Properties in the MST:
DESKTOP_SHORTCUTS = 0
DISABLEADVTSHORTCUTS = 0
SCHEDULE_ASUW = 0
AMDS_IS_INSTALLED = 1
BONJOUR_IS_INSTALLED = 1
REBOOT = ReallySuppress
NO_ASUW = 0
NO_BONJOUR = 0
IAcceptLicense = Yes
REGSRCH_DESKTOP_SHORTCUTS = 0

2) Install iTunes on a test machine and make all the customizations you want. All the customizations will be stored in following files:

a) “%userprofile%\AppData\Local\Apple Computer\iTunes\cache.db
b) “%userprofile%\AppData\Local\Apple Computer\iTunes\iTunesPrefs.xml”
c) “%userprofile%\AppData\Roaming\Apple Computer\iTunes\iTunesPrefs.xml”
d) “%userprofile%\AppData\Roaming\Apple Computer\iTunes\Preferences\com.apple.iTunes.plist”
e) “%userprofile%\AppData\Roaming\Apple Computer\iTunes\Preferences\keychain.plist”

Copy these files in C:\ProgramData\Apple Computer\iTunes\ folder in your MST file and then use the below script to run in Custom Action just before InstallFinalize. Condition to be kept as NOT REMOVE~=”ALL”

‘Used to copy the config file to the current user\appdata\local directory.

on error resume next
Set oShell = CreateObject( “WScript.Shell” )
userprofile=oShell.ExpandEnvironmentStrings(“%USERPROFILE%”)
systemdrive=oShell.ExpandEnvironmentStrings(“%SYSTEMDRIVE%”)
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set afile = fso.GetFile(systemdrive & “\ProgramData\Apple iTunes\local\cache.db”)
strDestination1 =userprofile & “\AppData\Local\Apple Computer\iTunes\cache.db”
Set bfile = fso.GetFile(systemdrive & “\ProgramData\Apple iTunes\local\iTunesPrefs.xml”)
strDestination2 =userprofile & “\AppData\Local\Apple Computer\iTunes\iTunesPrefs.xml”
Set cfile = fso.GetFile(systemdrive & “\ProgramData\Apple iTunes\Roaming\iTunesPrefs.xml”)
strDestination3 =userprofile & “\AppData\Roaming\Apple Computer\iTunes\iTunesPrefs.xml”
Set dfile = fso.GetFile(systemdrive & “\ProgramData\Apple iTunes\Roaming\Preferences\com.apple.iTunes.plist”)
strDestination4 =userprofile & “\AppData\Roaming\Apple Computer\iTunes\Preferences\com.apple.iTunes.plist”
Set efile = fso.GetFile(systemdrive & “\ProgramData\Apple iTunes\Roaming\Preferences\keychain.plist”)
strDestination5 =userprofile & “\AppData\Roaming\Apple Computer\iTunes\Preferences\keychain.plist”

fso.CreateFolder(userprofile & “\AppData\Local\Apple Computer”)
fso.CreateFolder(userprofile & “\AppData\Local\Apple Computer\iTunes”)
fso.CreateFolder(userprofile & “\AppData\Roaming\Apple Computer”)
fso.CreateFolder(userprofile & “\AppData\Roaming\Apple Computer\iTunes”)
fso.CreateFolder(userprofile & “\AppData\Roaming\Apple Computer\iTunes\Preferences”)
afile.Copy(strDestination1)
bfile.Copy(strDestination2)
cfile.Copy(strDestination3)
dfile.Copy(strDestination4)
efile.Copy(strDestination5)

Return COUNT from SQL Database using VBScript

email me

DIM Connection, Recordset, SQL, Server, field, strAllFields

‘Create an instance of the ADO connection and recordset objects

SET Connection = CreateObject(“ADODB.Connection”)
SET Recordset = CreateObject(“ADODB.Recordset”)

‘Open the connection to the database – CONNECTION STRING
Connection.Open “DSN=test;UID=ENTER_USERNAME;PWD=ENTER_PASSWORD;Database=pubs”

‘Declare the SQL statement that will query the database
SQL = “SELECT COUNT(au_lname) as COUNTER FROM dbo.authors”

Recordset.Open SQL,Connection

IF Recordset.EOF THEN
wscript.echo “There are no records to retrieve; Check that you have the SQL query.”
ELSE
‘If there are records then loop through the fields
DO WHILE NOT Recordset.Eof
wscript.echo Recordset(“COUNTER“)
Recordset.MoveNext
LOOP
END IF

‘close connection
Connection.Close
WScript.Quit

How to Connect to a SQL Database and Return Record Data with VBScript

email me

‘Make sure your database is online and ready to use

‘To create a  DSN, just follow this link

The Script

Dim Connection, Recordset, SQL, Server, field, strAllFields

‘Declare the SQL statement that will query the database
SQL = “SELECT * FROM dbo.authors”

”’other sql statements
”’SQL = “SELECT DISTINCT * FROM dbo.authors ORDER BY au_lname DESC”

‘Create an instance of the ADO connection and recordset objects
Set Connection = CreateObject(“ADODB.Connection”)
Set Recordset = CreateObject(“ADODB.Recordset”)

‘Open the connection to the database
Connection.Open
“DSN=test;UID=ENTER_USERNAME;PWD=ENTER_PASSWORD;Database=pubs”

‘Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection

‘Determine whether there are any records
If Recordset.EOF Then
wscript.echo “There are no records to retrieve; Check that you have the correct SQL query.”
Else
‘if there are records then loop through the fields
Do While NOT Recordset.Eof

‘What I want to return
field = Recordset(“au_lname”)

”’return more than one column
”’field = Recordset(“au_lname”) & “, ” & Recordset(“au_fname”)

‘Store all returned values into a string
if field <> “” then
strAllFields = chr(13) & field + strAllFields
end if

Recordset.MoveNext
Loop
End If

‘Display all values
msgbox “Author Names ” & chr(13) & chr(13) & strAllFields

‘Close the connection and recordset objects to free up resources
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing

 

For my reference

When working with Microsoft Access databases (or any other databases, for that matter) there are 4 types of SQL statements (or queries) that can be used to work with the information in the database, and these SQL statements are:

• select – obtain information from the database
• insert – add a new record into the database
• delete – remove records from the database
• update – change the details contained in the database

And all of these SQL statements can be used with VBScript – however, the first step is to connect to the database.
Connecting to a Microsoft Access Database
A programmer can easily use VBScript to make a connection to a Microsoft Access database by making use of one of Microsoft’s Active Data Objects:

dim connection_string : connection_string = _
“provider=microsoft.jet.oledb.4.0;” _
& “data source=c:\customer.mdb”
dim conn : set conn = createobject(“adodb.connection”)
conn.open connection_string

In this example a connection is made to the database using the Microsoft Jet engine and accesses a Microsoft .mdb file. Then, with the connection in place, the programmer can then use VBScript to run queries and work with the contents of the database


The Select Query

The select query is perhaps the most commonly used query – this extracts information from the database and, in the case of VBScript, any results from the query are loaded into a recordset – in this example the contents of the id field from the name table are loaded into the recordset:

dim sql : sql = “select id from name”
dim rs : set rs = createobject(“adodb.recordset”)
rs.cursorlocation = 3 ‘Use a client-side cursor
rs.open sql, conn, 3, 3
‘A static copy of a set of records, locked only when updating

The contents of the recordset can then be used in VBScript – in this case to obtain a new id number for use in the database’s name table:

rs.movelast
dim id
if not rs.eof then
id = rs.Fields(0) + 1
else
id = 1
end if
msgbox id

This new id can be used when a new record is added to the table.

The Insert Statement
The next statement – the insert statement – adds a new record to a table:

dim surname : surname = “jones”
dim firstname : firstname = “john”
sql = _
“insert into name (id, surname,firstname)” _
& ” values (” & id & “,'” & surname & “‘,'” & firstname & “‘)”
conn.Execute sql

The insert statement is different from the select statement in that there is no result returned to VBScript – another select statement would have to be used in order to examine the new contents of the table.

The Delete Statement

The insert statement adds a record to a table and so, of course, the delete statement removes a record:
sql = _
“delete from name” _
& ” where surname = ‘” & surname & “‘” _
& ” and firstname = ‘” & firstname & “‘”
conn.Execute sql

As with the insert statement no result is returned.

The Update Query

The final statement – update – modifies a record in a database table, and so this next example inserts and then updates a record:
surname = “smith”
firstname = “jane”
sql = _
“insert into name (id, surname,firstname)” _
& ” values (” & id & “,'” & surname & “‘,'” & firstname & “‘)”
conn.Execute sql
dim new_surname : new_surname = “smyth”
sql = _
“update name” _
& ” set surname = ‘” & new_surname & “‘” _
& ” where surname = ‘” & surname & “‘” _
& ” and firstname = ‘” & firstname & “‘”
conn.Execute sql

And again no result would be returned and a select statement would be needed for the updated contents to be viewed.


Summary

The 4 types of SQL statements (or queries) used with databases, such as Microsoft Access, are:

• select
• insert
• delete
• update

Each can be used with VBScript by making use of Microsoft’s Active Data Objects which make data manipulation very easy:

• use the ADO to connect to the database
• use the ADO to create a recordset from the select statement.
• use the ADO to change the contents of the database using insert, delete and update statements

Giving the VBScript programmer full control of any database.

Issues Resulting in BitLocker Recovery Mode and Their Resolution

email me

Specific operations or actions will cause BitLocker to go into Recovery Mode and ask you to enter the 48-digit Recovery Key. This can be caused by several things, and a complete list can be viewed here, but today I am going to go over the most common issues.

Scenario # 1:      When you are using a Laptop or Desktop computer and do not have the BIOS Boot order with the OS HDD listed as the first boot device. The reason for this is the boot device makes up part of the system measurement used by BitLocker and this must remain consistent to validate the system status and unlock BitLocker. (I.e. if you have the DVD-ROM drive listed first and had a bootable media inserted, this can cause the system measurement to change.) Some firmware will also treat PXE network boot as a change in boot order – even when the user does not choose network boot. Changing from a wireless to wired network can trigger a recovery event. Putting the HDD first in boot order generally eliminates these issues.

Resolution:

o   Suspend Bitlocker drive encryption by typing “manage-bde -protectors -disable c:” from an elevated command prompt.

o   Go into the BIOS and change the Boot Order so the OS HDD is first in the list.

o    By default from most hardware vendors, the HDD is not the first boot device.

o    If you have a laptop with a docking station, make sure that it is plugged into the docking station, in order to make sure that the external devices presented by the docking station are present in BIOS.

o    Boot into the Operating System and run “manage-bde -protectors -enable c:

Scenario # 2:      When you are either deploying a new system or encrypting the drive for the first time. You might pause the Bitlocker encryption process, in order to speed up the performance or while performing other tasks, so that encryption can run later or you need more than the 6 GB worth of free space to continue deploying the system. When you run “manage-bde -pause c:” you are pausing the drive encryption of C:, but not the Bitlocker protectors on the system.

You might say to yourself, if I run “manage-bde -status c:” I see that the protection is off on that drive. The reason you see this is that the protection for the drive is not yet completed, but the clear text key still exists.

Volume C: [] [OS Volume]    Size:                 37.17 GB    BitLocker Version:   Windows 7    Conversion Status:   Encryption Paused    Percentage Encrypted: 3%    Encryption Method:   AES 128 with Diffuser    Protection Status:   Protection Off <— Where it shows “Protection Off”    Lock Status:         Unlocked    Identification Field: None

Resolution:

o   When you need to pause the encryption, whether for performance or drive space reasons, you need to run “manage-bde -pause c:

o   After encryption has been paused, you will want to run “manage-bde -protectors -disable c:

o   Once you have completed your tasks and wish to start the encryption process again you can run “manage-bde -resume c:

o   Once the encryption is complete, or if you have completed your tasks, you will then want to run “manage-bde -protectors -enable c:

Scenario # 3:      The BIOS / TPM firmware are out of date on the systems.

Resolution:

o   Suspend Bitlocker drive encryption “manage-bde –protectors –disable c:

o   Update the BIOS on the system

o    If there is a TPM Firmware update, please follow the vendor installation instructions.

o   Reboot the Operating System and run “manage-bde –protectors –enable c:

Scenario # 4:      When you are installing additional language packs onto the system, and selecting the option to apply the language settings to all users and system accounts. This causes a locale change in the BCD (Boot Configuration Database), which Bitlocker with TPM interprets as a boot attack.

Resolution:

o   Suspend BitLocker drive encryption “manage-bde –protectors –disable c:

o   Add language packs to the system and make any language settings.

o   Resume Bitlocker drive encryption “manage-bde –protectors –enable c:

Scenario # 5:      When you create or modify any of the partitions that reside on the O/S drive.

Resolution:

o   Suspend BitLocker drive encryption “manage-bde –protectors –disable c:

o   Shrink, expand, or create any partitions on the drive.

o   Resume BitLocker drive encryption “manage-bde –protectors –enable c:

What are Regular Expressions?

email me

Regular Expressions is a sequence of characters that forms a pattern, which is mainly used for search and replace (in coding, in some applications, and even in databases). The purpose of creating a pattern is to match specific strings, so that the developer can extract characters based on conditions and replace certain characters.

example at link

 

Recommended Book

 

RegExp Object

RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily. It is similar to RegExp in JavaScript

Properties :

  • Pattern – The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object.
  • IgnoreCase – A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicity, IgnoreCase value is set to False.
  • Global – A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False.

Methods :

  • Test (search-string) – The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned.
  • Replace (search-string, replace-string) – The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned.
  • Execute (search-string) – The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn’t modify the original string.

Matches Collection Object

The Matches collection object is returned as a result of the Execute method. This collection object can contain zero or more Match objects and the properties of this object are read-only.

  • Count – The Count method represents the number of match objects in the collection.
  • Item – The Item method enables the match objects to be accessed from matches collections object.

Match Object

The Match object is contained within the matches collection object. These objects represent the successful match after the search for a string.

  • FirstIndex – It represents the position within the original string where the match occurred. This index are zero-based which means that the first position in a string is 0.
  • Length – A value that represents the total length of the matched string.
  • Value – A value that represents the matched value or text. It is also the default value when accessing the Match object.

All about Pattern Parameter:

The pattern building is similar to PERL. Pattern building is the most important thing while working with Regular Expressions. In this section, we will deal with how to create a pattern based on various factors.

Position Matching :

The significance of position matching is to ensure that we place the regular expressions at the correct places.

Symbol Description
^ Matches only the beginning of a string.
$ Match only the end of a string.
\b Matches any word boundary
\B Matches any non-word boundary

Literals Matching :

Any form of characters such as alphabet, number or special character or even decimal, hexadecimal can be treated as a Literal. Since few of the characters have already got a special meaning within the context of Regular Expression, we need to escape them using escape sequences.

Symbol Description
Alphanumeric Matches alphabetical and numerical characters only.
\n Matches a new line.
\[ Matches [ literal only
\] Matches ] literal only
\( Matches ( literal only
\) Matches ) literal only
\t Matches horizontal tab
\v Matches vertical tab
\| Matches | literal only
\{ Matches { literal only
\} Matches } literal only
\\ Matches \ literal only
\? Matches ? literal only
\* Matches * literal only
\+ Matches + literal only
\. Matches . literal only
\b Matches any word boundary
\B Matches any non-word boundary
\f Matches a form feed
\r Matches carriage return
\xxx Matches the ASCII character of an octal number xxx.
\xdd Matches the ASCII character of an hexadecimal number dd.
\uxxxx Matches the ASCII character of an UNICODE literal xxxx.

Character Classes Matching :

The character classes are the Pattern formed by customized grouping and enclosed within [ ] braces. If we are expecting a character class that should not be in the list, then we should ignore that particular character class using the negative symobol, which is a cap ^.

Symbol Description
[xyz] Match any of the character class enclosed within the character set.
[^xyz] Matches any of the character class that are NOT enclosed within the character set.
. Matches any character class except \n
\w Match any word character class. Equivalent to [a-zA-Z_0-9]
\W Match any non-word character class. Equivalent to [^a-zA-Z_0-9]
\d Match any digit class. Equivalent to [0-9].
\D Match any non-digit character class. Equivalent to [^0-9].
\s Match any space character class. Equivalent to [ \t\r\n\v\f]
\S Match any space character class. Equivalent to [^\t\r\n\v\f]

Repetition Matching :

Repetition matching allows multiple searches within the regular expression. It also specifies the number of times an element is repeated in a Regular Expression.

Symbol Description
* Matches zero or more occurrences of the given regular Expression. Equivalent to {0,}.
+ Matches one or more occurrences of the given regular Expression. Equivalent to {1,}.
? Matches zero or one occurrences of the given regular Expression. Equivalent to {0,1}.
{x} Matches exactly x number of occurrences of the given regular expression.
{x,} Match atleast x or more occurrences of the given regular expression.
{x,y} Matches x to y number of occurences of the given regular expression.

Alternation & Grouping :

Alternation and grouping helps developers to create more complex Regular Expressions in particularly handling intricate clauses within a Regular Expression which gives a great flexibility and control.

Symbol Description
0 Grouping a clause to create a clause. “(xy)?(z)” matches “xyz” or “z”.
| Alternation combines one regular expression clause and then matches any of the individual clauses. “(ij)|(23)|(pq)” matches “ij” or “23” or “pq”.

Building Regular Expressions

Below are few examples, which clearly explain on how to build a Regular Expression.

Regular Expression Description
“^\s*..” and “..\s*$” Represents that there can be any number of leading and trailing space characters in a single line.
“((\$\s?)|(#\s?))?” Represents an optional $ or # sign followed by an optional space.
“((\d+(\.(\d\d)?)?))” Represents that at least one digit is present followed by an optional decimals and two digits after decimals.

Email Address Validation

email me

This is a VBScript I wrote to determine the validity of an email address. Simple AI is about pattern recognition, and if you notice in the code below, a particular pattern is exactly what we’re looking for.

further reading link

The script

DIM strEmailAddress, objPatternMatch

strEmailAddress = "mrnettek@yahoo.com"

Set objPatternMatch = New RegExp

With objPatternMatch
.Pattern = "^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,4}$"
.IgnoreCase = False
.Global = False
End With
' The Test method objPatternMatch TRUE if a match is found or FALSE if a match is NOT found
If objPatternMatch.Test( strEmailAddress ) Then
msgbox strEmailAddress & " is a valid e-mail address"
Else
msgbox strEmailAddress & " is NOT a valid e-mail address"
End If

Set objPatternMatch = Nothing
Set strEmailAddress = Nothing

WScript.Quit(0)