PowerShell: Zip up files using .NET and Add-Type

Posted by Kris Powell

Oct 16, 2014 10:00:00 AM

I recently came across a need to zip up some files prior to copying them over the network. Normally, I’d simply use kris_resizedanother tool such as WinZip or 7zip, but I thought I’d like to see how PowerShell could handle it.

There are many tools out there to help you with this (7zip cli, PowerShell community extensions, etc). They’re not included with Powershell, so I decided to try and make use of the tools we have at hand.

I decided to go with a quick way to zip up files by leveraging .NET and using the cmdlet Add-Type

Zipping files with PowerShell

Note: This requires .NET 4.5 and Powershell 3+

This example script is pretty straightforward and simple.  It makes use of the System.IO.Compression.Zipfile class that was included with .NET 4.5.  We make use of the PowerShell cmdlet Add-Type to add a Microsoft .NET Framework type to the PowerShell session.  This allows to leverage .NET in our PowerShell scripts.

#############################################################################
#
# -SourceFolder    = The folder with the files you intend to zip
# -DestinationFile = The zip file that you intend to create
# -Compression     = The type of compression you'd like to use:
#                         Optimal (default option)
#                         Fastest
#                         NoCompression
# -IncludeParentDir = Setting this option will include the parent directory
#
#############################################################################

$SourceFolder    = "C:\temp\Zip This Folder"
$DestinationFile = "C:\temp\NewZip.zip"
$Compression     = "Optimal"  # Optimal, Fastest, NoCompression

Zip-Directory -DestinationFileName $DestinationFile `
    -SourceDirectory $SourceFolder `
    -CompressionLevel $Compression ` #Optional parameter
    -IncludeParentDir #Optional parameter

function Zip-Directory {
    Param(
      [Parameter(Mandatory=$True)][string]$DestinationFileName,
      [Parameter(Mandatory=$True)][string]$SourceDirectory,
      [Parameter(Mandatory=$False)][string]$CompressionLevel = "Optimal",
      [Parameter(Mandatory=$False)][switch]$IncludeParentDir
    )
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $CompressionLevel    = [System.IO.Compression.CompressionLevel]::$CompressionLevel  
    [System.IO.Compression.ZipFile]::CreateFromDirectory($SourceDirectory, $DestinationFileName, $CompressionLevel, $IncludeParentDir)
}

#############################################################################
 
Read More

Topics: powershell

Which Java 7 (or 8) Version Should I Deploy?

Posted by Shane Corellian

Oct 15, 2014 4:57:00 PM

Ha! Oracle released three new Java updates on October 14th. The obvious question is: Which Java update should I apply?

Java 7 Update 71

Java 7 Update 72

Java 8 Update 25

The answer, as usual, depends on the needs of your organization. If you have been using Java 7 then it's safe to continue using that Java family for now. I would, however, recommend that you deploy Java 8 to a few "test" computers so that you can prepare for the inevitable move to Java 8. It's important to note that Java 7 reaches its EOL (End of Life) in April, 2015.

If you're sticking with Java 7 then Oracle recommends that you deploy Update 71. From Oracle: "[Update 71] is the intended upgrade for most users." This update contains only security fixes. 

As far as Update 72 Oracle has this to say:"[Update 72] is available for developers and users requiring additional non-security improvements or for testing updated features.  You should use 7u72 if you are facing any of the specific issues as noted in its release notes, and also as part of your quality assurance cycles. These improvements and features are planned to appear as part of the next scheduled CPU in January 2015."

The PDQ Deploy Package Library has added Update 71 for Java 7 and Update 25 for Java 8. If you have Auto Deployments configured for Java then these are the versions that will (by default) be deployed.

blog-javau71-autodeployment

If there is a sufficient demand then we will certainly add Update 72 to the Package Library although it would be a separate package altogether, which means that PDQ Deploy users who have Auto Deployments configured for Java 7 wouldn't have Update 72 applied as a natural upgrade to earlier Java 7 versions.

If you use the Collection Library in PDQ Inventory then you may notice that computers running Update 71 or Update 72 will be placed in the Java 7 (Latest) collections. (See image below.)

blog-java7u71-collections

If you do need to use Java in your organization it is definitely worth the effort to test Java 8. Find out which (if any) of your Java applications or websites don't work with it. It's important to note that Oracle has now made Java 8 the default Java download on their site. If you use Java 8 then it is recommended to deploy Update 25.

Use PDQ Deploy to silently install Java in your environment, it's what we're here for after all!

Read More

Topics: java

PowerShell: Sending Email (with Gmail example)

Posted by Kris Powell

Oct 9, 2014 10:55:44 AM

It’s late on a Friday night. Like most people, you have somewhere else you would rather be. Instead, you are stuck atkris_resized work because you completely forgot about some scheduled maintenance that has to be done that night.

You’re familiar enough with PowerShell to make some scripts to take care of the maintenance, but you’re worried about the off-chance that one of the scripts fails or you’re worried that something could go wrong.

Wouldn’t it be great if you could start your scripts and configure them to email you the results? You could still get out, enjoy your Friday night and rest assured that you’re scripts are doing their job without you losing yours!

(Disclaimer: We do not condone the shirking of any responsibilities that you may have...especially on Friday nights.)

Sending Email with PowerShell

There are a multiple ways to send an email with PowerShell. This is a native cmdlet option that is simple and easy to use. It uses the cmdlet Send-MailMessage.

Send-MailMessage <parameters>

List of available parameters

-Attachments string
    The full path and filenames to be attached to the email.

-Bcc string
    Email addresses that you would like to bcc.

-Body string
   The body of the email message.

-BodyAsHtml
   Indicates that the value of the Body parameter contains HTML.

-Cc string
   Email addresses that you would like to cc.

-Credential PSCredential
   An account that has permission to send the email. The default is the current user.

-DeliveryNotificationOption Option
   Delivery notifications will be sent to the email address specified in the -From parameter.

          None - No notification (default)
          OnSuccess - Notify if the delivery is successful.
          OnFailure - Notify if the delivery is unsuccessful.
          Delay - Notify if the delivery is delayed.
          Never - Never notify.

-Encoding Encoding
   The encoding used for the body and subject. 

-From string
   
The address from which the mail is sent.

-Priority Priority
   
The priority of the email message. Valid values: Low, Normal (default), High

-SmtpServer string
   The name of the SMTP server that sends the email message.

-Subject string
 
  The subject of the email message.

-To string
   
The addresses you wish to send email to. 

-UseSsl
    
Use the Secure Sockets Layer (SSL) protocol to establish a connection to the SMTP server to send email. SSL is not used by default.

Examples of Usage:

Example 1 - Sending a simple email

Send-MailMessage -From “email@yourdomain.com” -To “AnotherEmail@yourdomain.com” -Credentials (Get-Credential) -SmtpServer “smtp.yourdomain.com”

Example 2 - Sending an email from Gmail

Here’s a full example of sending an email via Gmail’s SMTP servers.  It will prompt you for a username and password thanks to (Get-Credential).  The username needs to be <your full gmail address> and password needs to be <your gmail password>, though you could always pipe in a PSCredential and get the same effect.

 

##############################################################################
$From = "YourEmail@gmail.com"
$To = "AnotherEmail@YourDomain.com"
$Cc = "YourBoss@YourDomain.com"
$Attachment = "C:\temp\Some random file.txt"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"

Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (Get-Credential) -Attachments $Attachment

##############################################################################

 Best of luck to you in your emailing endeavors!

Read More

Topics: powershell

How to Disable Java Automatic Updates

Posted by Annalisa Williams

Oct 8, 2014 10:36:00 AM

o you're just the kind of control freak that wants control over when and how Java gets updated. It's okay, you're in good company here. We all know who is really in charge of keeping the world (er, the company...we meant company) from falling into shambles (read: sys admins). 

So here's how to disable Java automatic updates.

Finding Where Java Automatic Updates are Enabled

First step is to find the registry key that enables Java's auto updates. Using PDQ Inventory, you can setup a scanner to locate the key. In PDQ Inventory go to File>Preferences>Scan Profiles. Click Add to create a new scan profile, in the pop up click Add>Registry. Here you will specify the path the key resides which will be HKEY_LOCAL_MACHINE hive, with the path SOFTWARE\JavaSoft\Java Update\Policy (the video below provides shows more in depth explanation on finding the path.) 

 

 

You can duplicate that scan that you just created by right clicking and selecting duplicate. Change the path to SOFTWARE\Wow6432Node\JavaSoft\Java Update\Policy to pick up the 32-bit Java installations that are running on 64-bit machines. 

Building a Collection 

Next, you'll want to build a collection of computers you need to make the change from enabled to disabled. 

Go to File>New Dynamic Collection (or Ctrl+N) and build a collection like the following: 

Collection_Java_Auto_Update

 

The below video demonstrates and discusses this dynamic collection and how to also build a report from the data: 

 

 

Silently Changing the Auto Update Policy 

Now that you've targeted which computers have auto updates enabled, it's time to disable all of them. In PDQ Deploy, create a new deployment package (File>New Package). You'll need to create two command steps, one for 32-bit and one for 64-bit machines. (Make sure that you change the architecture respectively under the "Conditions" tab for each step.)

Your command for the 32-bit will be:

%SystemRoot%\System32\Reg.exe DELETE "HKLM\SOFTWARE\JavaSoft\Java Update" /f

Your command for the 64-bit will be:

%SystemRoot%\System32\Reg.exe DELETE "HKLM\SOFTWARE\Wow6432Node\JavaSoft\Java Update" /f

Now you're ready to deploy these commands to the computers you've selected in the collection you've made earlier. Hit Deploy>Deploy Once and under the Choose Targets button select PDQ Inventory. You should see your collection name in the list and can add all or as many of the computers you want to send the deployment out to.

You're all set! The video below shows these steps in detail and how you can verify the key has been removed. 

 

See all the videos in this playlist.

 

 

Read More

Topics: java

Powershell: Get CPU Usage for a Process Using Get-Counter

Posted by Kris Powell

Oct 2, 2014 11:08:00 AM

I was on Stack Overflow not too long ago when I came across a post involving gathering CPU usage bykris_resized percentage that I simply couldn’t pass up. I had to see how PowerShell would handle it.  

I wasn’t disappointed.

After a few revisions, here is a neat way to get the CPU usage of a particular process and have it displayed by CPU percentage.

Be sure to choose between option A or option B. I currently have option B commented out.

#############################################################################
# Option A: This is if you just have the name of the process; partial name OK
$ProcessName = "cpu"

# Option B: This is for if you just have the PID; it will get the name for you
#$ProcessPID = "6860"

#$ProcessName = (Get-Process -Id $ProcessPID).Name
$CpuCores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors
$Samples = (Get-Counter "\Process($Processname*)\% Processor Time").CounterSamples
$Samples | Select `
InstanceName,
@{Name="CPU %";Expression={[Decimal]::Round(($_.CookedValue / $CpuCores), 2)}}
#############################################################################

This makes use of the Get-Counter cmdlet that allows you to get performance counter data for local/remote machines. Let's find out more! The following command will get you a lot of information about all the counter sets that are available to use.

Get-Counter -ListSet *

It's a lot of information. Too much for me, in fact, which is why I usually use the following command. It will get you a list of all the sets of counters that are available to be used:

Get-Counter -ListSet * | Sort-Object CounterSetName | Format-Table CounterSetName

In that list, I see an object called Processor that I'd like to know more information about and which counters are available. I would find out more information like this:

Get-Counter -ListSet Processor

That gets a lot of information. I'd like to see the counters themselves as I would use them with Get-Counter:

(Get-Counter -ListSet Processor).Counter

Now we should have a list that includes "\Processor(*)\% Processor Time" This is what I used to find out the percentage of CPU time for the process. The asterisk (*) in this case is a wildcard grabbing all processes. In the script above, we populate that with the process name that we'd like the know the CPU percentage for.

We also make use of the Get-WMIObject cmdlet to get the total logical processors for the system. This cmdlet is one of the most useful in Powershell and we will likely post many blogs that include Get-WMIObject. Due to how much information can be gleaned from a system by using this cmdlet, we will not go into too much detail at this point in time.

Read More

Topics: powershell

How To Install Firefox Silently

Posted by Annalisa Williams

Oct 1, 2014 12:18:39 PM

There a couple ways to silently install Firefox. First, you'll want to get your free download of PDQ Deploy and do the initial set up. There is a more in-depth explanation on how to build your own deployment packages here. 

To create the package you will go to File>New Package. Name your Firefox package. In the Install step click the ellipsis button in the Install File and navigate to the Firefox Setup xx.exe file. 

At this point you have two options to do a silently install Firefox. In the parameters field you can type

-ms

or use an INI file. Copy and paste the following into a text file and save as a .INI in the same directory as your Firefox setup exe. 

[Install]
InstallDirectoryName=Mozilla Firefox
CloseAppNoPrompt=true
QuickLaunchShortcut=true
DesktopShortcut=true
StartMenuShortcuts=true

Then in the parameters field enter:

/INI=<full path to the INI>\Firefox.ini

In the Additional Files field add the Firefox.ini file.  (You could also just check the Include Entire Directory checkbox but if you do this you want to make sure there aren't unnecessary files in the directory such as earlier Firefox Setup executables)

firefox

Now you're all set to deploy your silent install. Now, the easier way to do this of course is to deploy it from the package in the Package Library that silently installs Mozilla Firefox that is available with either a PDQ Deploy Pro mode or Enterprise mode license. Easier yet, with Enterprise mode you can set up Firefox to automatically deploy whenever a new version is released. 

Note: Do not use /S (a common silent install parameter) because /S for Firefox performs a silent uninstall

Read More

Topics: install silently

Attaching Multiple Packages to an Auto Deployment Schedule

Posted by Annalisa Williams

Sep 29, 2014 12:24:00 PM

One nifty thing about setting up Auto Deployments is you can attach multiple packages from the Package 150pxAutoDLibrary to a single Auto Deployment schedule. The video below is a tutorial on how attaching and detaching packages to a single schedule works. 

While in the Package Library click the checkboxes next to the applications you would like grouped in the same schedule. Once you have those selected you can go ahead and click the "Add Auto Deployment" button in the upper right corner of your screen. This will bring up a window that will allow you to set the frequency at which your schedule runs and what workstations you want to this schedule to deploy to.

Attaching and Detaching Packages

After you have made your schedule you may want to make changes to your Auto Deployment Schedule.

Making changes to an already existing auto deployment schedule is easy, you can easily add or remove packages by opening up the schedule (All Schedules, then double-click the schedule you wish to modify and click the packages tab) from here you have two buttons in the upper right corner, Detach from Selected or Attach to Package. Remove packages by selecting them and clicking Detach from Selected. Add new packages by clicking attach to package. You can come back to this window at anytime and make changes. 

multiple_package_auto_deployment

When attaching new packages, be sure to select the packages from the package library and NOT the packages folder. If you select from the packages folder (imported packages) you will not get the latest versions of applications as the come out, it will only deploy that version of the application.

In an earlier blog we also explained how approval periods work and how to change your approval policy for individual packages as well as your default approval policy for all auto deployment schedules. A video tutorial on that is available in that blog post. Below is a tutorial showing how to attach and detach packages from an auto deployment schedule. 

Read More

Topics: Auto Deployments

PowerShell: Console Window Tips

Posted by Kris Powell

Sep 25, 2014 11:30:00 AM

kris_resized

If you use PowerShell on a regular or semi-regular basis you may already know these tricks of the trade, but in case you were not aware here are some neat tricks to use in the PowerShell console window.

Tab Completion

Go ahead and type a partial command and press your Tab key. PowerShell magically knows what you’re trying to look for, or at least it will venture an educated guess.

Get-Da<Tab> should autocomplete to Get-Date.

Get-Date - Animated.gif

You can even press Tab (and Shift-Tab) multiple times to cycle through multiple matches.

Get- should autocomplete to multiple commands. Just keep pressing Tab to cycle forwards alphabetically and press Shift-Tab to cycle backwards alphabetically.

Get- - Expansion - Animated.gif

This is great for typing commands more quickly or for trying to type commands that you may not fully remember.

Show Recent Command List

You can show all recently typed commands at a console window by tapping the F7 key. You can then select a command by highlighting it and hitting the Enter key.

F7 - Animated.gif

Scroll Through Recent Commands

You type a command and realize you have a syntax error. Rather than type the command all over again, you can simply tap the Up arrow key to scroll backwards through your recent commands. You can tap the Down arrow key to scroll forwards.

Pause Results On Screen

Have you ever run a command that output more results than fit the screen? Usually, the results will zoom past faster than most of us can read, so we often find ourselves having to scroll to view the results.

No more!

There are two common methods for accomplishing this:

<command> | Out-Host -Paging

<command> | more

Something to note, however, is that it will evaluate the results of a command before outputting them to the console window.

I know that there are many other tips that each of us have come across (aliases, for example). Please feel free to add any suggestions to the comments below so that other readers may be able to benefit from your experience!
Read More

Topics: powershell

Auto Deployment Deep Dive: Approval Periods

Posted by Annalisa Williams

Sep 24, 2014 11:46:00 AM

AutoDeployment400px_(1)

It's here. Auto Deployment. This is the feature that will allow you to get the next level of lazy as a sys admin, making you the world's greatest sys admin. Set it and forget it and let PDQ Deploy worry about getting the latest Flash, Java or any number of packages in the Package Library deployed. (See video below.) 

Approval Policy

Hopefully you don't need to be told twice, but you should be doing test deployments before unleashing a new version to all your company's workstations to make sure these new versions don't bring a mini-Armageddon upon your network. This why when setting up an auto deployment schedule, you have a default seven day "approval period". What this does is hold off on attaching the new version to the auto deployment schedule giving you an opportunity to test out the deployment first before it goes out. 

You can adjust the approval policy default for all packages or change the approval policy on individual applications. To change the default by going into File>Preferences>Package Library. After changing this, future auto deployments set will be assigned this approval period. However, if you have a lot of faith in Oracle and want to get latest Java 7 out right way you can change the approval policy for that particular package in your auto deployment schedule. 

Adjusting Approval Policy for Specific Packages

Under the Auto Deployment Packages section (located in the left side panel) select the auto deployment schedule you wish to modify, then in the main window select the package you want changed. Over in the right panel under the Auto Deployment field click the link to change and a window will pop up and you can set the approval period to immediately approve. Once set to immediately approve, this package (when a new version comes out) will automatically deploy upon the next time the schedule is run.

Changing the approval policy in this way will ONLY impact that particular package and not any other packages that are in this same auto deployment schedule. Also a package set to immediately approve does not mean that the package will necessarily automatically deploy, it will deploy when the schedule is set to run next. You can adjust when the schedule runs by double-clicking the schedule in the main window. In the window that pops up go to the schedule tab and there you can make those changes. 

This video tutorial shows step-by-step how to set up an Auto Deployment schedule and adjust the approval period. 

Auto Deployments are a PDQ Deploy Enterprise mode feature. Current customers can upgrade or make sure their Enterprise license is up-to-date at the customer portal. 

 

Read More

Topics: Auto Deployments

Powershell: Get-Help

Posted by Kris Powell

Sep 18, 2014 1:48:00 PM

kris_resizedFrom the results of my last Powershell blog post (Get-Command and Get-Member), we should have a list of commands (cmdlets, aliases, etc).

But, how do we know what each cmdlet does?  Or, what if we know how a command works but want to see some examples?

We need some more information about how to use those commands in more detail.  Let’s learn more about the Get-Member cmdlet that we introduced last time by utilizing the tools built into Powershell.

Get-Help

Get-Help displays detailed information about how to use a command and any examples that may exist.

The basic syntax is pretty simple and straightforward.

Get-Help <cmdlet>

In order to find out more about the Get-Member cmdlet, we type:

Get-Help Get-Member

This will give us some basic syntax and usage information about Get-Member as well as a brief description.  Let’s introduce some of the parameters that give us even more information about the cmdlet that you’d like to know more about.

Get-Help <cmdlet> -Examples

This will show usage examples for the cmdlet

Get-Help <cmdlet> -Detailed

This will show more detailed information than the basic syntax

Get-Help <cmdlet> -Full

This shows the entire help file relating to the cmdlet, including details/examples.

Get-Help <cmdlet> -ShowWindow

This will show the full help file for a cmdlet in a new window.  It includes a search box and a settings button to help you configure which information you want displayed.

Get-Help <cmdlet> -Online

This will pull up the online help files for the cmdlet.


Note: If you find that you’re help files seem to be lacking, it’s possible that they’re not fully installed or up-to-date.  In that case, run Powershell as an Administrator and type the cmdlet, Update-Help and it will update all the associated help files.)

Read More

Topics: powershell

Admin Arsenal Blog

Subscribe to Email Updates