Month: February 2011

Test Multiple Network Locations with Test-Path

Frequently we relocate a large number of employee home folders in bulk and we need to verify that the move was successful, or we want to test the validity of a large number of network shared folders. This utility does that utilizing the Powershell test-path commandlette.

If you want a basic understanding of how the test-path commandlette works, type this in your Powershell console window:

get-help test-path –full

Here is a general description of what this script utility, Test-Paths.ps1 does:

.SYNOPSIS

This script will test the validity of paths that are contained in the paths.ini file. Output is generated to a CSV file, and to Out-GridView.

.DESCRIPTION

The targets of the test-path command are pulled from the “paths.ini” file that is collocated with the test-paths.ps1 file.

Each target is tested using the Powershell test-path commandlette. Results are stored along with the path name in two output methods.

out-gridview and filename.csv

.PARAMETERS

-nogridview: Prevents the script from generating the Out-GridView window.

-noexport: Prevents the script from generating the exported CSV file.

-outfile filename.csv: Use an alternative name for the output file. CSV extension is best. The default if this switch is not added is testpathresult.csv.

.EXAMPLES

This will give two outputs. A file named testpathresult.csv and the out-gridview window:

.\test-paths.ps1

This example will give no out-gridview window, but will save a CSV file named patrick.csv:

.\test-paths.ps1 -nogridview -outfile patricks.csv

This example will give only the out-gridview window:

.\test-paths.ps1 –noexport

Here are a couple of examples with the script in action. In this first one I will get all failed status results for the test-path commands, but that is because I am using simulated directory paths.

Here are the contents of the paths.ini file which is collocated with the script:

Figure 1: Contents of Paths.ini File

Here are a few screen shots of the utility being run, and some of the selected output screen shots.

.\test-paths.ps1

Figure 2: Command Window Output

You can see that the Powershell command window echoes the target currently being tested.

Since the above example did not use either the of the two exclusion switches, both out-gridview and a CSV file were generated. Here are images of both types of output:

Figure 3: Out-gridview

Figure 4: Testpathresult.CSV File

Notice there are two columns in Figure 3: Accessible and HomeDirPath. In each of these the path tested was shown as False because the path was not found.

Here is another example, but this one excludes the export to the CSV file.

.\test-paths.ps1 –noexport

I added “c:windows” to the paths.ini file to show that the test-path can actually find a valid path. With this one we still see the out-gridview window, but no CSV file is generated. Notice that now we have a True in the Accessible column.

Figure 5: True Path Now Found

And finally, the last example where an alternate output file name is generated using the –outfile parameter:

.\test-paths.ps1 –outfile february28th.csv -nogridview

With this one no out-gridview window is generated, but the output file is unique and will not be overwritten the next time the utility is run.

Figure 6: Alternate Output File Naming

In summary, this utility provides an easy way to test a few, or thousands of network paths very easily.

It is run in a Windows Powershell environment. The target paths are inserted in the paths.ini text file, and the command is run as detailed above.

Let me know if you have any questions about this.

Thanks

Patrick Parkison

Below is the code used in the test-paths.ps1 script.

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

<#

.Patrick Parkison

pp1071@att.com

.SYNOPSIS

This script will test the validity of paths that are contained in the paths.ini file. Output is generated to a CSV file, and to Out-GridView.

.DESCRIPTION

The targets of the test-path command are pulled from the “paths.ini” file that is co-located with the test-paths.ps1 file.

Each target is tested using the Powershell test-path commandlette. Results are stored along with the path name in two output methods.

out-gridview and filename.csv

.PARAMETER

-nogridview: Prevents the script from generating the Out-GridView window.

-noexport: Prevents the script from generating the exported CSV file.

-outfile: Use an alternative name for the output file. CSV extension is best. The default if this switch is not added is testpathresult.csv

.EXAMPLES

This will give two outputs. A file named testpathresult.csv and the out-gridview window:

.\test-paths.ps1

This example will give no out-gridview window, but will save a CSV file named patrick.csv:

.\test-paths.ps1 -nogridview -outfile patricks.csv

This example will give only the out-gridview window:

.\test-paths.ps1 -noexport

#>

param([switch] $noGridview, [switch] $noExport, [string]$outfile = “testpathresult.csv”)

#Change the title bar of the script window. This is helpful for long running scripts.

$Host.UI.RawUI.WindowTitle = “Running test-path utility.”

#Makes an array, or a collection to hold all the object of the same fields.

$dataColl = @()

#Get location of the script. Info will be used for getting location of all test targetrs, and for saving output to the same folder.

function Get-ScriptPath

{

Split-Path $myInvocation.ScriptName

}

#ScriptPath will be used to place the output file.

$scriptPath = get-scriptpath

#Paths.ini is a text file containing a list of targets e.g. \servernamesharename

$sourcefile = $scriptPath + “paths.ini”

<#

This is the output CSV file. It is overwritten each time the script is run.

If a historical record is desired, a date can be appended to the file name. See this reference on how to do that: https://thescriptlad.com/?s=date

#>

$outputfile = $scriptPath + “” + $outfile

foreach ($path in (gc $sourcefile)){

$dataObject = New-Object PSObject

Write-Host “Scanning: $path”

Add-Member -inputObject $dataObject -memberType NoteProperty -name “Accessible” -value (Test-Path $path )

Add-Member -inputObject $dataObject -memberType NoteProperty -name “HomeDirPath” -value $path

$dataColl += $dataObject

}

#This section is used to generate the out-gridview display.

if (!$noGridview)

{

$label = “Test-Path Results. Total Responses: ” + $dataColl.count

$dataColl | Out-GridView -Title $label

}

#Output to the CSV file for use in Excel.

if (!$noExport)

{

$dataColl | Export-Csv -noTypeInformation -path $outputfile

}

#Restore the default command window title bar.

$Host.UI.RawUI.WindowTitle = $(get-location)

Voice Spoken Weather Report

Here is a Powershell script that is fun, and useful if you like to be able to get a spoken weather report quickly.  It uses the SAPI com object in Windows to convert text to voice. If you have more than one TTS engine on your PC, you will be able to modify it under the Windows Control Panel.

To start with you will need to create a function that will be used to convert text to voice.

function say

{

$Voice = new-object -com SAPI.SpVoice #Make a voice object using the com object.

$Voice.Speak( $Args[0], 0 )|out-null

}

The second part of this script comes from /\/\o\/\/. You’ll find a detailed post on how to connect to a web-service to capture weather information.  That is located here:

http://thepowershellguy.com/blogs/posh/archive/2009/05/15/powershell-v2-get-weather-function-using-a-web-service.aspx

What I’ve done is to put his work into a function that allows you to select a country or city based on command line parameters, and then speak the results over your computer speakers. If you select the -help parameter and use the -country countryname parameter, all of the cities for your country will be selected.

Here is that function:

Function Get-Weather ([switch]$help,$city,$country,$filter = ”)

{

$weather = New-WebServiceProxy -uri http://www.webservicex.com/globalweather.asmx?WSDL

if ($help)

{

write-host “Starting help.”

$xml = [xml]$weather.GetCitiesByCountry($Country)

$xml.NewDataSet.table | sort city | Out-GridView

}
else

{

([xml]$weather.GetWeather($City,$country)).CurrentWeather

}

}

Now that the functions are out of the way, here is the “main” portion of the script.

#Main
#Determine if help switch is active.

switch ($help)

{

{$_ -eq $true }

{

get-weather -help -country $country

break

}

default

{

if ($full)#This is the full text output. No audio.

{

Get-Weather  -country $country -city $city

}

else #Audio output, streamlined for quicker information.

{

$currentWeather = get-weather -city $city

Write-Host $currentWeather

$currentTemperature = $currentWeather.temperature

$currentTemperature = $currentTemperature.split()

$currentSkyConditions = $currentWeather.SkyConditions

$wrsentence = “Here is the weather information you needed. In ” +  $city + ” the temperature is ” + [int]$currentTemperature[1] + ” degrees fahrenheit, and it is ” + $currentSkyConditions

say $wrsentence

}

}

}

I’ve used the default city of Memphis that I set up in the parameters, but it works just as well if I used the command line parameters.

I’ve saved all of this in a script called get-weather.ps1

Here is a sample using  Quebec, Canada

.\get-weather  -country Canada -city Quebec

If  I am not sure of all of the city names that are available for Mexico, then I can type:

.\get-weather  -country Mexico -help

This will open up an out-grid view with all of the cities available in Mexico.

Since I set Memphis as the default city in the parameters, just typing the following will give me local weather information.

.\get-weather.ps1

If I want just screen output for a city, I can use something like the following:

.\get-weather -full -country canada -city Quebec

Give this a try and see if it works. Let me know if you have any questions.

Thanks,

Patrick

User Home Folder Size and other Information (without Quest)

Frequently during my daily work I need to gather information on users that are contained in our Active Directory listing.  In a previous blog post, I had a script which does this work using a Quest commandlette.  Some environments don’t allow this, so a method to gather user data without using Quest is helpful to have available.
This script is used to quickly gather information on a users home folder, SAM account name, their email address, and the size of their home folder.

I use this a lot when I am moving users home folders from one server to another. To save time I frequently have the line that gathers home folder size remarked out with #.

The user account names that I am searching for are contained in a text file called
accounts.txt. This file is contained in the same folder as this script. The output is sent to the screen as well as a log file called output.csv.

#************************************************************

$userArray = @(“SAMID,HomeDirectory,EmailAdress,HomeFolderSize”)
$allUsers = gc .\accounts.txt
$tempArray = @()
function logfile($strData)
{
Out-File -filepath output.csv -inputobject $strData -append
}
function getAccountInfo
{
$strName = $currentUser
$strFilter = “(&(objectCategory=User)(samAccountName=$strName))”
#Get User AD info
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = $strFilter
$objPath = $objSearcher.FindOne()
$objUser = $objPath.GetDirectoryEntry()
[string]$folder = $objUser.homeDirectory
[string]$email = $objUser.mail
[string]$samID = $objUser.sAMAccountName
[string]$folderSize= getFolderSize($objUser.homeDirectory)
#$objUser.memberOf

$result = “$samID,$folder,$email,$folderSize”
$result #This causes the output to steam out, and be piped as the return from the function.
$folderSize = $null
$fs = $null
}
function getFolderSize($strPath)
{
$fs = New-Object -comobject Scripting.FileSystemObject
#Check validity of $strPath
if ($fs.FolderExists($strPath))
{
[double]$tempSize = ($fs.GetFolder($strPath).size) / 1024 / 1024
$tempSize = ‘{0:N}’ -f[double]$tempSize
$tempSize
}
else
{
$tempSize = “Bad folder path!”
$tempSize
}
}
$header = “SAMID,HomeDirectory,EmailAdress,HomeFolderSize”
Out-File -filepath output.csv -inputobject $header
foreach ($currentUser in $allUsers)
{
$tempOutput = getAccountInfo $currentUser
$tempOutput
$userArray += [string[]]$tempOutput
logfile($tempOutput)
}

#************************************************************
Let me know if you have any questions about this, or if it is helpful.

Thanks
Patrick

User Home Folder Size and other Information (with Quest)

Here is a function that can be used to quickly gather folder information about a user’s home folder.

There is one stipulation.

For this to work you must have the Quest Active Directory Snap-In configured for your Powershell session.
This will apply to users contained within an Microsoft Active Directory structure.
I have used the “^” in place of the “select-object” command. This is an alias that I use to make typing much faster. It is a symbol that I have never had a conflict on.

I have called the function GQUF. This is short for Get-QADUserFunction, but you may call it whatever you like of course.

Here is the syntax of the command. There are three options that are available when this command is run with the second command line switch.

“GQUF userid –groups” or

“GQUF userid -explorer” or

“GQUF userid –size.”

The –groups switch will detail all of the active directory groups in which the member is included.

The –explorer switch will open an explorer window pointed at the user’s home folder.

The –size switch will detail the total size of the user’s home folder.

Here is the code. See a screen shot at the bottom.

#*******************************

#This function looks up a user home drive and home directory

#Uses get-qaduser

function gquf

{

$UserID = $Args[0]
$Domain = $Args[1]

$result = Get-QADUser $Args[0] | Select-Object SamAccountName, homedirectory, homedrive, email, displayname # | ft -autosize

#$result | ft -autosize

Write-Host “Display Name:” $result.displayname -foregroundcolor green

Write-Host “Email Address:” $result.email -foregroundcolor green

Write-Host “HomeDir:” $result.homedrive $result.homedirectory -foregroundcolor green

Write-Host “”

Write-Host “Permissions for “$result.homedirectory -foregroundcolor Yellow

get-aclf $result.homedirectory

switch ($Args[1])

{

{$_ -eq “-groups”}

{

write-host “Member Of:”

(Get-QADUser $Args[0] | ^ memberof).memberof | sort

}

{$_ -eq “-explorer”}

{

explorer $result.homedirectory

}

{$_ -eq “-size”}

{

Write-Host “Calculating the size of the homefolder…” -foregroundcolor red

$fs New-Object -comobject Scripting.FileSystemObject

$tempSize $fs.GetFolder($result.homedirectory).size/1024/1024

$tempSize ‘{0:N}’ -f [double]$tempSize

Write-Host “$tempSize MB”

}

}

}
#*******************************

Here is the screen shot for the –size switch. Sensitive information has been blocked out.

Thank You,

Patrick

Creating a Folder Named After a Date

I like to create folders on the fly for logging  purposes, as well as for keeping track of re-occurring actions, like scanning for disk usage on a given date.

The following PowerShell command is useful for creating a folder with a name in the format YYYYMMDD.

$folderName = “folder1_” + (Get-Date -uFormat  “%Y%m%d”)
This command makes a folder call folder1_20110226.

Another technique is do make the folder, and assign the date to the name all at once.

md (“folder2_” + (Get-Date -uFormat  “%Y%m%d”)).

Below you will see both techniques used, and then the old DIR command just to show that they were created successfully.

Make Folders with Date Names.

Instead of the DIR command I could have used the Powershell commandlette Get-ChildItem folder*, and it would have worked just as well.  I like DIR because I am use to it, and because it is less typing.

That’s all for this entry. Have a nice day.

Thanks,

Patrick

Retrieving Shares in Powershell with WMI

Powershell one liners are a great way to work with Windows Management Instrumentation (WMI).  One of the WMI features I use the most is Win32_Share. It is a fast and easy way to retrieve share information.

In this blog entry I would like to explore the capabilities of WMI by developing a WIN32_Share utility. To begin let’s look at the most simple command available.

Get-WmiObject win32_share

Basic WMI Win32_Share Command

You’ll see from the image above that we get back three types of information from this WMI query. Name, Path, and Description. It may not be readily visible, but we also get back several types of shares.  Above we see administrative shares, printer, and shares, and regular file shares. As a system administrator that is interested in managing the files shares available to my user I want to work with only file shares now.  We can add some syntax to filter the type of share that is returned. To do that we need to know the share type.

Here is a modified version of the basic command we used above:

Get-WmiObject win32_share | Select-Object name, path, description, type | Format-Table -autosize

I used the Powershell commandlette select-object to request four specific properties to be returned from the WMI query. They are name, path, description, and type.  Also, I’ve added the text “Format-Table -autosize” to make it all fit neatly on the screen. Here is the result of the query:

GWMI WIN32_Share with Select-Object

Now to make it even more useful, we only want the shares that would be accessed by our users. They don’t need access to the admin shares (type 2147483648), or the shared printer (type 1). To filter on the type property we can use the Powershell commandlette where-object:

Get-WmiObject win32_share | Select-Object name, path, description, type | Where-Object { $_.type  -eq ‘0’}| Format-Table -autosize

GWMI Win32_Share with Type Filtering

Finally we can use the sort-object commandlette to sort the WMI query based on any property we want:

PS>$ Get-WmiObject win32_share | Select-Object name, path, description, type | `>> Where-Object { $_.type  -eq ‘0’}| Sort-Object path | ft -autosize>>

WMI Win32_Share with Sort

One great feature of Powershell version 2.0 is the out-gridview commandlette. It allows you to sort and filter using a dotnet gridview. Here is the command a screen capture of the output. Notice how the actual command is much short as we are filtering and sorting in the resulting gridview object:

Get-WmiObject win32_share | Select-Object name, path, description, type | Out-GridView.

WMI Win32_Share with Out-GridView

So, that’s it for now. Next time we will expand this further to see how we can pull back the file shares from multiple servers at once.