Showing posts with label hints. Show all posts
Showing posts with label hints. Show all posts

Friday, 20 August 2021

Google Classroom - How to get a list of all classes/classrooms

You can use the GAM utility to easily export the details of all Google Classrooms in your domain by following the commands below. In this example we'll be exporting the details to a CSV file

(Be sure to update the path to gam.exe and the output CSV file location)

$allclasses = C:\admin\gam\gam.exe print courses > "C:\Admin\Google Classroom\allclasses.csv"

This works well, but if you look at your CSV file you'll notice that firstly, it isn't formatted into columns properly, and secondly, there are a heap of fields called "coursematerial" that aren't required. We can filter out those fields by using the command below

$allclassesfiltered = import-csv "C:\Admin\GoogleClassroom\allclasses.csv" | select-object * -ExcludeProperty "courseMaterial*"

We can then re-export the CSV file with the command below which will actually export it correctly as a CSV file with data separated into columns correctly

$allclassesfiltered | export-csv "C:\Admin\Google Classroom\allclasses-filtered.csv" -NoTypeInformation


Thursday, 19 August 2021

GAM - How To Sync Google Classroom Students from CSV File

GAM is great command line utility that fills a huge void in the management of Google Classroom - since Google haven't bothered after all these years to create any kind of centralised management interface for the product despite a huge uptake in use from COVID-19 and remote learning.

One of the downfalls of GAM is it can be a little slow - if you wanted to add students individually to a class, the command to add each student takes several seconds to execute - which doesn't sound like much, but in a large school with lots of students and lots of classes - it could take hours to complete.

Thankfully, they have included the ability to synchronise members (students) of a class from a CSV file. What they don't mention in their documentation though is how the CSV file should be formatted - kind of important, right?

The CSV file should be formatted as a basic list - with a single column and no column headings - containing the email addresses of the students you wish to add. If you opened it in Notepad - it would look like the screenshot below

Example CSV file format to sync students to Google Classroom with GAM

One thing to note - if you are going to sync from a CSV file, it will add all the students in the CSV file to the classroom, but it will also remove any students already in the classroom who aren't listed in the CSV file, so it's important your CSV file contains all the students in the class.

The command to run the sync is below;

C:\admin\gam\gam.exe course "googlecourseid"  sync students file "C:\admin\GoogleClassroom\class1.csv"

(Be sure to update the path to your gam.exe file, the google course ID and the CSV file location)

Thursday, 27 May 2021

Searching for String within Multiple Files using Powershell

 I recently had a situation where I had to search for a particular string within a large number of files. More specifically, I was looking for what file contained a set of  text used for a menu on a website - the problem is I didn't know which file contained the text, but I knew what I was looking for. The web server had a large number of xml, html and css files, so I quickly put together a powershell script to search these files quickly and was able to find what I was looking for within a matter of minutes! Certainly faster than manually opening files and performing a CTRL + F find within them.

$files = get-childitem -path "C:\inetpub\wwwroot\*.css" -recurse
foreach ($file in $files)
    {
    $filecontent = get-content $($file.fullname)
    $lookup = $filecontent | select-string "What I'm Looking For"
    if ($lookup)
    {write-host "$($file.fullname)"}
    }

The first line searches the folder C:\inetpub\wwwroot for any file ending in .css.  The -recurse switch means it searches all subfolders within C:\inetpub\wwwroot as well. You can of course change the search directory and file type being searched for

$files = get-childitem -path "C:\inetpub\wwwroot\*.css" -recurse

The next section is a ForEach loop that goes through every file that is found within $files (as outlined above). The content of the file is read into the $filecontent variable

$filecontent = get-content $($file.fullname)

Next we perform a search of all the text within the $filecontent variable for a particular string of text. In this example the text we're looking for is "What I'm Looking For" - change this to whatever string of text you are trying to find tin these files. The result of the search is stored in the $lookup variable. If no match is found then $lookup will be null.

$lookup = $filecontent | select-string "What I'm Looking For"

Finally, if a result is found and the $lookup variable is not null, the full name of the file is written to the screen

if ($lookup)
    {write-host "$($file.fullname)"}

This little script saved me a heap of time - as built in windows search functions are pretty unreliable and don't search for content within files. Hope it is able to help you as well.

Wednesday, 19 October 2016

iPhone - Bottom Half of Screen Disappearing

For quite some time I experienced what I thought was a strange issue on my iPhone where the bottom half of the screen would suddenly disappear, or "scroll" down underneath the viewable area of the screen - just like in the picture below;

Original home screen
Home screen after "Reachabiliy" activated
 




















After a little bit of research, I found out that is actually a feature within the iPhone software known as "reachability". The idea being that the top half of the screen scrolls or moves towards the bottom of the screen, to make items that were originally at the top of screen more accessible when using the device with one hand. Pretty clever, right?

Reachability is activated by double tapping (note: not double pressing) the home button. Ie. tap the home button twice rapidly, but don't actually press the button down so it 'clicks'

Press the home button or tap anywhere on the screen to return the screen to normal

Thursday, 13 October 2016

Automatically logoff sessions from windows server using Powershell

Windows server has the functionality through group policy to automatically log off users at a certain time of day, or once their set logon hours expire etc, but in my experience (and many other users based on internet research), it doesn't work very reliably.

Here is a script you  can use that will get a list of all current user sessions on a server, and log them off. A "safelist" is also included where you can specify usernames that should not be logged off automatically by this script - ie. administrator accounts etc. Usernames should be specified in inverted commas and separated by single commas.

I've also incorporated logging functionality, as it may be useful to know what users are staying logged onto the server (perhaps when they shouldn't be), and to be 100% certain about what the script is doing, or has done. Adjust the $logfile variable as required, or ensure the default folder (C:\Admin) exists for it to work correctly.

This does not require any additional modules to be installed either.

The script works by using the query session command, and then manipulating/formatting the results to obtain a list of current user sessions. Because the query session command is a DOS based command, the results aren't formatted nicely into variables/members that powershell can easily understand and work with, so formatting/manipulation is done using the .Substring and .Trim functions. The list of user sessions t hat is obtained is then compared against the safelist and if the user is not present in the safelist, is then logged off the server.

You will need to setup a scheduled task to run this powershell script - you can view my blog post here on setting up Powershell scripts to run via scheduled tasks in windows

$safelist = "administrator", "user1"
$date = get-date -f "ddMMyyyy"
$logfile = "C:\Admin\LogOffScript-$date.txt"

$sessions = query session |  where-object { $_ -notmatch '^ SESSIONNAME' } | %{
    $item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
    $item.Active = $_.Substring(0,1) -match '>'
    $item.SessionName = $_.Substring(1,18).Trim()
    $item.Username = $_.Substring(19,20).Trim()
    $item.Id = $_.Substring(39,9).Trim()
    $item.State = $_.Substring(48,8).Trim()
    $item.Type = $_.Substring(56,12).Trim()
    $item.Device = $_.Substring(68).Trim()
    $item


foreach ($session in $sessions)
{
if ($safelist -notcontains $($session.username))
{
$time = get-date
logoff $($session.id)
write-output "$time | Logged off $($session.username)" | out-file $logfile -append
}
}

Wednesday, 12 October 2016

Windows - Unable to remove printer driver - The specified printer driver is currently in use

Sometimes you may need to uninstall a printer driver from a computer (because of corruption, to re-install etc), and may get the below error message;

"Unable to remove printername. The specified printer driver is currently in use"



This may even occur AFTER you have removed the printer itself from your list in Devices & Printers.

Here are some steps I found that allowed me to remove the printer and printer driver without having to restart the computer;


  1. Open Devices and Printers
  2. Right click the device you need to remove and select Remove Device
  3. Open Services.msc and locate the Print Spooler service
  4. Right click the Print Spooler service and select Stop
  5. Open regedit
  6. Browse to the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Environments\
  7. Depending on whether you are running a 32 or 64 bit windows, expand the key for Windows NT x86 (if you're running 32 bit windows), or Windows x64 (if you are running 64 bit windows)
  8. Expand the Print Processors key
  9. Rename any entries under Print Processors to have .old on the end. In the example below, there is one entry, winprint which I renamed to winprint.old

  10. Go back to services.msc and start the Print Spooler service
  11. Open the Print Server Properties and try to remove the driver pack - it should now remove successfully
  12. Once the driver pack is removed, stop the Print Spooler service again
  13. Go back to regedit and rename the key(s) you renamed to have .old on the end back to their original name(s) - as per my example, winprint.old will be renamed back to winprint
  14. Start the Print Spooler service from services.msc
  15. Re-install printer & drivers as required




Tuesday, 11 October 2016

Removing old Windows Updates - Windows Installer Directory

Windows updates can tend to take up a large number of space after some time on the system drive (C:\), and are not easily removed.

Updates are typically installed into the C:\Windows\Installer directory and hold the .msi and .msp files used to install (or uninstall) windows updates.

A company called "Homedev" have developed a product called "Patch Cleaner" that is clever enough to search this windows installer directory and detect which patches can safely be removed. Over time windows updates tend to replace, outdate or supersede each other - rendering them useless and taking up precious hard disk space on your hard disk!

How does it work? Well, as explained by Homedev, their application queries the operating system for a list of all the currently installed patches and updates. It then compares this list returned by the operating system against all the files in the C:\Windows\Installer directory. Anything that's found in the folder but not in the list provided by the operating system is flagged as able to be removed by the application.

The application also has the ability to relocate the files to another location first (such as another drive, like an external USB hdd) which reduces the risk involved in removing some of these files. If it turns out the files are required they can simply be copied back to the C:\Windows\Installer directory.

The latest version of the application can be downloaded and installed from the below website;

http://www.homedev.com.au/free/patchcleaner


  1. Once you have downloaded the file, double click it to run/execute
  2. Click Next to begin the installation process

  3. Select I Agree on the license agreement then select Next

  4. It is recommended to leave the default installation path and set to Everyone to be able to access the application. Click Next

  5. Click Next to begin the installation

  6. Click Close to exit the wizard once installation has completed

  7. You can now run PatchCleaner from the shortcut placed on the desktop or from within the Start Menu

  8. Upon startup, the application will automatically scan for files that can be removed

  9. Once the scan is finished, you will be presented with a window like the one below. The screen details how many files are orphaned and can be removed (in this example, there are 32 files, totalling 2.17GB in size). You can click either the Delete button to permanently delete the files, or the Move button the move all these files to another location (as mentioned previously)

  10. After deleting or moving the files, the application will run another scan and present a window again like the one above.




Monday, 10 October 2016

iPod/iPhone/iPad not appearing in iTunes

I occasionally experience an issue with my iPod, where after connecting it to my laptop via USB, and having the iPod appear in Windows Explorer, it won't appear as a device in iTunes

iPod showing in Windows Explorer but not iTunes

Follow the steps below to fix the issue;


  1. Close iTunes if you already have it running
  2. Click on the Start button (bottom left corner of screen) and type services.msc and press Enter
  3. A new window will now open showing a list of all windows services. Sort the list by name and locate the Apple Mobile Device Service
  4. Right click on this service and select Restart

  5. Once the service has restarted, locate the iPod Service. Right click on this service and select Restart

  6. Open iTunes. Your iPod/iPhone should now appear within iTunes correctly


Friday, 7 October 2016

Optus - Sagemcom F@ST 3864 modem/router - admin username and password

The Sagemcom F@ST 3864 modem/router that is provided by Optus has an administrative interface that you can login to to access advanced features that aren't accessible via the the "standard" interface.

The standard interface is accessed via http://192.168.0.1/main.html?loginuser=1 and allows access to basic settings such as wifi options without needing to enter a username/password

However, if you change the "loginuser=" value from a "1" to a "0" you get prompted for a username/password. Once you've entered the correct username/password you can then access more advanced features within the modem setup/config.

There are a number of forum posts stating some of the default usernames/passwords for this modem, but none of them worked for me, even after a factory reset. What I did stumble across though was how to definitively (and easily) retrieve the admin password for this modem;


  1. Open a web browser and go to http://192.168.0.1/password.html
    You will be presented with a screen like the one pictured below;

  2. Right click in a blank area of the page, and select the option to "View source" or "View page source" (the wording might be slightly different depending on what browser you are using)

  3. This will load up all the html code used on this page. If you look towards the top of the page, you will see a line starting with "pwdAdmin = " - what is after this and contained within single quotes is the admin password that is set on the router



  4. You can then go to the URL http://192.168.0.1/main.html?loginuser=0 and enter the username "admin" and the password from Step 3 above and you will be able to access the hidden/advanced menu options within the router



Fix Windows Update Error Code 80070003

I got this error code today on a Windows 7 PC after trying to install some windows updates



Code 8007003
Code 643

To fix it, follow the steps below;
  1. Click on the Start button (bottom left corner) and types services.msc and press enter (to open the Services control panel)
  2. Locate the Windows Update service. Right click it and select Stop


  3. Open Windows Explorer. Navigate to the folder C:\Windows\SoftwareDistribution\Download folder. Delete everything within this folder - (this is where the windows updates are downloaded to before being installed)
  4. Go back to your list of services from Step 2. Right click the Windows Update service and select Start
  5. Go back to your windows updates and click Check for updates again and proceed to install them as you normally would




Thursday, 6 October 2016

IIS - Make OWA the Default Website Page

After installing Microsoft Exchange, a "virtual directory" for Outlook Web Access (OWA) is created that is generally accessible via the URL https://mail.yourdomain.com/owa

In some scenarios it may be preferable to configure https://mail.yourdomain.com to redirect automatically to the OWA virtual directory (as users may forget to include this part if they are manually typing the URL). This means as soon as they try to access the root domain website, they are automatically presented with a login page for OWA.

It is very easy to configure, as per the steps below;

  1. Open Internet Information Services (IIS) Manager (from Control Panel > Administrative Tools)
  2. Expand the tree from the left hand side and highlight/select Default Web Site

  3. Double click the HTTP Redirect icon from the main window

  4. Select the option to Redirect requests to this destination and enter /owa into the text box below
    Select the option to Only redirect requests to content in this directory (not subdirectories). Ensure the status code is set to Found (302)

  5. Click Apply in the top right corner to apply the changes
  6. Try accessing the base URL again and you should be automatically redirected to the OWA login page



Wednesday, 5 October 2016

Get Computer Serial Number & HP Product Number using Powershell

You can use powershell to quickly obtain the serial number/service tag for a computer/server

get-wmiobject win32_bios | select SerialNumber



Some computer manufacturers (such as HP) also have a product number that you can access with the following command;

get-wmiobject win32_computersystem | select-object OEMStringArray

This win32_computersystem class also contains other details/information such as the Manufacturer and Model number of the computer system - you can view all the details by removing the pipe and everything after it

get-wmiobject win32_computersystem

This information is also available through the registry via the key
HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System

Thursday, 29 September 2016

iPhone/iPad - Cannot send mail. A copy has been placed in your Outbox. The recipient was rejected by the server

Occasionally I've seen users experience an issue where they can no longer send emails to anyone from their iPad or iPhone, they get the below error message;

"Cannot send mail. A copy has been placed in your Outbox. The recipient %name% was rejected by the server"

The issue is usually caused by the authentication (ie. username and password) failing for the email account, because it is either missing or incorrect.

I've often seen this happen after iOS updates, as passwords for email accounts aren't always preserved during the update process. As a result, the password appears to be present (when you check the settings), but actually isn't, and therefore emails won't send any longer.

To fix the issue, do the following on the problematic device(s);


  • Go to Settings
  • Go to Mail

  • Select Accounts

  • Select the account that you are having problems sending from

  • Select the account again (first option at top of screen)

  • Update the Domain, Username and Password fields. Even if the password appears to be in there (represented by black circles), delete whatever is in there and re-type the password

  • Click Done from the top right corner. Settings should now be checked and you should get a list of ticks down the ride side of the page
If the settings saved successfully you can try sending emails again, it should now work correctly.

Friday, 23 September 2016

How to easily view/find the distinguished name for an Active Directory user account

The distinguished name for a user account is often required for scripting or other management/administrative tasks when working with Active Directory. It represents the unique identifier for every user account so is one of the best ways to work with user accounts (as opposed to just working off first name, last name etc).

They are difficult to remember, and nearly impossible to type using the correct format/syntax - so here's some simple instructions on how to quickly/easily obtain the distinguished name for a user account from Active Directory Users & Computers;

  1. Open Active Directory Users & Computers
  2. Ensure "Advanced Features" are enabled (go to View > Advanced Features)
  3. Open the Active Directroy User object you wish to view the DN for
  4. Select the Attribute Editor tab
  5. Scroll down to the locate the Distinguished Name value
  6. You can double click the entry then copy it to the clipboard from the "Value" field as per the screenshot below

Monday, 19 September 2016

iTunes could not connect to the iPhone because an invalid response was received from the device

I encountered this issue on my home PC after getting my new iPhone 7. I had previously sync'd the phone with my laptop, but upon connecting it to my PC, I got the error message;

"iTunes could not connect to the iPhone because an invalid response was received from the device"

I was pretty confident the phone wasn't the issue as it had successfully sync'd with another computer - I tried the following steps first which did not fix the issue;


  • Different USB/lightning cable
  • Different USB port
  • Rebooted computer
  • Rebooted iPhone
  • Ensured iPhone wasn't locked when connecting
  • Removed iPhone device from device manager
What ended up fixing the issue in the end was uninstalling and re-installing iTunes on the computer.

Run/Trigger Powershell Script from Windows Task Scheduler

Windows built in Task Scheduler application can be used to trigger/run powershell scripts on custom schedules as required. Here's how to set it up.


  1. Open Task Scheduler (Control Panel > Administrative Tools > Task Scheduler)
  2. Right click on Task Scheduler Library and select Create Task

  3. Enter a name for the scheduled task. Select the option to Run whether user is logged on or not to ensure the task will still run even if you are not currently logged into the computer

  4. Go to the Triggers tab and click the New button. Set the task to run on the schedule as required (eg. daily, weekly, hourly, etc). I recommend setting the option to Stop the task if it runs longer than and set to 30 mins. This means if there is a bug/problem with the script it will terminate after this time and won't continue running in the background
  5. Select the Actions tab and click the New button. Configure as per below:

    Action: Start a program
    Program/script: C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe
    Add Arguments: (Full path to your powershell script .ps1 file)

    Example path may be D:\Powershell\TestScript.ps1

  6. Other settings and conditions can be configured in their respective tabs as required, but the default settings within here will work

    Note: if you find that your scheduled task won't run, check out My Post on Powershell Execution Policies which may be preventing the scheduled task from running your powershell script

Friday, 9 September 2016

Get ActiveSync Enabled Accounts/Mailboxes using Powershell

Here is a short/simple script you can use to obtain a list of all mailboxes within your Exchange environment that have the ActiveSync service enabled on them.

#Add Exchange Cmdlets
add-pssnapin *exchange* -erroraction SilentlyContinue

get-casmailbox -resultsize unlimited | where {$_.ActiveSyncEnabled -eq $true}

The output will now be displayed showing all mailboxes in your environment that have ActiveSync functionality enabled on them.

You can export your results to a .csv by adding a bit more to the end of the command as per below. You can of course change the output path as required

get-casmailbox -resultsize unlimited | where {$_.ActiveSyncEnabled -eq $true} | select Name, ActiveSyncEnabled | export-csv "C:\activesyncusers.csv" -notype

Monday, 5 September 2016

Backing Up Your PC/Computer for Free

With the relatively low cost of computer storage (hard drives) these days, and the ever increasing risk of viruses and malware infections, there's really no excuse for not backing up your PC to an external hard disk drive on a regular basis.

Having a full backup of your computer ensures that all those important files you have on your computer (think photos, songs, documents, spreadsheets etc) are able to be recovered/restored in the event of a serious problem. Such problems could be a virus or malware infection (as previously mentioned), or your computer/laptop being lost, stolen or damaged, or could even be a random hard disk drive failure that can happen from time to time.

One of the best and easiest backup solution products available that is absolutely free for home/personal use is a product called Macrium Reflect. In this blog post I'll be outlining the process for downloading, installing and configuring Macrium Reflect to backup your computer.

Macrium's process for backing up is referred to as "imaging". It essentially takes a snapshot, or "image" of everything on your hard drive and stores it into a large, compressed "image" file.

Before we begin though, you will need an external hard disk drive (USB connected) for your backup to be stored on. These can be bought from any computer or technology store. A 1TB drive would typically be large enough to backup everything on most personal computers, but large drives are available if required.


  1. To begin the installation, open your web browser and go to http://www.macrium.com/reflectfree.aspx and click the "Download" button at the top of the page. Select the option for "Home Use" if prompted.
  2. A file called ReflectDL.exe will now begin to download. Once the download is finished, run/open the file to begin the installer
  3. Ensure the option for Free/Trial software is selected (it should be by default). All other default options can remain. Click the "Download" button to begin the download.


  4. Select "Yes" to proceed with the download. Note that the download is quite large and can take some time to complete (depending on the speed of your internet connection)
  5. The installer will automatically launch once the download is completed. Click the "Next" button to begin
  6. Click "Next" again to proceed past the welcome page and begin the installer
  7. Select "I accept the terms in the license agreement" and select "Next"
  8. Your macrium reflect free license key is automatically generated and displayed here. Click "Next" to continue


  9. Registration is optional. For the purpose of this tutorial we will select "No" then select "Next"


  10. Leave the default installation options then click "Next"


  11. Click "Install" to begin the installation then click "Finish" to complete the installation when prompted


  12. A shortcut to the Reflect application should have been placed on your desktop. Double click the icon to launch Macrium Reflect


  13. From the main Reflect window, ensure you are on the "Create a backup" tab. Select the disks/drives you wish to backup then click the "Image this disk..." option. For this example, we will only be imaging/backing up the C:\ (system drive). If you have multiple disks/drives you can select them from this screen.


  14. Select the destination folder for where the backup image file is to be kept. This should be the external hard drive you have connected to your computer. In this example, my external hard drive has drive letter G:\ assigned to it, and I'll store the backup in a folder called "Win10Backup" on the G:\. Click "Next" to continue


  15. From the next screen you can select a retention or schedule/policy for your backups. You can click the "Add Schedule" button and select the option for "Full". I recommend running a full backup on a weekly basis. Schedule the backup to run on a day/time where the computer is not being utilised (the computer will need to be left switched on for the backup to run). For this example, we'll schedule to run on Monday mornings at 2:00am




  16. Uncheck the options to "Define Retention Rules" and set the option to "Purge the oldest backup set(s) if less than 500GB remaining". Click "Next" to continue


  17. Review your settings and click "Finish" to complete the process
  18. Uncheck the option to "Run this backup now" then click "OK" to save the backup definition file you've just created


  19. You will now be taken to the "Backup Definition Files" tab where you can see the backup definition you have just created. From here you can make amendments/adjustments to the backup file if required


  20. From the "Scheduled Backups" tab you can also review the schedule for your backups and can make amendments if required



    Depending on the size of your hard drive(s) and the amount of data on them, it can take several hours for a backup to complete.

    Once a full backup has completed, you can check for a .mrimg file in the backup location you specified in Step 14 (above). If there is a file in this folder then you have successfully backed up your computer to an image file!



    Stay tuned for my next blog post where I'll run through the process of restoring/recovering files from a backup image file.


Friday, 28 March 2014

Check/Monitor Website URL with Powershell

Windows Powershell has a built in web request module that you can use to test/check the availability of website URL(s).

The full script to do this is below;

[string] $url = "http://www.google.com"
[net.httpWebRequest] $req = [net.webRequest]::create($url)
$req.method = "HEAD"
[net.httpWebResponse] $res = $req.getresponse()

The first line is self explanatory - simply put in the full URL for the website you wish to check. In this example we will be checking http://www.google.com

[string] $url = "http://www.google.com"

The second line is where we create the actual web request instance in Powershell - under the $req variable

[net.httpWebRequest] $req = [net.webRequest]::create($url)

On the third line, we change the request method to be "HEAD" which means that only header information for the requested URL is retrieved. This speeds up the web request process as it does not pull all the data from the web URL - only the header information. If you leave this line out, the default method is "GET".

$req.method = "HEAD"

On the last line we actually submit the web request, and store the response in the $res variable

[net.httpWebResponse] $res = $req.getresponse()

For a successful web request, the response should look something like this:

IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Cache-Control, Content-Type, Date, Expires...}
ContentLength           : -1
ContentEncoding         : 
ContentType             : text/html; charset=ISO-8859-1
CharacterSet            : ISO-8859-1
Server                  : gws
LastModified            : 28/03/2014 10:24:19 AM
StatusCode              : OK
StatusDescription       : OK
ProtocolVersion         : 1.1
ResponseUri             : http://www.google.com.au/?gfe_rd=cr&ei=I7M0U5P_BenC8gfRvIHADg
Method                  : HEAD
IsFromCache             : False

Based on this, you could check the statuscode or statusdescription properties of $res to make sure the value matches "OK".

Alternatively, if you enter an invalid URL for a website that doesn't exist, you will get an error, and the value of $res will be $null. The error you get will be something along the lines of;

Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (502) Bad Gateway."
At line:4 char:46
+ [net.httpWebResponse] $res = $req.getresponse <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Wednesday, 26 March 2014

Get Folder Size (including subfolders) with Powershell

The method for obtaining the size of all items within a folder using Windows Powershell is unfortunately not as straight forward as it probably should be. The method outlined below is very useful for querying multiple folders to determine the size of all items inside, including all subfolders and files.

$dir = "C:\temp"
$totaldirsize = (get-childitem $dir -recurse -force | measure-object -property length -sum)

The first variable sets the directory that we wish to query - in this example it is C:\temp.

Next, we use a get-childitem to query the directory. The -recurse and -force switches mean that all sub directories and files are also included. We then pipe the results to measure-object and calculate the length of each child item (which is actually the size in bytes) and use the -sum switch to add them all up.

If you run the above command, and then look at the $totaldirsize variable, you will see something like below;

PS C:\> $totaldirsize

Count    : 38
Average  : 
Sum      : 51652089
Maximum  : 
Minimum  : 

Property : length

So from this we can see there are 38 items in total in the C:\temp directory, and the sum of all files is 51652089 bytes. To make this more useful, we can easily convert this value to KB, MB or GB

$mbsize = $totaldirsize.sum / 1MB

If we now look at $mbsize, we'll usually have an integer with a large number of decimal places. In this example, the result I got was 49.2592706680298. So as a final step, I'd like to round this number to 2 decimal places

$mbsize2 = "{0:N2}" -f $mbsize

Now if we look at the value of $mbsize2, the result is 49.26.

You can change the 2 in {0:N2} to any other digit to round the number to that many places after the decimal point.