Dotnet Cookbook
Dotnet Cookbook
PS> [System.Guid]::NewGuid().Guid
7cb953d9-c906-46e8-86e8-666a717e7bed
In this example, [System.Guid] is the .NET type you are using. .NET types are enclosed in brackets. NewGuid() is the method you
are running. The method returns an object with a property called Guid:
PS> [System.Guid]::NewGuid()
Guid
---cd87da91-9b4f-4c24-a18c-8acee41e3f3f
To get just the GUID number, the example accesses this property directly.
In this issue, we will present you a mixture of examples that all use static members. These examples cover only a fraction of useful
.NET types but will give you a good understanding on how this technique works. Use it as a starting point to explore the other static
members in the types.
2. Getting Documentation
.NET types that are part of the Microsoft .NET Framework come with excellent documentation. If you wanted to know more about the
type System.GUID, simply navigate to your favorite Internet search engine, and enter the type name as search phrase.
When you add the additional search phrase PowerShell, you will quickly find a vast number of articles on how others used the .NET
type.
From the list, you can see that the type has a property called UtcNow. So if youd like to know the current UTC time, run this:
PS> [DateTime]::UtcNow
Monday, December 16, 2013 13:54:10
Likewise, you can use any of the methods (which always are followed by braces including the method arguments). For example, to
convert ticks (the smallest time unit in Windows systems) to a real DateTime object, do this:
PS> [DateTime]::FromBinary(623577621536757899)
Saturday, January 15, 1977 08:35:53
4. Converting Types
You can easily convert types if you know the target type name. So if you wanted to convert a double number into an integer number,
stripping the decimals and rounding the number, here is the solution:
PS> [Int]7.68
8
PS> [System.Version]3.2.12.9
Major
----3
Minor
----2
Build
----12
Revision
-------9
User
---tobias.weltner
Host
---email.de
Address
[email protected]
PS> [System.Net.Mail.MailAddress][email protected]
DisplayName
-----------
User
---tobias.weltner
Host
---email.de
Address
[email protected]
PS> ([System.Net.Mail.MailAddress][email protected]).Host
email.de
Author Bio
Tobias Weltner is a long-term Microsoft PowerShell MVP, located in Germany. Weltner offers entry-level and advanced PowerShell
classes throughout Europe, targeting mid- to large-sized enterprises. He just organized the first German PowerShell Community
conference which was a great success and will be repeated next year (more on www.pscommunity.de).. His latest 950-page
PowerShell 3.0 Workshop was recently released by Microsoft Press.
To find out more about public and in-house training, get in touch with him at [email protected].
5. Turning On Standby-Mode
To programmatically enter standby mode, you can use native .NET code like this:
function Invoke-Standby
{
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::SetSuspendState(0,0,0) | Out-Null
}
Powershell Plus
However, this returns a culture-neutral list which is not returning the day in a localized (regional) form. To get the localized names, use
this line instead:
0..6 | ForEach-Object { [Globalization.DatetimeFormatInfo]::CurrentInfo.DayNames[$_] }
To get month names, try this:
0..11 | ForEach-Object { [Globalization.DatetimeFormatInfo]::CurrentInfo.MonthNames[$_] }
14. Get-Clipboard
If your PowerShell host uses the STA mode (which is default for PowerShell 3.0 and better), you can easily read clipboard
content like this:
function Get-Clipboard {
if ($Host.Runspace.ApartmentState -eq STA) {
Add-Type -Assembly PresentationCore
[Windows.Clipboard]::GetText()
} else {
Write-Warning (Run {0} with the -STA parameter to use this function -f $Host.Name)
}
}
15. Set-Clipboard
If you are using Windows Vista or better, you can pipe text to clip.exe to copy it to your clipboard:
Dir $env:windir | clip
Here is yet another approach that you can use if your PowerShell host uses the STA mode:
function Set-Clipboard {
param( $text )
if ($Host.Runspace.ApartmentState -eq STA) {
Add-Type -Assembly PresentationCore
[Windows.Clipboard]::SetText($text)
} else {
Write-Warning (Run {0} with the -STA parameter to use this function -f $Host.Name)
}
}
Set-Clipboard Hello World
PS> [TimeSpan]100
Days
Hours
Minutes
Seconds
Milliseconds
Ticks
TotalDays
TotalHours
TotalMinutes
TotalSeconds
TotalMilliseconds
:
:
:
:
:
:
:
:
:
:
:
0
0
0
0
0
100
1,15740740740741E-10
2,77777777777778E-09
1,66666666666667E-07
1E-05
0,01
This will get you a time span of 100 ticks, which is the smallest unit available to measure time. As PowerShell does support some
hidden shortcuts for other units, this will create a time span of exactly five days:
PS> [TimeSpan]5d
Days
Hours
Minutes
Seconds
Milliseconds
Ticks
TotalDays
TotalHours
TotalMinutes
TotalSeconds
TotalMilliseconds
:
:
:
:
:
:
:
:
:
:
:
5
0
0
0
0
4320000000000
5
120
7200
432000
432000000
Split expects a regular expression and fails when you use special characters like \. To translate a plain text into an escaped regular
expression text, try this:
[Regex]::Escape(\)
As you see, \ is the RegEx escape character and therefore needs to be escaped:
c:\test\subfolder\file -split \\
(c:\test\subfolder\file -split \\)[-1]
PS> [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
S-1-5-21-2649034417-1209187175-3910605729-1000
In fact, the method returns a wealth of additional information about your current access token:
PS> [Security.Principal.WindowsIdentity]::GetCurrent()
AuthenticationType
ImpersonationLevel
IsAuthenticated
IsGuest
IsSystem
IsAnonymous
Name
Owner
User
Groups
:
:
:
:
:
:
:
:
:
:
Token
UserClaims
:
:
DeviceClaims
Claims
:
:
NTLM
None
True
False
False
False
TobiasAir1\Tobias
S-1-5-21-2649034417-1209187175-3910605729-1000
S-1-5-21-2649034417-1209187175-3910605729-1000
{S-1-5-21-2649034417-1209187175-3910605729-513, S-1-1-0, S-1-5-32-545,
S-1-5-4...}
2276
{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name:
TobiasAir1\Tobias,
http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid:
S-1-5-21-2649034417-1209187175-3910605729-1000,
http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid:
S-1-5-21-2649034417-1209187175-3910605729-513,
http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid:
S-1-5-21-2649034417-1209187175-3910605729-513...}
{}
{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name:
TobiasAir1\Tobias,
http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid:
S-1-5-21-2649034417-1209187175-3910605729-1000,
http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid:
S-1-5-21-2649034417-1209187175-3910605729-513,
http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid:
S-1-5-21-2649034417-1209187175-3910605729-513...}
Actor
BootstrapContext
Label
NameClaimType
RoleClaimType
:
:
:
: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
: http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid
To change values, use SetEnvironmentVariable(). Note that you need full admin privileges to change machine-level environment
variables because they affect all users.
[Environment]::SetEnvironmentVariable(Launched, $true, User)
[Environment]::SetEnvironmentVariable(Note, SomeContent, User)
Note: Changes you make to user-level and machine-level environment variables are visible in the env: drive only after you restart
PowerShell. When PowerShell starts, it receives a copy of all environment variables, and this copy is not updated.
To delete an environment variable, set it back to an empty text:
[Environment]::SetEnvironmentVariable(Installed, , User)
[Environment]::SetEnvironmentVariable(Note, , User)
# MUST EXIST!