Scripted Home Folder Management with PowerShell Pt. 1

2017-07-27T00:01:07+00:00 August 29th, 2012|Uncategorized|

I’ve been doing tons of scripting for the project on which I’m working lately.  And I thought it’d be cool to spend a few posts in a row covering a few base elements of PowerShell-based user and Home Folder management, and build up toward a script for user and folder creation/deletion that you can easily use. 

I don’t intend to get fancy with this; in fact, I intend to make is simple as possible, and maybe kick around a few alternative methods to do the same tasks.  My goal is not to teach PowerShell, but to show you you can script these things easily.

So join me on the journey!  But let’s get there in small steps.  We’ll start at the start, with user creation.  Open a PowerShell session, and let’s get to it…

In order for this article series to work, I have to make some assumptions: I’ll assume you have the proper rights, a test environment, the proper PowerShell modules, and a Windows 7 or Server 2008 R2 computer.

For this first method in Part 1, we are going to show you how to do it with just native Powershell, using the ADSI provider, without any additional Powershell modules.  It’s like learning how to do the work on paper before you use a calculator…  😉

First, set up a variable that opens an LDAP connection to the server, using the ADSI provider (note, “LDAP” is case-sensitive) and specifying the OU where we’ll be creating our new User object:

$MyConnection = 
[ADSI]"LDAP://ou=Demo,dc=CoretekServices,dc=local"

Next, set up a variable that defines what you’re creating, along with a few critical attributes:

$MyObject = $MyConnection.create("User","cn=Jeremy Pavlov") 
$MyObject.Put("givenName","Jeremy")
$MyObject.Put("surname","Pavlov")
$MyObject.Put("samAccountName","JPavlov")

Finally, the command to make it happen:

$MyObject.SetInfo()

…and with that, the user is created in a “disabled” state.  So let’s fix that and set a password, using the same object and connection calls:

$MyObject.PsBase.Invoke("SetPassword","ChangeMe123!")
$MyObject.PsBase.InvokeSet("AccountDisabled","$false")
$MyObject.SetInfo()

But, as you may or may not expect, the act of setting the password in the previous step also clears the requirement for the user to change the password at first login… but we definitely want the user to do that.  So let’s set it back with one final step:

$MyObject.pwdLastSet = 0
$MyObject.SetInfo()

Okay, okay, I know what you’re saying, “…Man, that’s alot of work…”  And I’ll admit,this is the hard way.  So I’ll show you some easier ways in the next post.

(Updated 20120903; fixed syntax typos, split some content to next week’s post)

Next time…  A couple easier creation options…  See you then!

 

 

How to script “Ownership” of NTFS File Systems…

2017-07-27T00:01:07+00:00 July 25th, 2012|Uncategorized|

There’s a time in every IT professional’s life where he or she will need to “Take Ownership” of files and folders that reside on an NTFS File Server (or in larger cases with hundreds or thousands of servers) in a Windows Server 2008 R2 or Windows 7 environment.  I’m sure most IT professionals already know how to do this in the Windows Explorer GUI … but what if your task at hand required that you script this process to run during a limited window of time given during a server migration, and you had to minimize the amount of “clicks” as well as the amount of time spent on multiple servers?  

I was recently assigned to a project very similar to the scenario described above; and after a little research, I stumbled upon a little-known Microsoft tool called ‘takeown.exe’ that has been shipping with Microsoft Server products since Windows Server 2003.  Within minutes of discovering ‘takeown.exe’ I had a script written and I was running it in my test environment with positive results.  This shows how simple the tool really is!

Below is the usage example as seen from the command line ‘takeown.exe /?’:

TAKEOWN 
[/S system [/U username [/P
[password]]]] /F filename [/A] [/R [/D prompt]]

Below is my personally recommended example: 

TAKEOWN.exe /F C:MyFolder /R /A

 

As expressed above, my suggestions are to use the /F (to specify the folder to apply ownership on), the /R switch (as in “recursive” which mean to apply to all child objects, sub-folders and files) and the /A switch (which gives ownership to the “Administrators” group instead of the currently logged in user).  And while I didn’t use the /D switch in the above example, it may be necessary to use the “/D Y” to avoid being prompted in cases where the user ID running the command does not have rights to list the folders.   

You can also reference additional parameters by typing in ‘takeown.exe /?’ from the command prompt on any Windows Server 2008 R2 server or Windows 7 machine.

 

Send an Email from the Windows Commmand Prompt or Script…

2017-07-27T00:01:07+00:00 July 18th, 2012|Uncategorized|

Today, Avi and I were discussing one of the requirements of an application he’s working on;  it seemed simple enough at first blush…

He needed to send an email from a Windows 7 computer — which is fairly straightforward if you happen to have something like BLAT installed, or if you’re able to script a call to a nearby SMTP gateway.  However, there was one major requirement this time:  it had to appear to come from the *user* of the application, with the user’s intent/blessing/permission. 

Yes, Avi could have configured the application to make a direct call to the local email client executable — if there were guaranteed to be one (not necessarily the case), and if the version/type were to be predictable (it might be Outlook, it might be GroupWise, etc.) to properly call with the correct options and flags.  Avi did some digging and soon found a way to get a fully formatted message to launch in Outlook, but we had to modify it a tad to get it to work in both GroupWise and Outlook (and perhaps others).  Here’s what we settled on, and how it works…

Aside: I’ll have to assume that your GroupWise or Outlook is properly installed and configured for these things to work.

Let’s start with the basics (pun intended); this should launch your email client and pre-populate the recipient (interestingly, it should work no matter whether your email client is configured or not):

start mailto:sales@CoretekServices.com

…but you knew that, and you’re clearly not impressed.  Now perhaps the trickiest part: after the recipient in the command — and before the next component (I use Subject in this example) — it is best to use a question (?) mark here for Outlook *and* GroupWise compatibility, although a caret+ampersand (^&) will work if using Outlook only (note that the “%20” is a space character):

start mailto:sales@CoretekServices.com?Subject=Your%20Subject...

…and now you’re intrigued.  Let’s build on that.  Next, we tack on another option in the command (I show the CC option here), separated with a caret+ampersand (^&) :

start mailto:sales@CoretekServices.com?Subject=Your%20Subject...^&CC=questions@YourLinuxGuy.com

…and now I’ve won you over.  Cool!  Let’s complete the line — separated by more caret+ampersand (^&) characters, of course — and make it a fully populated email, ready-to-send:

start mailto:sales@CoretekServices.com?Subject=Your%20Subject...^&CC=careers@CoretekServices.com^&BCC=secret@CoretekServices.com^&Body=This%20is%20the%20message,%20which%20I%20agree%20to%20send%20by%20clicking%20SEND.

Now click send, and enjoy!

 

 

Windows 7 and Server 2008 DOS Batch File Date Tip….

2017-07-27T00:01:07+00:00 May 30th, 2012|Uncategorized|

No matter what people think, DOS batch scripts are just as alive and needed as ever.  And for all the tasks we create on Windows servers, we still commonly need to gather application output, rotate logs, etc.

So when running a script that exports results to a log/results file, I always prefer to date my file names for easy tracking and history.  My preferred date arrangement for filenames is the date in reverse format: YYYYMMDD, or 20120531.  And since the DOS date command isn’t as friendly or flexible as the Linux/Unix date command (with which you may easily format the output in myriad ways), it’s best to do the next-best thing: use the date *variable*.

Most folks don’t even know that your Windows system is keeping a real-time variable for the date, but it certainly makes sense that it would be necessary.  Go ahead, pull up a command prompt and type: echo %date%

…and on Windows 7 and Server 2008 (for XP, please see this post), you’ll get a result like this:  Wed 05/31/2012

 So what we need to do now is to utilize string manipulation, grab the date elements we want, and flip the order around to get the arrangement we need:
set todaysdate=%date:~10,4%%date:~4,2%%date:~7,2%

 The structure above is this:  There are 3 sections, all of which use the date variable.  The first section moves in 10 characters, and grabs 4.  The second moves in 4 characters and grabs 2, and the third moves in 7 and grabs 2.  As a result, we have reverse-date!

Then set a variable to use the combined date variable in the filename.

set exportfile=C:tempexportmyexport-%todaysdate%.txt

…now just call the %exportfile% in your batch file when you redirect your output, and viola!!  Here’s what it looks like when you echo %exportfile%:

C:tempexportmyexport-20120531.txt

Enjoy…

😎

(Updated 20120809 for OS version clarification)

How to run bginfo.exe at startup on Windows Server 2008 R2

2017-07-27T00:01:07+00:00 May 9th, 2012|Uncategorized|

No matter what area of IT you work in, there’s always some important piece of information you frequently need to retrieve from a workstation or server; often, it’s several pieces of information.  A lot of time can be spent searching a system to obtain that info. Fortunately, there’s a tool that’s been around for years that can display system info right on the desktop: bginfo (http://technet.microsoft.com/en-us/sysinternals/bb897557).

 

Bginfo is often a necessity in a lab environment, but it can be used anywhere.  Some of the most popular information to display is:

  • OS version
  • SP version
  • IP address
  • Boot time
  • Disk “Free Space”

…but there’s a whole lot more.  In fact, you can configure bginfo to display just about any attribute of the system.  (NOTE: A detailed explanation about how to display custom info using bginfo is beyond the scope of this article; but if you would like to learn more, check out Shay Levy’s article here: http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2008/07/22/bginfo-custom-information.aspx).

It’s nice to run bginfo at startup silently and unattended.  This can be challenging, though, particularly on Windows Server 2008 R2.  To do so, you need to edit the following registry key:

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionRun

**Credit to James from redkitten.co.uk for documenting this here: http://www.redkitten.co.uk/windows-server/using-bginfo-on-windows-server-2008/

Create a new REG_SZ value under the “Run” key named “bginfo”, or whatever you want.  The value of the key will be the path to bginfo.exe, and any parameters you want to pass.  Personally, I’ve had the best luck passing /silent /accepteula /timer:0 to run bginfo silently at startup.  The help file indicates /NOLICPROMPT is also a parameter to bypass the Sysinternals accept EULA dialog, but /accepteula always works for me.

Something else to be aware of — especially if you intend to run bginfo in an enterprise with UAC turned on and GPOs applied — is to keep the output bitmap file in a location that the logged on user has write permissions.  The reason for this is that bginfo runs in the user context to display on the user’s desktop; and because the information is “dynamic” — at least at each user logon — the output bitmap file needs to be updated.  You can change where bginfo stores the .bmp under the Bitmap -> Location… menu.  The default location is in the user’s TEMP directory, which should be okay.

 Bginfo is a fun, easy and very useful way to customize your desktop, and I hope this helps you (and other users) be more productive!

 

Active Setup – Solve Problematic HKCU Keys…

2017-07-27T00:01:07+00:00 March 28th, 2012|Uncategorized|

Hello fellow packagers — ever have an issue with trying to get a program to lay down the HKEY_CURRENT_USER (HKCU) keys?  Well, let’s break down how to fix this issue.  I am going to show you how to set up Active Setup within your applications MSI/MST file in order to have this HKCU stay on the machine, no matter how many users log into the system. 

Active Setup helps to lay down Current User data when an application is deployed or even installed straight from the MSI itself.  Active Setup can be set to do a repair and check for the current user keys that the application needs in order to fully run right.  I am going to show this process, as its one of the most common processes to use with Active Setup.

Windows has keys that it will look for before it kicks off the full install of the MSI.  These keys can be found under:

HKLMSoftwareMicrosoftActive SetupInstalled Components<UID>

…and also under:

HKCUSoftwareMicrosoftActive SetupInstalled Components<UID>

The <UID> should be unique, based off the application you’re using.  Now, the best value to use for the <UID> would be the Globally Unique IDentifier (GUID); I suggest using the Product Code for the GUID.  There are many options you can use for the GUID, but for this example I am going to use the Product Code for the application.  This Code can be found in AdminStudio in a few locations: General Information, Property Manager or Direct Editor->Property table (these locations might be a little different depending on your packaging tool).  Most packaging tools will still have a Property table where you can find the Product Code.  Make sure to write down the GUID you will be using, as we will need this information later on.

So let’s take a deeper look into this process, in order to make these keys no longer an issue.  Let’s begin by opening the MSI we would like to edit.  You can also use a MST transform file if you are working with a vendor MSI.   

Once the application is open you will want to navigate to the Registry section of your MSI/MST.  When you are in the Registry section of your MSI/MST, navigate to:

HKEY_LOCAL_MACHINESOFTWAREMicrosoft

Under the Microsoft folder, right click the folder and select New and make a new Key, in order to make a new folder under Microsoft.  We will label this folder “Active Setup”.

You might be saying “Hey, I don’t have a Software folder under HKLM”…  This is fine, it just means we need to make one.  It’s easy as pie; you would make the parent folders the same way we did with the “Active Setup” Folder.  Just make sure you build the folder structure as indicated above.

We need to set up two more folders the same way we did with our “Active Setup” folder.  This time, however, we will name the first folder “Installed Components”, under the “Active Setup” folder.  Under the new “Installed Components” folder, make another folder and label it “ProductCode”.

Once we have all our folders set up we need to make a “New string Value” under our “ProductCode” folder.  To do this you can right click on the “ProductCode” folder and you will see the option “New string Value” under the drop down list.  We are going to label our “New string Value” as “StubPath” (Windows will run anything under the “StubPath” whenever there is a command under it).  If the current user key is already on the system, msiexec will not run the repair again because the key is already in the location it should be.

When you have your “StubPath” string created, double click it; we need to make some changes to the values in this string.  You will see the Edit Data box come up; in this box we are going to use the following commands in the Value Data field:

Msiexec /fu (ProductCode or GUID) /qn

These are what the switches are doing that you are adding to the msiexec:

/f – Repair
 
 /u – all required user-specific registry entries
 
 /qn – Silent mode with no UI.

 (For other repair options and switches I have added a link to Microsoft’s “msiexec” page:  http://technet.microsoft.com/en-us/library/cc759262%28v=ws.10%29.aspx)

This new key will run once the application is launched.  Make sure to test your application out, and check those keys you have made.  The best way to check the MSI/MST is to launch the MSI/MST though the command line. 

I hope this helps to clear up and issues with Current User key, and gives you a better understanding on how to fix the issue.

 

Windows Installer Verbose Log Analyzer…

2017-07-27T00:01:08+00:00 March 7th, 2012|Uncategorized|

All software packagers know that an installation log file is critical for understanding and analyzing the behavior of an installation package, particularly with Windows Installer .MSI packages.  Many, however, are not aware of a very helpful utility that can be used to help read log files.

Microsoft provides a tool called “Windows Installer Verbose Log Analyzer” with the Windows SDK for Windows 7 and .NET Framework Service Pack 1.  The log analyzer, WiLogUtl.exe, provides a graphical interface that allows you to interact with the log and presents critical installation information in an easy to read format.

 

 

The entire SDK is approximately 1.4 GB; but if you only want to install WiLogUtl.exe, as well as a few other handy utilities like Orca, select only Win32 Development Tools on the Install Options install dialog.  By default the log analyzer is installed to C:Program FilesMicrosoft SDKsWindows

[version number]BinWiLogUtl.exe.

One particularly handy feature of WiLogUtl.exe is the ability to view a log file in an HTML format.  This special format presents the installer actions in a color coded layout which allows you to easily distinguish errors from custom actions, standard actions and other information in the log.  The interface includes buttons to quickly navigate through the log.

 

Another very useful feature of the log analyzer is the Property button, which allows you to see all the installer properties and – more importantly – their values, in one window.  Often times unexpected installation behavior can be attributed to incorrect property values.

 

 

The States button provides a view of the installation’s features and components; also very handy.

 

Understanding the root cause of unexpected installation behavior and resolving it can help ensure that your package won’t cause problems in production – and the Windows Installer Verbose Setup Log Analyzer can help save time doing it.

 

 

Finding Rogue KMS Servers in the Enterprise…

2017-07-27T00:01:08+00:00 February 8th, 2012|Uncategorized|

In larger Enterprises with Microsoft-based infrastructure, it’s highly likely that the licensing for the Windows 7 workstations will be based on the Microsoft KMS model.  If you don’t already know, this means you run servers in-house that register themselves into DNS as license providers, and Windows clients will learn of them (and become affiliated with them) to get a license, rather than contacting Microsoft themselves across the Internet.

Unfortunately, one problem that can occur is that someone who has access to the Microsoft license codes (like an I.T. worker, developer, etc.) might accidentally install a KMS license on a server that is not intended to be a KMS server.  And when a KMS license is installed, the server doesn’t know any better; and dutifully registers its KMS capability with the internal Active Directory based DNS as a VLMCS SRV record. 

Recently, I ran into a situation where I needed to hunt down and eliminate some accidentally rogue KMS servers that had cropped up across a large infrastructure, and be able to re-check at regular intervals.  While I originally wrote the script as a bash shell script for Linux, I re-wrote it into PowerShell recently for someone who asked, and I thought I’d post the new version here.

Mind you, this is a stripped-down version of the script, but it includes all that is needed to run the check manually for a hierarchical DNS infrastructure (although you may wish to strip out components if you just want to check the parent domain). 

Copy the contents below, paste them into a PowerShell script file (*.ps1), change the variables at the top… and have fun!

 

# Change the following 3 variables as needed.
# This script will loop through the subdomains, checking for KMS servers in each
# subdomain, and then at the parent domain.
$subs = @("subdomain1", "subdomain2", "etcetera")
$parentdomain = mydomain.local
$outfile = "checkKMS-Results.txt"
write "KMS check report..." | Out-File $outfile
write " " | Out-File $outfile -append
write "The only valid KMS servers are at the $parentdomain, as follows:" | Out-File $outfile -append
write "KMS1, KMS2, KMS3" | Out-File $outfile -append
write " " | Out-File $outfile -append
write "There should not be a KMS server at any of these locations:" | Out-File $outfile -append
foreach ($item in $subs)
{
  write "Checking subdomain: $item"
  $result = nslookup -type=srv _vlmcs._tcp.$item.$parentdomain. |findstr /C:"_vlmcs" /C:"svr hostname"
  if ("X$result" -eq "X")
  {
    write "No registered KMS server in $item" | Out-File $outfile -append
  }
  else
  {
    write "***KMS FOUND at this location: ***" | Out-File $outfile -append
    write $result | Out-File $outfile -append
  }
}
write " "  | Out-File $outfile -append
write "On the contrary, the following should be valid KMS servers:" | Out-File $outfile -append
$result = nslookup -type=srv _vlmcs._tcp.$parentdomain. |findstr /C:"_vlmcs" /C:"svr hostname"
$result | Out-File $outfile -append
write "...Done!" | Out-File $outfile -append

Enjoy!

🙂

 

Basic MSI – Public_Property as Component Install Location

2017-07-27T00:01:08+00:00 February 1st, 2012|Uncategorized|

Sometimes enterprise level packaging can be quite complex, having requirements for variables, sources, destinations, etc., that are all over the map — and all over the network. 

For instance, what if you are working with application bundle files in an MSI that are not intended to be local to the device?  In that case, how does one use a “public property” that contains a path to a network drive as the destination for files to be installed in a basic MSI?

Well, that leads us to this item from Kathy at the Flexera Community Forum:

“If you’re installing the file through a component, you can use a type 35 custom action sequenced after CostFinalize to set the destination folder for the component to the value in the property.”

This translates to using a “Set Directory” custom action.

Steps:

  1. Create a new component.
  2. Under the new component, create a folder under a location that will always exist (such as under the INSTALLDIR/TARGETDIR location).
  3. Add any files needing to be installed to said folder.
  4. Create a public property with the full destination path as its value (where you want the files to end up eventually).
  5. Create a “Set Directory” custom action.
  6. Source of the CA is the directory created in Step 2.
  7. Target of the CA is the public property created in Step 4 (inputted as
    [PUBLIC_PROPERTY]).
  8. Leave the rest of the CA choices as the default options aside from the “Install Execute Sequence”.   Change the setting to “After CostFinalize”. 
  9. Complete the CA with default options.

The public property can be populated through many different means (a VBS, command-line, etc.) making it quite flexible.  The files will install to the location specified in the public property!

 

Application Virtualization – The UAC Panacea?

2017-07-27T00:01:08+00:00 January 18th, 2012|Uncategorized|

…with contributions from Aaron Gierak, Voltaire Toledo, and Jeremy Pavlov.

The User Account Control (UAC) Challenge

It is commonly known that in XP you have to give end users Administrator privileges in order to do even the most simple routine tasks; like changing the system clock, plugging in a USB drive, running a defrag, updating software, or even running security products.  Of course you can use the RunAs command, but that still requires having an Administrator password – which defeats the security purpose of a limited user account.  And just when we thought moving to Windows 7 would eliminate this security privilege nightmare, enter UAC…

User Account Control (UAC) is a technology aimed to improve the security of Microsoft Windows by limiting application software to standard user privileges until an administrator authorizes an increase or elevation.  In this way, only applications trusted by the user may receive administrative privileges, and malware should be kept from compromising the operating system.  In other words, a user account may have Administrator privileges assigned to it, but the applications that the user runs do not inherit those privileges unless they are approved beforehand, or the user explicitly authorizes it.

It is possible to turn off UAC while installing software, and re-enable it at a later time.  However, this is not recommended since File & Registry Virtualization is only active when UAC is turned on – and if UAC is switched off, user settings and configuration files may be installed to an unintended location (i.e. a system directory rather than a user-specific directory).  Also Internet Explorer 7’s “Protected Mode” – whereby the browser runs in a sandbox with lower privileges than the standard user – relies on UAC; and will not function if UAC is disabled.

The Application Virtualization Question

So is application virtualization the solution?  If a virtualized package runs at the kernel level, does it eliminate having to give an XP user Administrator rights?  When you repackage an application that you have been running in XP – in order to port to Win7 – does the app skate by UAC in a way that allows you to keep UAC turned on?

By default, UAC virtualizes requests for protected resources to provide compatibility with applications not developed for UAC.  This is important because many applications written for Windows XP and earlier operating systems assume that the user has administrative privileges and attempt to write to protected resources such as the Program Files or System folders.  The first time an application makes a change to a virtualized resource, Windows copies the folder or registry key to the location within the user’s profile.  Then, the change is made to the user’s copy of that resource.  UAC virtualization is designed to allow already-installed applications to run successfully with standard user privileges, even if they store temporary files or logs in a protected folder.

Installs, Upgrades, and Updates

Many of the problems with UAC come from application installs or upgrades/updates where a new driver or an action that requires UAC acceptance is needed.  With application virtualization – especially a tool like Symantec’s Workspace Streaming where you package from the kernel level – you can bundle the drivers *inside* the virtual app.  As a result, nothing would ever be required of the end-user since nothing is ever “installed”. 

Secondary Executions

However, another issue that bumps against UAC is what we commonly call the “Secondary Execution Event”, where a loaded executable decides to make a call on its own (outside of the one that the app designer intended).  For instance, if a permitted/intended executable launched, and then it calls out to the manufacturer for an updated version, or the latest driver, that is not pre-bundled in the package.  Examples of this are the Juniper VPN agent or the MS Security Center executable.

Panacea or Pariah?

The good news is that application virtualization absolutely does address UAC and elevation features by isolating areas that normally prevent non-elevated users from writing to them by creating a virtual HKLM registry hive, Windows and Program Files.  Virtualizing applications also mitigates potential conflicts in a shared session environment like Remote Desktop Servers or XenApp.

However, is application virtualization the silver bullet to fix all elevation and UAC issues?  The answer is “it depends”.  If the application explicitly requires elevated privileges within its manifest, then it will always present a UAC prompt.  In addition, if the application attempts to make a system change like a driver installation or some kind of self-updating feature, it will force Windows 7 to prompt you for elevation.  These challenges can be further addressed with tools such as AppSense Application Manager, or Viewfinity Privilege Management (which elevate a user’s privilege on a per-executable basis), or SystemGuard (which can elevate privileges to write to the registry).

The bottom line is that application virtualization brings many advantages.  In addition to extending the life of legacy applications, reducing deployment costs, and reducing user downtime caused by install/uninstall issues and application conflicts, many UAC issues can be mitigated with application virtualization, especially when coupled with effective use of user virtualization tools.

 

Next installment – Application Streaming…

 

Load More Posts