Tag Archives: New-Item

Let’s Learn the Get-FileHash Command

Someone, somewhere, sent me down a path. At the end of it, while it is not where I needed to be, I learned — or relearned rather — about the Get-FileHash cmdlet. Whether you know about it or not, we will quickly cover it and walk through some examples, as well. Get-FileHash, and I quote, “Computes the hash value for a file by using a specified hash algorithm.” This is what it does, but is not the why. Here is its reference page, however: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash, and the why, is definitely in there; you should read it.

The idea, for those that are not going to read it, is that we can obtain a file’s hash and then check the hash to ensure the file has not been changed. At this point in your career, you have likely seen file hashes near, or alongside, a file download. Checking the file hash against the file, after it is downloaded, allows you to be certain that the file is the right one and that it was not altered by the download process, or anything else. It is what you were expecting.

If you are going to run any of my below commands, first be certain you know your working directory and that it is a location where you have permissions to write. We will start by creating a new file, adding a sentence to it, and then returning that content to ensure it is properly in place.

New-Item -Name hashfile.txt -ItemType File

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           4/19/2022  7:06 PM              0 hashfile.txt
Add-Content -Path .\hashfile.txt -Value 'This is our file at the beginning.'
Get-Content -Path .\hashfile.txt
This is our file at the beginning.

That all works and so now we have a file with which can experiment. If you are wondering how you learn PowerShell, this is how you do it. Follow along, as there is a goodie further down below. In this example we invoke Get-FileHash against our file, only returning the algorithm used and the hash. We are using Format-List in order to better display this content.

Get-FileHash -Path .\hashfile.txt | Tee-Object -Variable SaveMeForLater | Format-List -Property Algorithm,Hash
Algorithm : SHA256
Hash      : 3C55E3C7D4C2EEF6910CB70FC425549981528CBBC0400A705104DC09A9391356

In this example, we do the same as we did above, however, now we are going to try out the other parameter values that the Algorithm parameter will accept. By default it uses SHA256, but it will accept SHA1, SHA384, SHA512, and MD5, too.

Get-FileHash -Algorithm SHA1 -Path .\hashfile.txt | Format-List -Property Algorithm,Hash

Algorithm : SHA1
Hash      : BD002AAE71BEEBB69503871F2AD3793BA5764097


Get-FileHash -Algorithm SHA256 -Path .\hashfile.txt | Format-List -Property Algorithm,Hash

Algorithm : SHA256
Hash      : 3C55E3C7D4C2EEF6910CB70FC425549981528CBBC0400A705104DC09A9391356


Get-FileHash -Algorithm SHA384 -Path .\hashfile.txt | Format-List -Property Algorithm,Hash

Algorithm : SHA384
Hash      : E6BC50D6465FE3ECD7C7870D8A510DC8071C7D1E1C0BB069132ED712857082E34801B20F462E4386A6108192C076168A


Get-FileHash -Algorithm SHA512 -Path .\hashfile.txt | Format-List -Property Algorithm,Hash

Algorithm : SHA512
Hash      : C0124A846506B57CE858529968B04D2562F724672D8B9E2286494DB3BBB098978D3DA0A9A1F9F7FF0D3B862F6BD1EB86D301D025B80C0FC97D5B9619A1BD7D86


Get-FileHash -Algorithm MD5 -Path .\hashfile.txt | Format-List -Property Algorithm,Hash

Algorithm : MD5
Hash      : 30091603F57FE5C35A12CB43BB32B5F5

For fun, let’s loop through these values and pump out all the hashes, one right after another. Notice that we are using hard-coded values for the Algorithm parameter. Obnoxious. We will get to another way, which is/was the goodie I mentioned above. The more I think about it though — as I have been in the last 10 minutes — the more I think it might need its own post. Anyway, more on that soon.

'SHA1','SHA256','SHA384','SHA512','MD5'
    | ForEach-Object {Get-FileHash -Algorithm $_ -Path '.\hashfile.txt'
    | Select-Object -Property Algorithm,Hash}

Algorithm Hash
--------- ----
SHA1      BD002AAE71BEEBB69503871F2AD3793BA5764097
SHA256    3C55E3C7D4C2EEF6910CB70FC425549981528CBBC0400A705104DC09A9391356
SHA384    E6BC50D6465FE3ECD7C7870D8A510DC8071C7D1E1C0BB069132ED712857082E34801B20F462E4386A6108192C076168A
SHA512    C0124A846506B57CE858529968B04D2562F724672D8B9E2286494DB3BBB098978D3DA0A9A1F9F7FF0D3B862F6BD1EB86D301D025B80C0FC97D5B9619A1BD7D86
MD5       30091603F57FE5C35A12CB43BB32B5F5

And, there they are again. The various hashes for our file. Now, let’s add some new files. All we are going to do is copy and paste our hashfile.txt to the same directory two times. Rename them so that in addition to hashfile.txt, you have hashfilecopy.txt and hashfile.copy. Watch those names and file extensions, although really, how important do you have to be? Think about it…

When checking the hash of a file, we verify the file contents have not changed. And they have not been changed! Only the file name and file extension have. You are starting to see how this can be a useful tool and guess what? It is built-in.

Get-ChildItem | Get-FileHash | Format-List

Algorithm : SHA256
Hash      : 3C55E3C7D4C2EEF6910CB70FC425549981528CBBC0400A705104DC09A9391356
Path      : C:\Users\tommymaynard\Documents\PowerShell_Get-FileHash\hashfile.copy

Algorithm : SHA256
Hash      : 3C55E3C7D4C2EEF6910CB70FC425549981528CBBC0400A705104DC09A9391356
Path      : C:\Users\tommymaynard\Documents\PowerShell_Get-FileHash\hashfile.txt

Algorithm : SHA256
Hash      : 3C55E3C7D4C2EEF6910CB70FC425549981528CBBC0400A705104DC09A9391356
Path      : C:\Users\tommymaynard\Documents\PowerShell_Get-FileHash\hashfilecopy.txt

Now real quick, let’s make another change. I am going to copy and paste hashfile.txt one last time. This copy I have renamed to hashfilechanged.txt. I opened it up and added a second sentence to it. Beneath the first line, I wrote, “This is our file at the end.”

Get-Content -Path .\hashfilechanged.txt
This is our file at the beginning.
This is our file at the end.
Get-FileHash -Path .\hashfilechanged.txt | Tee-Object -Variable SaveMeForNow | Format-List -Property Algorithm,Hash
Algorithm : SHA256
Hash      : 6998575555A0B7086E43376597BBB52582A4B9352AD4D3D642F38C6E612FDA76

I used Tee-Object a couple of times in this post to capture the original hash and this one, after adding a second sentence. As you can see, the file contents are indeed different now, even though the files could have had the same name, were they in different directories.

$SaveMeForLater.Hash
$SaveMeForNow.Hash

3C55E3C7D4C2EEF6910CB70FC425549981528CBBC0400A705104DC09A9391356
6998575555A0B7086E43376597BBB52582A4B9352AD4D3D642F38C6E612FDA76

And, the goodie I mentioned. It is official; it will get its own post. Why not? I make the rules. I’ll link it from here once it is up and published!

Extract Media Folder from PowerPoint Files

On Wednesday, I wrote a response to something on Stack Overflow. So I don’t have to chase it down one day, I though I’d briefly discuss it here and include the updated code I would be more likely to use, providing I ever need to use it.

If you open a PowerPoint .pptx file in something like 7-Zip, you’ll quickly realize that the .pptx is a compressed, or archived, file format. While this brings down the file size (1.65MB file vs. 3.27MB when expanded), this is more more to say that there are a few folders, and several files, that make up a single PowerPoint file.

A person on Stack Overflow wanted to automate the expansion of a series of .pptx files and extract the media folder. This folder holds all the images in a PowerPoint file. I’m not going to bother to explain the code, but let me set the stage. I created a folder on my desktop called pptx. Inside the folder were four PowerPoint files using the .pptx file extension. My code created a new folder for each file in the pptx folder, expanded each PowerPoint file in their own new folders, located the nested media folder, moved it to the top level of their new folder, and then deleted all the other folders and files inside the new folder. If there wasn’t a media folder, it would still create the new folder; however, it would create a single text file in there called “No media folder.txt.” This was to help ensure the user didn’t think the code didn’t work, when they didn’t find the media folder inside the new folder.

I’ll included the original code from the forum post further below, but for now here’s an updated and cleaner version.

$Path = 'C:\users\tommymaynard\Desktop\pptx'
$Files = Get-ChildItem -Path $Path

Foreach ($File in $Files) {
    New-Item -Path $File.DirectoryName -ItemType Directory -Name $File.BaseName | Out-Null
    $NewFolder = $File.FullName.Split('.')[0]

    Add-Type -AssemblyName System.IO.Compression.FileSystem
    [System.IO.Compression.ZipFile]::ExtractToDirectory($File.FullName,$NewFolder)
    
    If (Test-Path -Path "$($NewFolder)\ppt\media") {
        Move-Item -Path "$($NewFolder)\ppt\media" -Destination $NewFolder
        Get-ChildItem -Path $NewFolder | Where-Object {$_.Name -ne 'media'} | Remove-Item -Recurse

    } Else {
        Get-ChildItem -Path $NewFolder | Remove-Item -Recurse
        New-Item -Path $NewFolder -ItemType File -Name 'No media folder.txt' | Out-Null
    }
}

And, here’s the original code and a link to the post itself. This below version didn’t use the $NewFolder variable, so there’s overwhelming inclusion of this piece of code: $File.FullName.Split(‘.’)[0]. It also defaulted to use the Expand-Archive cmdlet, if that was available. As I mentioned in the Stack Overflow post itself, it’s so slow. I’ve removed that so that it’s much faster now, which reminded me, I’ve actually written about this time difference before. It was just last October.

$Path = 'C:\users\tommymaynard\Desktop\pptx'
$Files = Get-ChildItem -Path $Path

Foreach ($File in $Files) {
    New-Item -Path $File.DirectoryName -ItemType Directory -Name $File.BaseName | Out-Null

    If (Get-Command -Name Expand-Archive) {
        Expand-Archive -Path $File.FullName -OutputPath $File.FullName.Split('.')[0]

    } Else {
        Add-Type -AssemblyName System.IO.Compression.FileSystem
        [System.IO.Compression.ZipFile]::ExtractToDirectory($File.FullName,$File.FullName.Split('.')[0])
    } # End If-Else.

    If (Test-Path -Path "$($File.FullName.Split('.')[0])\ppt\media") {
        Move-Item -Path "$($File.FullName.Split('.')[0])\ppt\media" -Destination $File.FullName.Split('.')[0]
        Get-ChildItem -Path $File.FullName.Split('.')[0] | Where-Object {$_.Name -ne 'media'} | Remove-Item -Recurse

    } Else {
        Get-ChildItem -Path $File.FullName.Split('.')[0] | Remove-Item -Recurse
        New-Item -Path $File.FullName.Split('.')[0] -ItemType File -Name 'No media folder.txt' | Out-Null
    } # End If-Else.
} # End Foreach.

Use the Date and Time in File Names

I have functions here and there, that will at times, create files to store generated information. Part of this process is naming the file. For me, I’ll often add the date and time to my file’s name, in order to know it’s creation time, at a glance.

So what does this mean? It means that I’ll often have to jump over to my ConsoleHost, or an old function, I suppose, to be certain I’m using the same date time format. Well, that may end today, right after this post is published. Now, I’ll have another place to look — my own website — to ensure my consistency when it comes to including the same naming.

You can’t use the standard output of Get-Date in a file name, and you probably wouldn’t want to anyway. This is due to the colons included in the time; they’re invalid characters for a file name.

PS > Get-Date

Friday, October 28, 2016 9:21:28 PM

But when we put the Get-Date output in a file name, it changes the output. We loose the day of the week and month as words, and instead get a date with forward slashes, such as 10/28/2016. This conversion happens when we put the cmdlet inside a string. Take a look.

PS > New-Item -Path "$(Get-Date).txt" -ItemType File
New-Item : Cannot find drive. A drive with the name '10/28/2016 09' does not exist...
PS > "$(Get-Date).txt"
10/28/2016 09:27:04.txt

The error makes sense though, as it’s parsing 10/28/2016 as a path. Not really the point here, but good to know. Either way, those slashes and colons aren’t going in a file name. It’s not permitted.

I’ve had a consistent file naming convention that includes the date and time for awhile now. What I really like about my date format is that files are automatically sorted by year, then month, then day, and then the time.

PS > Get-Date -Format 'DyyyyMMddThhmmsstt'
D20161028T093059PM

PS > New-Item -Path "Get-Date -Format 'DyyyyMMddThhmmsstt'" -ItemType File

    Directory: C:\Users\tommymaynard

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       10/28/2016   9:32 PM              0 Get-Date -Format 'DyyyyMMddThhmmsstt'

Oops, notice the problem in that second example above? I need to ensure the command inside my string is being treated as a command, and not just standard text. In the previous example, it used my actual command, as the file name. Let’s try that again.

PS > New-Item -Path "$(Get-Date -Format 'DyyyyMMddThhmmsstt').txt" -ItemType File

    Directory: C:\Users\tommymaynard

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       10/28/2016   9:34 PM              0 D20161028T093445PM.txt

In this final example, we included some text around the date, so that I can better distinguish the reason for the file, but still have the date and time included in the name. We also used the subexpression operator —  $() — to make sure my command was treated as such. Oh, did you notice the capital D and T? I used these as separators to help better display the (D)ate and (T)ime. It makes the files name easier for me to visually parse.

PS > New-Item -Path "User_Disable_Log($(Get-Date -Format 'DyyyyMMddThhmmsstt')).txt" -ItemType File

    Directory: C:\Users\tommymaynard


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       10/28/2016   9:37 PM              0 User_Disable_Log(D20161028T095316PM).txt

That’s all for now! Enjoy the weekend.

Keep an Attached Drive Active

I recently received two drives sent via FedEx for a rather large data copy. Maybe I haven’t been looking, but I’ve never seen anything like these drives before, although it wasn’t too difficult to believe they existed. They each hold 6TB and have a 10-key keypad on the drive case where you have to punch in a PIN to unlock the drive. Neat, except that the drives also have a timeout period in which they automatically lock. To unlock each drive, providing there’s been no disk activity, as that’s what starts the timeout counter, is a trip to the data center to enter the PIN again.

keep-an-attached-drive-active01

A coworker and I quickly arrived at the same idea in order to keep the drives active. I bet you just thought of an idea, too. It’s extremely simplistic, but that’s typically the road on which I travel. In the simple Do-While loop below, we created a file on each of the attached drives. In my example, the loop slept for eight minutes after it created the file. Then it removed the files and slept for another 10 seconds before repeating.

Do {
    New-Item -Path E:\keepalivefile.txt,F:\keepalivefile.txt -ItemType File | Out-Null
    Start-Sleep -Seconds 480 # equal to 8 minutes
    Remove-Item -Path E:\keepalivefile.txt,F:\keepalivefile.txt
    Start-Sleep -Seconds 10
}
While ($true)

That’s all I’ve got tonight, other than to say, I have no idea what I would’ve done if I didn’t know Windows PowerShell. Seriously, how would I have been able to guarantee the drives wouldn’t lock, besides to manually create the disk activity? Keeping File Explorer open wasn’t enough, I tried. PowerShell to the rescue. Again.

Proving PowerShell’s Usefulness to Newbies, Part I

Months ago, I started writing a list of ways to potentially impress PowerShell newbies for a presentation (I’ve yet to ever give). Since I’m not sure if I’ll be up in front of a crowd of PSNewbies any time soon, I figured I would share them here. Consider these when you need to impress the PowerShell non-believers.

Part I
The power in PowerShell has been said to be a number of different things, by a number of different people. In today’s topic, the power is speed and accuracy. We’re going to automate the creation of 10,000 directories (a.k.a. folders). That’s no small task if you’re doing it manually.

Beginning in the example below, we’ll start by creating a single directory to hold the other 10,000 directories, by running a New-Item command. Once that’s finished, which is practically instantaneous, we’ll run second command to create the 10,000 new folders. We’ll do this by using a range operator (..) and the numbers 1 and 10000, piping each of those numbers and the ones in between, to that second New-Item command.

Notice the $_ variable, as this has the tendency to cause some confusion. This variable holds the value of the current object that’s entered, or crossed, the pipeline — you pick your visual. In this case, it represents the current number from within our range of numbers. The first time this command runs, $_ will be set to 1, the second time this runs it will be set to 2, and the last time it runs, it will be set to 10000. I should note, that in PowerShell 3.0, the $PSItem variable was introduced. It can be used in place of $_ in version 3.0 and above.

PS> New-Item -Path C:\Testing -ItemType Directory

    Directory: C:\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----          1/6/2016   9:52 PM            Testing

PS> 1..10000 | ForEach-Object {New-Item -Path "C:\Testing\$_" -ItemType Directory}

    Directory: C:\Testing

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----          1/6/2016   9:52 PM            1
d----          1/6/2016   9:52 PM            2
d----          1/6/2016   9:52 PM            3
d----          1/6/2016   9:52 PM            4
d----          1/6/2016   9:52 PM            5
d----          1/6/2016   9:52 PM            6
d----          1/6/2016   9:52 PM            7
d----          1/6/2016   9:52 PM            8
d----          1/6/2016   9:52 PM            9
d----          1/6/2016   9:52 PM            10
...

I haven’t included all 10,000 results, for good reason, but as you can see, the moment the command was entered into the PowerShell host, it began to create the new folders. This would be the time at which you retie your shoes. The example further below indicates the command takes about 10 seconds to complete. Depending on your sneakers, if you’re wearing those, you might actually take longer. If you don’t have laces, take a drink of something, or simply sit there in amazement at all the work you’re not really doing. It might actually be too fast, once you’ve realized how much time you just freed up.

A little note about Measure-Command used below: Typically this cmdlet will internally measure things and not really do much that you can actually see. In this case, it’s actually going to create the folders as part of the measurement. To me, it makes sense that it wouldn’t be able to measure this unless it really creates the folders. On that note, if you ran the command above, you’ll want to delete the existing folders, if you want to measure how long it takes to create the folders. The New-Item cmdlet can’t create folders that already exist. To remove the directories, run:  Remove-Item -Path ‘C:\Testing\*’ from your PowerShell console.

PS> Measure-Command -Expression {1..10000 | ForEach-Object {New-Item -Path "C:\Testing\$_" -ItemType Directory}}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 10
Milliseconds      : 293
Ticks             : 102939103
TotalDays         : 0.000119142480324074
TotalHours        : 0.00285941952777778
TotalMinutes      : 0.171565171666667
TotalSeconds      : 10.2939103
TotalMilliseconds : 10293.9103

PS> Remove-Item -Path C:\Testing\*

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 9
Milliseconds      : 793
Ticks             : 97934962
TotalDays         : 0.000113350650462963
TotalHours        : 0.00272041561111111
TotalMinutes      : 0.163224936666667
TotalSeconds      : 9.7934962
TotalMilliseconds : 9793.4962

In the second command above, we actually measured the time it took to remove the directories we created — you saw that command a moment ago. It came in at a faster time than it took to create them, although this won’t always be the case. It’s still quite quick for either operation.

This is a great example of the power in PowerShell, but before I wrap up, let’s see how much time I just saved. Let’s assume it takes me 4 seconds to manually create a folder. To create 10,000 folders, I would need a free 40,000 seconds. To put that into hours, I would need over 11 of them to do this task by hand. We only get one person’s salary, but we should probably get a few.

PS> $SecondsToCreateFolder = 4
PS> $NumberOfFolderToCreate = 10000
PS> $NumberOfFolderToCreate * $SecondsToCreateFolder
40000
PS> $SecondsInMinutes = $MinutesInHours = 60
PS> $SecondsInMinutes
60
PS> $MinutesInHours
60
PS> ($NumberOfFolderToCreate * $SecondsToCreateFolder) / $SecondsInMinutes / $MinutesInHours
11.1111111111111

Thanks for reading this post.

Get All 13 Months in a Year

I started a little, pet project recently and it’s all based around how I store my pictures and video files. I have a base directory – C:\Users\tommymaynard\Documents\Media – that contains a subdirectory for each year: 2012, 2013, etc. Inside each of those, I have 12 other directories – one for each month. These each use the naming convention 01 – January, 02 – February, etc. Inside each of those directories, I have at least two other directories: pictures and videos. Here’s an image that may help this structure make more sense.

Get All 13 Months in a Year01

I don’t always sort my photos and videos right away. Instead, I’ll often procrastinate and just drop them into a ‘Pics to Sort’ folder on my desktop – that’s literally the directory’s name. I wondered if I would procrastinate any less, if I had Windows PowerShell build out the desired directory structure for me each year. As an aside, if you consider that I always add my pictures and videos to the same I’ll-sort-you-later directory, then I could easily build a solution to do the sorting, based on file extension and creation date, from this directory into the proper subdirectories in the media directory. I’ll save this one for another day, but thanks for thinking of it.

For this Quick Learn, let’s only concern ourselves with capturing the month’s names. While I could have created a hard-coded array of the month names, I decided to see what I could get return using Get-Date – not what I wanted. I could return the current month’s name using Get-Date -Format MMMM, or the current month’s numeric representation using Get-Date | Select-Object Month, but neither of these return all of the months. The system knows the names of the months and so I opted to look for a .NET way to get them.

So, here it is, the System.Globalization.DateTimeFormatInfo .NET class. When you enter this as the value of the New-Object’s -TypeName parameter, it will return a great deal of information, to include a property called MonthNames. In the example below, you can see the code used to store the month names in a variable. You would think I would be done here, but I wasn’t.

PS C:\> $MonthNames = (New-Object System.Globalization.DateTimeFormatInfo).MonthNames
PS C:\> $MonthNames
January
February
March
April
May
June
July
August
September
October
November
December

PS C:\>

Instead of creating directories, like my project does, the example below simply echos the month’s numeric value, a space-dash-space, and then the month’s name. I’ve added a for statement example as well, just in case someone were to wonder why I didn’t include one, since I was incrementing a counter variable and knew how many looping iterations I had to do.

PS C:\> $i = 1
PS C:\> $MonthNames | foreach {Write-Output "$i - $_";$i++}
1 - January
2 - February
3 - March
4 - April
5 - May
6 - June
7 - July
8 - August
9 - September
10 - October
11 - November
12 - December
13 -
PS C:\>
PS C:\> for ($i=1; $i -le $MonthNames.Count; $i++) {echo "$i - $($MonthNames[$i-1])"}
1 - January
2 - February
3 - March
4 - April
5 - May
6 - June
7 - July
8 - August
9 - September
10 - October
11 - November
12 - December
13 -
PS C:\>

Based on these results, the MonthNames property has a thirteenth entry, and that’s a problem, since there’s no thirteenth month. I proved to myself that there was a problem a couple different ways, as seen below. Remember that the first index, or element, of an array is index zero, making January $MonthNames[0] and December $MonthNames[11].

PS C:\> $MonthNames.Count
13
PS C:\> $MonthNames[0]
January
PS C:\> $MonthNames[11]
December
PS C:\> $MonthNames[12]

PS C:\> $MonthNames[13]
PS C:\>

I needed to ensure this extra, blank month wasn’t making its way into my code. While I could have done my filtering when I was actually creating new directories, it is a better practice to only store what I need, and to only store what’s correct. As can be seen below, I only returned twelve months by adding a pipeline and some filtering.

PS C:\> $MonthNames = (New-Object System.Globalization.DateTimeFormatInfo).MonthNames | Where-Object -FilterScript {$_ -notlike ''}
PS C:\> $MonthNames
January
February
March
April
May
June
July
August
September
October
November
December
PS C:\> $MonthNames.Count
12

Since I was already here, I checked out another property. DayNames didn’t have a blank entry, and had I needed to use it, I wouldn’t have had to do any filtering on the returned results – something I incorrectly assumed about MonthNames. Hope this is helpful to someone, and thank you for reading this post.

PS C:\> $DayNames = (New-Object System.Globalization.DateTimeFormatInfo).DayNames
PS C:\> $DayNames
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
PS C:\> $DayNames.Count
7
PS C:\>

about_Profiles

This post is the help rewrite for about_Profiles. While the help files for Windows PowerShell are invaluable, the idea behind a rewrite is so true beginners might even better understand the help file concepts. At times, some things discussed in the Windows PowerShell help file will not be included in a help rewrite. Therefore, it is always best to read the actual help file after reading this post. (PS3.0)

Once you start using your profile ($PROFILE), you’ll have a hard time not using it and not adding new things to it. When you have a profile (script), it runs each time you open a new Windows PowerShell session. My current profile does a number of things – it sets my location to the C:\ drive, sets various variables, set aliases, modifies the console’s window title, and creates several functions. Some of those functions allow me to connect remotely to Exchange servers, load the VMWare PowerCLI PSSnapin (without having to remember its name), use Wake-on-LAN to wake my home computer, and several others.

There are several different profiles based on the host and the user. To see your profile, type $PROFILE and press Enter in the console or Integrated-Scripting Environment (ISE). As seen in the example below, this will display the path to the profile. Line 1 is typed in the standard PowerShell console and Line 3 in the ISE.

PS C:\> $PROFILE
C:\Users\tommymaynard\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
PS C:\> $PROFILE
C:\Users\tommymaynard\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

There are more profiles than these two and they are active under different circumstances. To see all the profiles, pipe the $PROFILE variable to the Select-Object cmdlet with the wildcard character.

PS C:\> $PROFILE | Select-Object -Property *

AllUsersAllHosts       : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
AllUsersCurrentHost    : C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1
CurrentUserAllHosts    : C:\Users\tommymaynard\Documents\WindowsPowerShell\profile.ps1
CurrentUserCurrentHost : C:\Users\tommymaynard\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Length                 : 82

Based on the information on the left hand side, there are different profiles based on who is using what host. While it’s not recommended to modify the profiles in the System32 directory, you should be able to tell what these do. The one on line1 is run for any user, regardless of what host (console/ISE) they use. The second one on line 2 is for any user in the current host. The third is for the current user, me, in all the hosts, and the final one is for me in the current host. These last two are the one’s you can modify.

But just by having a path stored in $PROFILE, doesn’t actually mean the file, or profile, actually exists. Use the Test-Path cmdlet to determine if the file/profile exists.

PS C:\> Test-Path $PROFILE
False

If this returns False, then you do not have a profile and so it will need to be created. You can create this file but using the New-Item cmdlet.

PS C:\> New-Item -Type File -Path $PROFILE -Force

    Directory: C:\Users\tommymaynard\Documents\WindowsPowerShell

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         8/20/2014  12:39 PM          0 Microsoft.PowerShell_profile.ps1

These two commands can be put together in an If-Else statement that will test for the file, and if not found, will create the file. Once you have a profile file created, you can open it up and start adding to it. Remember that every time you open the matching console, the profile script will run.

If (-not(Test-Path $PROFILE)) {
    New-Item -Type File -Path $PROFILE -Force
}

Here’s some quick examples of things that could be added to a profile. The first example  changes the prompt location from its default to the root of the C:\ drive.

Set-Location \

The next example sets aliases for c and gh. The first example, in line 1, will allow me to use the letter c to run the Clear-Host cmdlet and in line 2, will allow me to use the alias gh in place of typing out Get-Help.

Set-Alias -Name c -Value Clear-Host
Set-Alias -Name gh -Value Get-Help

These next example allow me to set variables inside my profile. This will allow me to use $DCs to return DC01, DC02, DC03, allow me to use $hosts to return the path of my hosts file, and allow me to return all my web and data servers by using the $AppServers variable. Noticed that $AppSevers is a mulit-dimentional array. Use $AppServers[0] to return the web servers and $AppServers[1] to return the data servers.

Set-Variable -Name DCs -Value 'DC01','DC02','DC03'
Set-Variable -Name hosts -Value "$env:SystemRoot\System32\drivers\etc\hosts"
Set-Variable -Name AppServers -Value @(('web01','web02','web03'),('data01','data02','data03'))

You can also create functions. This function allows me to type Add-VMC to load the VMware PSSnapin. For me, it’s easier to remember this short function name than remembering the PSSnapin name or having to type out Get-PSSnapin -Registered to find the name.

Function Add-VMC {
	Add-PSSnapin VMware.VimAutomation.Core
}

Start using your $PROFILE today and everything you can to help personalize your PowerShell experience. Keep in mind that profiles do not exist in remote sessions.

Learn More

This information, and more, is stored in the help file about_Profile that comes with Windows PowerShell. This information can be read by typing any of the commands below. The first example will display the help file in the Windows PowerShell console, the second example will open the full help in it’s own window, the third example will send the contents of the help file to the clipboard (so it can be pasted into Word, Notepad, etc.), and the fourth example will open the help file in Notepad.

PS C:\> Get-Help about_variables
PS C:\> Get-Help about_variables -ShowWindow
PS C:\> Get-Help about_variables| clip
PS C:\> Notepad $PSHOME\en-us\about_Variables.help.txt

Using Replace() to Fix Split() (and Convert-Path)

I was working on a recent project that required scripting ACLs, and so I had a Windows PowerShell console open in addition to the ISE. This allowed me to quickly check the owner of a directory (or folder). I could press the up arrow to rerun my command, and I could quickly see if the owner had changed according to my script. Let’s say my directory is called ‘TestFolder’ and is located at the root of the C:\ drive.

PS C:\> New-Item -Path TestFolder -ItemType Directory

    Directory: C:\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        10/21/2014   9:19 PM            TestFolder

To get the ACL information for the folder, you can use the Get-Acl cmdlet, as in the example below.

PS C:\> Get-Acl -Path .\TestFolder

    Directory: C:\

Path                                    Owner                                   Access
----                                    -----                                   ------
TestFolder                              BUILTIN\Administrators                  BUILTIN\Administrators Allow  FullCo...

Being the PowerShell enthusiast that I am, I modified my command so that only the information I wanted (the path and the owner) was being returned. This is done using the Select-Object cmdlet. Unfortunately, when the command returned those two properties, the Path property was no longer what I was expecting – take a look below. While the example above only returned the name of the folder (TestFolder), I thought I would change this to show the full path (C:\TestFolder) since I was now dealing with a string that included it.

PS C:\> Get-Acl -Path .\TestFolder | Select-Object -Property Path,Owner

Path                                                        Owner
----                                                        -----
Microsoft.PowerShell.Core\FileSystem::C:\TestFolder         BUILTIN\Administrators

The first thing I thought to do was to split the path at the two colons (::) and grab the second element, which I thought would end up being C:\TestFolder. The split method didn’t work so well; here’s what I ended up with.

PS C:\> Get-Acl -Path .\TestFolder | Select-Object -Property @{N='Path';E={($PSItem.Path).Split('::')[-1]}},Owner

Path                                                        Owner
----                                                        -----
\TestFolder                                                 BUILTIN\Administrators

The reason this didn’t work is because the Split() method doesn’t split on each occurrence of two, back-to-back colons like you might expect, it splits on every colon. Since C:\ has a colon, it split there as well. FYI: The use of [-1] returns the last element in an array – good to know, I know. Here’s an example that may help better explain. In this example below, the string is split on every exclamation point (!) and every question mark (?) – not only on the combination of both (!?).

PS C:\> $String = 'Today is the 21st! That is great news, right?'
PS C:\> $String
Today is the 21st! That is great news, right?
PS C:\> $String.Split('!?')
Today is the 21st
 That is great news, right

PS C:\>

What I then decided to do to get this the way I wanted it, was to first replace the two, back-to-back colons with a single character (that was not a part of the string), and then split on that single character. It worked, and here’s what that looks like.

PS C:\> Get-Acl -Path .\TestFolder | Select-Object -Property @{N='Path';E={(($PSItem.Path).Replace('::','@')).Split('@')[-1]}},Owner

Path                                                        Owner
----                                                        -----
C:\TestFolder                                               BUILTIN\Administrators

PS C:\>

It was about this point, that I wanted to see if the -split operator would have handled this the same way and required the additional work that the Replace()/Split() methods did. Of course, after all I did to get this to work how I wanted, I determined I should have started with the -split operator. The -split operator isn’t looking at the characters individually, but instead of, as a whole – two, back-to-back colons is two back-to-back colons.

PS C:\> Get-Acl -Path .\TestFolder | Select-Object -Property @{N='Path';E={(($PSItem.Path) -split '::')[-1]}},Owner

Path                                                        Owner
----                                                        -----
C:\TestFolder                                               BUILTIN\Administrators

A note, if the @{N=…;E={…}} syntax is confusing, or new to you, then spend some time reading this: http://technet.microsoft.com/en-us/library/ff730948.aspx, and then run Get-Help about_Hash_Tables.

This happens just about every time I get to ready to publish a new post. I discovered a better way to handle the problem – much like I did when I considered the -split operator.  It turns out that I could have used a built-in cmdlet to convert the path for me. That’s right, there’s a cmdlet that would have handled everything. Using the Convert-Path cmdlet will convert something like this: Microsoft.PowerShell.Core\FileSystem::C:\TestFolder to this: C:\TestFolder. Here’s the example.

PS C:\> Get-Acl -Path .\TestFolder | Select-Object -Property @{N='Path';E={Convert-Path $PSItem.Path}},Owner

Path                                                        Owner
----                                                        -----
C:\TestFolder                                               BUILTIN\Administrators

PS C:\>

Well, that’s it for this one. As much as I might seem irritated about how I did this three different ways – from the most work to the least – I understand how important this learning process is, and that one day I will be grateful for having gone down this path… (pun intended).