Posts Tagged ‘Tips’
What Scope Am I In?
In PowerShell the question of scope is too complicated and convoluted. I’m going to try to help you understand it, but I’m not guaranteeing that I will be able to make it seem any simpler than it actually is. Hopefully, I won’t make it more complicated than it inherently is
In PowerShell you always have three named variable scopes: script, local and global. The default scope is always the same as the local scope, so when you set a variable without specifying the scope, it’s always set at local scope. One thing to note is that you can access these named scopes through the $variable notation, or through the variable drive, so all of the following are equivalent:
Set-Variable var "one" -Scope Local
$var = "one"
$local:var = "one"
Set-Content Variable::Local:Var "one"
A side note: the PSProvider drive notation means that when you’re in strict mode, if you want to test for the existence of a variable without causing an error, the simplest way to do it is with Test-Path Variable:Var…
What’s so hard about that?
Well, the question is: what scope are you in “right now” when a line of code is executing from a function or a script …
Sometimes local scope is ALSO script scope, and sometimes, script scope is also global scope. Specifically: when you’re typing at the console, all three scopes are the same.
Let’s write a function to determine what named scope we’re in:
By setting a variable, and then testing the named scopes, we can verify what scope we were in when we set the variable. Of course, there’s no point testing the Local scope, because we already know that is where we are… then we return a hashtable of booleans indicating which scopes are active.
If you dot-source that Get-Scope function, you’ll find the scope that you’re in where you dot-source it:
- if you do it at the interactive prompt it should tell you all three scopes are set
- if you do it in a script file it should tell you Local and Script
- but if you do it in a function, it will always just tell you “local” — and will not tell you if the function is in a script or not … nor how deep you are.
- and if you do it in a module, the results will depend on whether Find-Scope is defined in the module or not (this is very weird)
So are we done?
Not even remotely. On top of the named scopes, PowerShell also has nested scopes. Each script, function, scriptblock, etc. adds to the nested scopes, and takes you further from the global scope. On top of that, PowerShell has Modules. In a module, scope is flattened. Specifically, in a module, the default scope becomes the Script scope, which in this case is not actually reserved for a single file, but for any scripts, functions, etc that are executed from within that module’s context.
To determine nesting level of the scope, we must do something like this:
function Get-ScopeDepth {
trap { continue }
$depth = 0
do {
Set-Variable scope_test -Scope (++$depth)
} while($?)
return $depth - 1
}
# Test it like this:
. Get-ScopeDepth
&{ . Get-ScopeDepth }
&{ &{ . Get-ScopeDepth } }
As long as modules aren’t involved, that will tell you how many scopes there are between you and global scope (and thus, return zero when dot-source from the console commandline).
This falls apart a bit if you’re in a module (in a module, you can’t get to global scope by increasing the scope value — effectively, the highest you can go is script scope, but in reality you can still access global scope by naming it). To determine if you’re in a module, you can simply check for the existence of the $PSScriptRoot variable, or verify that $Invocation.MyCommand.Module is set to something.
Additionally, if you’re in a module, you need to define this function in that module for it to work at all.
There’s one more thing you could use to help you learn what scope you’re in, and that is the Get-PSCallStack cmdlet. This will tell you how many commands have been called to get you where you are. It’s usually the same as the Scope Depth, but not when it’s in a script file, etc.
Here’s my finished scope digging function:
function Get-Scope {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[System.Management.Automation.InvocationInfo]$Invocation
)
function Get-ScopeDepth {
trap { continue }
$depth = 0
do {
Set-Variable scope_test -Scope (++$depth)
} while($?)
return $depth - 1
}
$depth = Get-ScopeDepth
Remove-Variable scope_test
New-Variable scope_test
New-Object PSObject @{
ModuleScope = [bool]$Invocation.MyCommand.Module
GlobalScope = [bool](Get-Variable scope_test -Scope global -ea 0)
ScriptScope = [bool](Get-Variable scope_test -Scope script -ea 0)
ScopeDepth = $depth
PipelinePosition = $Invocation.PipelinePosition
PipelineLength = $Invocation.PipelineLength
CallStack = Get-PSCallStack
StackDepth = (Get-PSCallStack).Count - 1
Invocation = $Invocation
}
}
- Remember: modules sometimes flatten scope.
- Remember: when calling this function you should dot-source it, and pass it $MyInvocation
As as side note and counter-example, take for instance this module:
All three of those functions will return ScopeDepth = 2 (the test-scope function, and the module itself), but the StackDepth will increase correctly. I don’t know why. It’s late, so I’m going to stop writing before I get more confusing.
Be a responsible geek – encrypt your email (free)
Everyone should encrypt their emails … especially geeks, who can be expected to understand how little effort it would take for a rogue sysadmin or clever hacker to sniff your email on it’s way to it’s intended destination.
Incidentally, if you’re a geek and you don’t know that, you should try running WireShark while you download and send emails…
Anyway. The point of this email is to point out that Comodo (one of the biggest SSL Certificate vendors, and one who’s trust certificates are pre-installed on Windows) is giving away free secure email certificates which you can use in Outlook, Thunderbird, or whatever your favorite email client is. They’re actually on the recommendation list from Microsoft, but inexplicably listed under “other” office versions (they work fine in Outlook 2007, just to be clear).
All you need to do now is run off and sign up and then tell all your friends and family to do the same thing.
PowerShell PowerUser Tips: List the Cmdlets in an Assembly
Tiny script… let me know if you know a better way.
function Get-Cmdlets {
param([System.Reflection.Assembly]$assembly)
$assembly.GetTypes() | Where-Object {
$_.GetCustomAttributes([System.Management.Automation.CmdletAttribute],$false)
} | ForEach-Object {
$type = $_
$_.GetCustomAttributes([System.Management.Automation.CmdletAttribute],$false)
} | Select VerbName, NounName, @{n="Type";e={$type}} |
}
## Example usage.
## You can use the [System.Reflection.Assembly]::Load... methods to get an assembly
## But for an example, use the "CallingAssembly" (System.Management.Automation )
Get-Cmdlets ([System.Reflection.Assembly]::GetCallingAssembly()) |
Sort VerbName, NounName | Format-Table -auto
PowerShell Power User Tips: A Better Prompt
For this edition of my Power User tips for PowerShell, I’m going to share my (heavily annotated) prompt function. Feel free to to copy useful pieces or just place the whole thing in your profile script
I’m not going to say anything more, I’ll let the comments speak for themselves.
Edit: Someone just pointed out that I forgot the bit of my prompt that sets my current path into the window title, and I realized I also forgot the bit that puts (Admin) in the title if you’re running “elevated” on Vista.
Edit: Ok, how many people noticed that I incorrectly used the Environement.CurrentDirectory when I set the WindowTitle (meaning it would only work right in FileSystem drives)? Fixed now.
# Set-Prompt.ps1 (Dot-Source from your profile)
###################################################
# This should go OUTSIDE the prompt function, it doesn't need re-evaluation
# We're going to calculate a prefix for the window title
# Our basic title is "PoSh - C:\Your\Path\Here" showing the current path
if(!$global:WindowTitlePrefix) {
# But if you're running "elevated" on vista, we want to show that ...
if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista and ...
new-object Security.Principal.WindowsPrincipal (
[Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) )
{
$global:WindowTitlePrefix = "PoSh (ADMIN)"
} else {
$global:WindowTitlePrefix = "PoSh"
}
}
function prompt {
# FIRST, make a note if there was an error in the previous command
$err = !$?
# Make sure Windows and .Net know where we are (they can only handle the FileSystem)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
# Also, put the path in the title ... (don't restrict this to the FileSystem
$Host.UI.RawUI.WindowTitle = "{0} - {1} ({2})" -f $global:WindowTitlePrefix,$pwd.Path,$pwd.Provider.Name
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# my New-Script and Get-PerformanceHistory functions use history IDs
# So, put the ID of the command in, so we can get/invoke-history easier
# eg: "r 4" will re-run the command that has [4]: in the prompt
$nextCommandId = (Get-History -count 1).Id + 1
# Output prompt string
# If there's an error, set the prompt foreground to "Red", otherwise, "Yellow"
if($err) { $fg = "Red" } else { $fg = "Yellow" }
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "[${Nesting}${nextCommandId}${Stack}]:" -NoNewLine -Fore $fg
return " "
}
PowerShell Power User Tips: Bash-style “alias” command.
I keep hearing from new users who are used to bash-style aliases, how frustrating it is not to be able to create aliases with parameters, the way you can in bash …
I’m going to show you how to make the “alias” command work roughly the way it does in bash, but first, let me clear this up:
| Bash or Csh | PowerShell |
|---|---|
| script | script |
| alias, shell functions | function |
| ... | alias |
In Bash, the recommendation is that “for almost every purpose, shell functions are preferred over aliases” ... and that recommendation is even stronger for PowerShell. The PowerShell “alias” is a true alias — it’s just another name for a command, script, function, etc. and it doesn’t support passing parameters or making mini-scripts at all.
Usually, an alias serves to give you a name you can remember, but sometimes it’s just to shorten the name, . Another use for them is to let you specify the default cmdlet — if you have two cmdlets (or script functions) with the same name, you can use an alias to override which one is executed by default.
The PowerShell function can do everything a bash alias can do (and everything a function or script can do, but this isn’t a tip about that, it’s a tip about making an alias
and unalias command that works the way you expect it to). So …
## Aliases.ps1 -- to be dot-sourced from your profile
if($Host.Version.Major -ge 2) {
function script:Resolve-Aliases
{
param($line)
[System.Management.Automation.PSParser]::Tokenize($line,[ref]$null) | % {
if($_.Type -eq "Command") {
$cmd = @(which $_.Content)[0]
if($cmd.CommandType -eq "Alias") {
$line = $line.Remove( $_.StartColumn -1, $_.Length ).Insert( $_.StartColumn -1, $cmd.Definition )
}
}
}
$line
}
}
function alias {
# pull together all the args and then split on =
$alias,$cmd = [string]::join(" ",$args).split("=",2) | % { $_.trim()}
if($Host.Version.Major -ge 2) {
$cmd = Resolve-Aliases $cmd
}
New-Item -Path function: -Name "Global:Alias$Alias" -Options "AllScope" -Value @"
Invoke-Expression '$cmd `$args'
###ALIAS###
"@
Set-Alias -Name $Alias -Value "Alias$Alias" -Description "A UNIX-style alias using functions" -Option "AllScope" -scope Global -passThru
}
function unalias([string]$Alias,[switch]$Force){
if( (Get-Alias $Alias).Description -eq "A UNIX-style alias using functions" ) {
Remove-Item "function:Alias$Alias" -Force:$Force
Remove-Item "alias:$alias" -Force:$Force
if($?) {
"Removed alias '$Alias' and accompanying function"
}
} else {
Remove-Item "alias:$alias" -Force:$Force
if($?) {
"Removed alias '$Alias'"
}
}
}
You can save that as alias.ps1 and create your aliases the way you used to in bash alias ls='ls -recurse' and still be able to invoke them and, you can pass them extra parameters somewhat like in csh when you invoke them.
I’ve added some extra text in the function name and content and in the alias description, so it’s actually pretty easy to find all the aliases and functions this script creates and dump them to a file so you can reload them later if you want … but I haven’t actually written a function to do that yet myself.
One important note: You must not use recursive aliases in the bindings on v1 — that is, alias ls='ls -recurse' will loop until it hits PowerShell’s recursive limit (only 100) and exit if you try to use it on v1 — because the script won’t be able to resolve the alias “ls” to Get-ChildItem … you’re probably better off not relying on that feature anyway.
PowerShell Power User Tips: Current Directory
This is the second in an occasional series of tips for PowerShell users: short posts which don’t intend to give guidance, but merely a tip on a feature you may not be aware of, or maybe even answers to some of the recurring questions that come up in #PowerShell.
Fixing the “Current Directory” problem
The core of this tip is very simple: Windows tracks your application’s “current directory” ... and you can get and set this location using static methods of the System.IO.Directory class: SetCurrentDirectory and GetCurrentDirectory.
The reason this is showing up as a Power User Tip is that PowerShell doesn’t set this environment setting when you navigate — it uses it’s internal “PSProvider” architecture, and doesn’t differentiate between whether you’re in a FileSystem location or a registry location, or even a third-party provider. So, it never actually changes the current directory, and any console command or .net method you call which uses the current directory will most likely be in the wrong place — like, for instance:
$sw = New-Object System.IO.StreamWriter("NeatFile.txt")
$sw.writeline("I could write a lot of neat stuff here!")
$sw.close()
The problem is that now you don’t know where “NeatFile.txt” is — the “current directory” depends on how you launched PowerShell — most frequently it’s your $Home directory (equivalent to Env:HOMEDRIVE + Env:HOMEPATH — usually something like C:\Documents and Settings\YourName), but it could be your SystemRoot (C:\Windows) or the current directory of the app that launched PowerShell (eg: C:\Windows\System32 when you run it via “runas”). You can figure it out by running: [IO.Directory]::GetCurrentDirectory().
But here’s something more interesting: you can “fix” the problem by using [IO.Directory]::SetCurrentDirectory. There are a couple of catches, however: You can’t just use $pwd or Get-Location because you might be in the registry or some other location that’s not a Directory. And you can’t just use Get-Location -PSProvider FileSystem because even though it returns the current FileSystem provider path, the FileSystem provider supports “fake” PSDrives (eg: you could create a Scripts: drive like new-psdrive scripts filesystem "$Home\Scripts") and these aren’t actually supported by the .Net FileSystem. Luckily, PowerShell includes a Convert-Path cmdlet which was created for this very purpose: converting a path from a Windows PowerShell path to a native path supported by the underlying provider.
Without further ado, here’s a one-liner you can add to your prompt function:
[IO.Directory]::SetCurrentDirectory((Convert-Path (Get-Location -PSProvider FileSystem)))
Edit: You can do the same thing using the System.Environment class, and it turns out that the ProviderPath is a property of the PathInfo object, perhaps you’ll find this syntax simpler:
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
PowerShell Power User Tips: Get-Command precedence
This is the first in what I hope will be an occasional series of tips for PowerShell users: short posts which don’t intend to give guidance, but merely a tip on a feature you may not be aware of, or maybe even answers to some of the recurring questions that come up in #PowerShell. We’ll see how this goes …
My first tip to power users is to remember the priority which PowerShell assigns to things by default:
- Alias
- Function (and Filter)
- Cmdlet
- ExternalScript
- Application
- Files with associations
This means that using an Alias, you can override anything (and since you can’t have multiple aliases with the same name, that makes aliases the ultimate way to disambiguate commands).
Functions and filters (there’s really no such thing as a filter) come before cmdlets (yes, even built-in cmdlets) and scripts (that is, your .ps1 files which are in your path, and are called “ExternalScripts” by PowerShell) come before applications, which come before scripts written in other languages, like .vbs or .bat or .cmd (even though they’re all shown as “Application” type commands, PowerShell prioritizes apps over executable scripts which are associated with an engine).
Incidentally, I’m not actually sure what a “Script” is (it’s a CommandType for Get-Command, but there aren’t any on my PCs) if anyone can run get-command -type "Script" and get something output, please let me know what it was.
It’s important to understand that this precedence order is not what you get if you run Get-Command (Get-Command merely orders everything alphabetically by name). In fact, as far as I know, PowerShell doesn’t give you a way to get a list of commands in the order that they would execute, nor does it specify any way of determining that order in the documentation. If you would like to see the proper order, you could use the following “filter” function, and sort by Order bearing in mind that it really only works precisely when you type the full command without wildcards.
filter which {
$_.Order = "luimcxp".IndexOf( $($_.CommandType)[1] )
$_
}
# So then you can pipe through which, and sort by order:
Get-Command SomeCommand | which | sort order
Oh, by the way, in case it’s not obvious … “luimcxp” is the second letter of each “CommandType” (which is unique in each one) in the order that I think they belong in … so IndexOf( $($_.CommandType)[1] ) gives us the correct ordering for the command in $_.