Jonathan
Jonathan

Reputation: 2845

Meaning of Powershell statement

I am completely new to Powershell and I am trying to understand what this fragment of code does:

$OwnFunctionsDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Functions"
Write-Host "Loading own PowerShell functions from:" -ForegroundColor Green
Write-Host "$OwnFunctionsDir" -ForegroundColor Yellow
Get-ChildItem "$OwnFunctionsDir\*.ps1" | %{.$_}
Write-Host ''

In particular I cannot interpret what the line Get-Children … does. This code is intended to be added to your Powershell profile to load commonly used functions at Powershell startup.

Upvotes: 0

Views: 127

Answers (1)

Jason Boyd
Jason Boyd

Reputation: 7029

Short Answer

This command loads the contents of all ".ps1" files in "<yourHomeDirecotry>\Documents\WindowsPowerShell\Functions" into your working session.

Long Answer

First, $env:USERPROFILE is an environment variable that corresponds to your home directory. So in my case it is "c:\users\jboyd"

The first interesting bit of code is:

$OwnFunctionsDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Functions"

This assigns a string to a new variable named OwnFunctionsDir. What's interesting about this string is that it is double quoted and it contains the variable $env:USERPROFILE. PowerShell expands variables in double quoted strings (this is not the case for single quoted strings). So if this were running on my machine the value of $OwnFunctionsDir would be "c:\users\jboyd\Documents\WindowsPowerShell\Functions".

Skipping the Write-host functions (because I think they are pretty self explanatory) takes us to:

Get-ChildItem "$OwnFunctionsDir\*.ps1" | %{.$_}

Get-ChildItem is interesting because its behavior depends on the PowerShell provider (don't worry about what that is) but in this case Get-ChildItem is the equivalent of dir or ls. $OwnFunctionsDir\*.ps1 is the path being enumerated. Using my machine as an example, this is equivalent to listing all files with names matching the wildcard pattern "*.ps1" (essentially all PowerShell files) in the directory "c:\users\jboyd\Documents\WindowsPowerShell\Functions".

The | character pipes the results of the command on the left to the command on the right.

The % character is an alias for the ForEach-Object command. The left and right curly braces are a scriptblock, this is the body of the foreach command. So each item from Get-ChildItem is piped into the scriptblock.

In the scriptblock of the ForEach-Object command the $_ variable represents the current item being processed. In this case $_ will be a PowerShell file with an extension ".ps1". When we invoke a PowerShell file with a period in front of it that is called dot sourcing. Dot sourcing loads the content of a file into your working session. So any variables or functions in the file are loaded.

Upvotes: 2

Related Questions