JETZT ONLINE BESTELLEN
First Edition Juni 2008
ISBN 978-0-596-52178-3
174 Seiten
EUR10.50
Weitere Informationen zu diesem Buch
Inhaltsverzeichnis | Index | Probekapitel |
Inhaltsverzeichnis
- Chapter 1: A Whirlwind Tour of Windows PowerShell
- InhaltsvorschauWhen learning a new technology, it is natural to feel bewildered at first by all the unfamiliar features and functionality. This perhaps rings especially true for users new to Windows PowerShell, because it may be their first experience with a fully featured command-line shell. Or worse, they've heard stories of PowerShell's fantastic integrated scripting capabilities and fear being forced into a world of programming that they've actively avoided until now.Fortunately, these fears are entirely misguided: PowerShell is a shell that both grows with you and grows on you. Let's take a tour to see what it is capable of:
- PowerShell works with standard Windows commands and applications. You don't have to throw away what you already know and use.
- PowerShell introduces a powerful new type of command. PowerShell commands (called cmdlets) share a common Verb-Noun syntax and offer many usability improvements over standard commands.
- PowerShell understands objects. Working directly with richly structured objects makes working with (and combining) PowerShell commands immensely easier than working in the plain-text world of traditional shells.
- PowerShell caters to administrators. Even with all its advances, PowerShell focuses strongly on its use as an interactive shell, and the experience of entering commands in a running PowerShell application.
- PowerShell supports discovery. Using three simple commands, you can learn and discover almost anything PowerShell has to offer.
- PowerShell enables ubiquitous scripting. With a fully fledged scripting language that works directly from the command line, PowerShell lets you automate tasks with ease.
- PowerShell bridges many technologies. By letting you work with .NET, COM, WMI, XML, and Active Directory, PowerShell makes working with these previously isolated technologies easier than ever before.
- PowerShell simplifies management of data stores. Through its provider model, PowerShell lets you manage data stores using the same techniques you already use to manage files and folders.
We'll explore each of these attributes in this introductory tour of PowerShell.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Introduction
- InhaltsvorschauWhen learning a new technology, it is natural to feel bewildered at first by all the unfamiliar features and functionality. This perhaps rings especially true for users new to Windows PowerShell, because it may be their first experience with a fully featured command-line shell. Or worse, they've heard stories of PowerShell's fantastic integrated scripting capabilities and fear being forced into a world of programming that they've actively avoided until now.Fortunately, these fears are entirely misguided: PowerShell is a shell that both grows with you and grows on you. Let's take a tour to see what it is capable of:
- PowerShell works with standard Windows commands and applications. You don't have to throw away what you already know and use.
- PowerShell introduces a powerful new type of command. PowerShell commands (called cmdlets) share a common Verb-Noun syntax and offer many usability improvements over standard commands.
- PowerShell understands objects. Working directly with richly structured objects makes working with (and combining) PowerShell commands immensely easier than working in the plain-text world of traditional shells.
- PowerShell caters to administrators. Even with all its advances, PowerShell focuses strongly on its use as an interactive shell, and the experience of entering commands in a running PowerShell application.
- PowerShell supports discovery. Using three simple commands, you can learn and discover almost anything PowerShell has to offer.
- PowerShell enables ubiquitous scripting. With a fully fledged scripting language that works directly from the command line, PowerShell lets you automate tasks with ease.
- PowerShell bridges many technologies. By letting you work with .NET, COM, WMI, XML, and Active Directory, PowerShell makes working with these previously isolated technologies easier than ever before.
- PowerShell simplifies management of data stores. Through its provider model, PowerShell lets you manage data stores using the same techniques you already use to manage files and folders.
We'll explore each of these attributes in this introductory tour of PowerShell.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - An Interactive Shell
- InhaltsvorschauAt its core, PowerShell is first and foremost an interactive shell. While it supports scripting and other powerful features, its focus as a shell underpins everything.Getting started in PowerShell is a simple matter of launching PowerShell.exe rather than cmd.exe—the shells begin to diverge as you explore the intermediate and advanced functionality, but you can be productive in PowerShell immediately.To launch Windows PowerShell, click:Start → All Programs → Windows PowerShell 1.0 → Windows PowerShellOr alternatively, click:Start → Runand then type:PowerShellA PowerShell prompt window opens that's nearly identical to the traditional command prompt window of Windows XP, Windows Server 2003, and their many ancestors. The
PS>prompt indicates that PowerShell is ready for input, as shown in .
Figure : Windows PowerShell, ready for inputOnce you've launched your PowerShell prompt, you can enter DOS-style and Unix-style commands for navigating around the filesystem, just as you would with any Windows or Unix command prompt—as in the interactive session shown in .Example . Entering standard DOS-style file manipulation commands in response to the PowerShell prompt produces the same results you get when you use them with any other Windows shellPS C:\Documents and Settings\Lee> function Prompt { "PS >" } PS >pushd . PS >cd \ PS >dir Directory: Microsoft.PowerShell.Core\FileSystem::C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 11/2/2006 4:36 AM $WINDOWS.~BT d---- 5/8/2007 8:37 PM Blurpark d---- 11/29/2006 2:47 PM Boot d---- 11/28/2006 2:10 PM DECCHECK d---- 10/7/2006 4:30 PM Documents and Settings d---- 5/21/2007 6:02 PM F&SC-demo d---- 4/2/2007 7:21 PM Inetpub d---- 5/20/2007 4:59 PM Program Files d---- 5/21/2007 7:26 PM temp d---- 5/21/2007 8:55 PM Windows -a--- 1/7/2006 10:37 PM 0 autoexec.bat -ar-s 11/29/2006 1:39 PM 8192 BOOTSECT.BAK -a--- 1/7/2006 10:37 PM 0 config.sys -a--- 5/1/2007 8:43 PM 33057 RUU.log -a--- 4/2/2007 7:46 PM 2487 secedit.INTEG.RAW PS >popd PS >pwd Path ---- C:\Documents and Settings\LeeEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Structured Commands (Cmdlets)
- InhaltsvorschauIn addition to supporting traditional Windows executables, PowerShell introduces a powerful new type of command called a cmdlet (pronounced command-let.) All cmdlets are named in a Verb-Noun pattern, such as
Get-Process, Get-Content, andStop-Process.PS >Get-Process -Name lsass Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 668 13 6228 1660 46 932 lsassIn this example, you provide a value to theProcessNameparameter to get a specific process by name.Once you know the handful of common verbs in PowerShell, learning how to work with new nouns becomes much easier. While you may never have worked with a certain object before (such as a Service), the standardGet, Set, Start, andStopactions still apply. For a list of these common verbs, see .You don't always have to type these full cmdlet names, however. PowerShell lets you use theTabkey to auto-complete cmdlet names and parameter names:PS >Get-Pr<Tab> -N<Tab> lsass
For quick interactive use, even that may be too much typing. For improved efficiency, PowerShell defines aliases for all common commands and lets you define your own. In addition to alias names, PowerShell only requires that you type enough of the parameter name to disambiguate it from the other parameters in that cmdlet. PowerShell is also case-insensitive. Using the built-ingpsalias that represents theGet-Processcmdlet (along with parameter shortening), you can instead type:PS >gps -n lsass
Going even further, PowerShell supports positional parameters on cmdlets. Positional parameters let you provide parameter values in a certain position on the command line, rather than having to specify them by name. TheGet-Processcmdlet takes a process name as its first positional parameter. This parameter even supports wildcards:PS >gps l*s
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Deep Integration of Objects
- InhaltsvorschauPowerShell begins to flex more of its muscle as you explore the way it handles structured data and richly functional objects. For example, the following command generates a simple text string. Since nothing captures that output, PowerShell displays it to you:
PS >"Hello World" Hello World
The string you just generated is, in fact, a fully functional object from the .NET Framework. For example, you can access itsLengthproperty, which tells you how many characters are in the string. To access a property, you place a dot between the object and its property name:PS >"Hello World".Length 11
All PowerShell commands that produce output generate that output as objects as well. For example, theGet-Processcmdlet generates aSystem.Diagnostics.Processobject, which you can store in a variable. In PowerShell, variable names start with a$character. If you have an instance of Notepad running, the following command stores a reference to it:$process = Get-Process notepad
Since this is a fully functionalProcessobject from the .NET Framework, you can call methods on that object to perform actions on it. This command calls theKill()method, which stops a process. To access a method, you place a dot between the object and its method name:$process.Kill()
PowerShell supports this functionality more directly through theStop-Processcmdlet, but this example demonstrates an important point about your ability to interact with these rich objects.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Administrators As First-Class Users
- InhaltsvorschauWhile PowerShell's support for objects from the .NET Framework quickens the pulse of most users, PowerShell continues to focus strongly on administrative tasks. For example, PowerShell supports
MB(for megabyte) andGB(for gigabyte) as some of the standard administrative constants. For example, how many disks will it take to back up a 40 GB hard drive to CD-ROM?PS >40GB / 650MB 63.0153846153846
Just because PowerShell is an administrator-focused shell doesn't mean you can't still use the .NET Framework for administrative tasks, though! In fact, PowerShell makes a great calendar. For example, is 2008 a leap year? PowerShell can tell you:PS >[DateTime]::IsLeapYear(2008) True
Going further, how might you determine how much time remains until summer? The following command converts"06/21/2008"(the start of summer) to a date, and then subtracts the current date from that. It stores the result in the$resultvariable, and then accesses theTotalDaysproperty.PS >$result = [DateTime] "06/21/2008" - [DateTime]::Now PS >$result.TotalDays 283.0549285662616
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Composable Commands
- InhaltsvorschauWhenever a command generates output, you can use a pipeline character (|) to pass that output directly to another command. If the second command understands the objects produced by the first command, it can operate on the results.You can chain together many commands this way, creating powerful compositions out of a few simple operations. For example, the following command gets all items in the
Path1directory and moves them to thePath2directory:Get-Item Path1\* | Move-Item -Destination Path2
You can create even more complex commands by adding additional cmdlets to the pipeline. In , the first command gets all processes running on the system. It passes those to theWhere-Objectcmdlet, which runs a comparison against each incoming item. In this case, the comparison is$_.Handles -ge 500, which checks whether theHandlesproperty of the current object (represented by the$_variable) is greater than or equal to500. For each object in which this comparison holds true, you pass the results to theSort-Objectcmdlet, asking it to sort items by theirHandlesproperty. Finally, you pass the objects to theFormat-Tablecmdlet to generate a table that contains theHandles, Name, andDescriptionof the process.Example . You can build more complex PowerShell commands by using pipelines to link cmdlets, as shown in this example with Get-Process, Where-Object, Sort Object, and Format-TablePS >Get-Process | >> Where-Object { $_.Handles -ge 500 } | >> Sort-Object Handles | >> Format-Table Handles,Name,Description -Auto >> Handles Name Description ------- ---- ----------- 588 winlogon 592 svchost 667 lsass 725 csrss 742 System 964 WINWORD Microsoft Office Word 1112 OUTLOOK Microsoft Office Outlook 2063 svchostEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Techniques to Protect You from Yourself
- InhaltsvorschauWhile aliases, wildcards, and composable pipelines are powerful, their use in commands that modify system information can easily be nerve-wracking. After all, what does this command do? Think about it, but don't try it just yet:
PS >gps [b-t]*[c-r] | Stop-Process
It appears to stop all processes that begin with the lettersbthroughtand end with the letterscthroughr. How can you be sure? Let PowerShell tell you. For commands that modify data, PowerShell supports-WhatIfand-Confirmparameters that let you see what a command would do:PS >gps [b-t]*[c-r] | Stop-Process -whatif What if: Performing operation "Stop-Process" on Target "ctfmon (812)". What if: Performing operation "Stop-Process" on Target "Ditto (1916)". What if: Performing operation "Stop-Process" on Target "dsamain (316)". What if: Performing operation "Stop-Process" on Target "ehrecvr (1832)". What if: Performing operation "Stop-Process" on Target "ehSched (1852)". What if: Performing operation "Stop-Process" on Target "EXCEL (2092)". What if: Performing operation "Stop-Process" on Target "explorer (1900)". (...)
In this interaction, using the-WhatIfparameter with theStop-Processpipelined command lets you preview which processes on your system will be stopped before you actually carry out the operation.Note that this example is not a dare! In the words of one reviewer:Not only did it stop everything, but on Vista, it forced a shutdown with only one minute warning!It was very funny though…. At least I had enough time to save everything first!Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Common Discovery Commands
- InhaltsvorschauWhile reading through a guided tour is helpful, I find that most learning happens in an ad-hoc fashion. To find all commands that match a given wildcard, use the
Get-Commandcmdlet. For example, by entering the following, you can find out which PowerShell commands (and Windows applications) contain the word process.PS >Get-Command *process* CommandType Name Definition ----------- ---- ---------- Cmdlet Get-Process Get-Process [[-Name] <Str... Application qprocess.exe c:\windows\system32\qproc... Cmdlet Stop-Process Stop-Process [-Id] <Int32...
To see what a command such asGet-Processdoes, use theGet-Helpcmdlet, like this:PS >Get-Help Get-Process
Since PowerShell lets you work with objects from the .NET Framework, it provides theGet-Membercmdlet to retrieve information about the properties and methods that an object, such as a .NETSystem.String, supports. Piping a string to theGet-Membercommand displays its type name and its members:PS >"Hello World" | Get-Member TypeName: System.String Name MemberType Definition ---- ---------- ---------- (...) PadLeft Method System.String PadLeft(Int32 tota... PadRight Method System.String PadRight(Int32 tot... Remove Method System.String Remove(Int32 start... Replace Method System.String Replace(Char oldCh... Split Method System.String[] Split(Params Cha... StartsWith Method System.Boolean StartsWith(String... Substring Method System.String Substring(Int32 st... ToChar- System.Char[] ToCharArray(), Sys... ArrayMethod ToLower Method System.String ToLower(), System.... ToLower- Method System.String ToLowerInvariant() Invariant ToString Method System.String ToString(), System... ToUpper Method System.String ToUpper(), System.... ToUpper- Method System.String ToUpperInvariant() Invariant Trim Method System.String Trim(Params Char[]... TrimEnd Method System.String TrimEnd(Params Cha... TrimStart Method System.String TrimStart(Params C... Chars Parameter- System.Char Chars(Int32 index) {... izedProperty Length Property System.Int32 Length {get;}Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Ubiquitous Scripting
- InhaltsvorschauPowerShell makes no distinction between the commands you type at the command line and the commands you write in a script. This means that your favorite cmdlets work in scripts and that your favorite scripting techniques (such as the
foreachstatement) work directly on the command line.For example, to add up the handle count for all running processes:PS >$handleCount = 0 PS >foreach($process in Get-Process) { $handleCount += $process.Handles } PS >$handleCount 19403While PowerShell provides a command (Measure-Object) to measure statistics about collections, this short example shows how PowerShell lets you apply techniques that normally require a separate scripting or programming language.In addition to using PowerShell scripting keywords, you can also create and work directly with objects from the .NET Framework. PowerShell becomes almost like the C# immediate mode in Visual Studio. In , you see how PowerShell lets you easily interact with the .NET Framework.Example . Using objects from the .NET Framework to retrieve a web page and process its contentPS >$webClient = New-Object System.Net.WebClient PS >$content = $webClient.DownloadString("http://blogs.msdn.com/ PowerShell/rss.aspx") PS >$content.Substring(0,1000) <?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/ utility/FeedStylesheets/rss.xsl" media="screen"?> <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel> <title>Windo (...)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Ad-Hoc Development
- InhaltsvorschauBy blurring the lines between interactive administration and writing scripts, the history buffer of PowerShell sessions quickly becomes the basis for ad-hoc script development. In this example, you call the
Get-Historycmdlet to retrieve the history of your session. For each of those items, you get itsCommandLineproperty (the thing you typed) and send the output to a new script file.PS >Get-History | Foreach-Object { $_.CommandLine } > c:\temp\script.ps1 PS >notepad c:\temp\script.ps1 (save the content you want to keep) PS >c:\temp\script.ps1If this is the first time you've run a script in PowerShell, you will need to configure your Execution Policy. For more information, type 'help about_signing'.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Bridging Technologies
- InhaltsvorschauWe've seen how PowerShell lets you fully leverage the .NET Framework in your tasks, but its support for common technologies stretches even further. As shows, PowerShell supports XML.Example . Working with XML content in PowerShell
PS >$xmlContent = [xml] $content PS >$xmlContent xml xml-stylesheet rss --- -------------- --- rss PS >$xmlContent.rss version : 2.0 dc : http://purl.org/dc/elements/1.1/ slash : http://purl.org/rss/1.0/modules/slash/ wfw : http://wellformedweb.org/CommentAPI/ channel : channel PS >$xmlContent.rss.channel.item | select Title title --- CMD.exe compatibility Time Stamping Log Files Microsoft Compute Cluster now has a PowerShell Provider and Cmdlets The Virtuous Cycle: .NET Developers using PowerShell (...)And Windows Management Instrumentation (WMI):PS >Get-WmiObject Win32_Bios SMBIOSBIOSVersion : ASUS A7N8X Deluxe ACPI BIOS Rev 1009 Manufacturer : Phoenix Technologies, LTD Name : Phoenix - AwardBIOS v6.00PG SerialNumber : xxxxxxxxxxx Version : Nvidia - 42302e31
Or, as shows, Active Directory Service Interfaces (ADSI).Example . Working with Active Directory in PowerShellPS >[ADSI] "WinNT://./Administrator" | Format-List * UserFlags : {66113} MaxStorage : {-1} PasswordAge : {19550795} PasswordExpired : {0} LoginHours : {255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255} FullName : {} Description : {Built-in account for administering the computer/ domain} BadPasswordAttempts : {0} LastLogin : {5/21/2007 3:00:00 AM} HomeDirectory : {} LoginScript : {} Profile : {} HomeDirDrive : {} Parameters : {} PrimaryGroupID : {513} Name : {Administrator} MinPasswordLength : {0} MaxPasswordAge : {3710851} MinPasswordAge : {0} PasswordHistoryLength : {0} AutoUnlockInterval : {1800} LockoutObservationInterval : {1800} MaxBadPasswordsAllowed : {0} RasPermissions : {1} objectSid : {1 5 0 0 0 0 0 5 21 0 0 0 121 227 252 83 122 130 50 34 67 23 10 50 244 1 0 0}Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Namespace Navigation Through Providers
- InhaltsvorschauAnother avenue PowerShell provides for working with the system is a providers. PowerShell providers let you navigate and manage data stores using the same techniques you already use to work with the filesystem, as illustrated in .This also works on the registry, as shown in .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Much, Much More
- InhaltsvorschauAs exciting as this guided tour was, it barely scratches the surface of how you can use PowerShell to improve your productivity and systems management skills. For more information about getting started in PowerShell, see the "Getting Started" and "User Guide" files included in the Windows PowerShell section of your Start menu. For a cookbook-style guide to PowerShell (and hard-won solutions to its most common problems), you may be interested in the source of the material in this pocket reference: my book Windows PowerShell Cookbook (O'Reilly).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 2: PowerShell Language and Environment
- InhaltsvorschauPowerShell breaks any line that you enter into its individual units (tokens), and then interprets each token in one of two ways: as a command or as an expression. The difference is subtle: expressions support logic and flow control statements (such as
if, foreach, andthrow) while commands do not. You will often want to control the way that Windows PowerShell interprets your statements, so lists the available options.Table : Windows PowerShell evaluation controls StatementExampleExplanationPrecedence control:()PS >5 * (1 + 2) 15 PS >(dir).Count 2276
Forces the evaluation of a command or expression, similar to how parentheses force the order of evaluation in a math expression.Expression subparse: $()PS >"The answer is (2+2)" The answer is (2+2) PS >"The answer is $(2+2)" The answer is 4 PS >$value = 10 PS >$result = $( >> if($value -gt 0) { $true } else { $false } >> ) >> PS >$result TrueForces the evaluation of a command or expression, similar to how parentheses force the order of evaluation in a mathematical expression. However, a subparse is as powerful as a subprogram, and is required only when it contains logic or flow control statements. This statement is also used to expand dynamic information inside a string.List evaluation:@()PS >"Hello".Length 5 PS >@("Hello").Length 1 PS >(Get-ChildItem). Count 12 PS >(Get-ChildItem *.txt).Count PS >@(Get-ChildItem *.txt).Count 1Forces an expression to be evaluated as a list. If it is already a list, it will remain a list. If it is not, PowerShell temporarily treats it as one.To create single-line comments, begin a line with the # character. Windows PowerShell does not support multiline comments, but you can deactivate larger regions of your script by placing them in a here string:# This is a regular comment # Start of the here string $null = @" function MyTest { "This should not be considered a function" } $myVariable = 10; "@ # End of the here string # This is regular script againSee "Strings" to learn more about here strings.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Commands and Expressions
- InhaltsvorschauPowerShell breaks any line that you enter into its individual units (tokens), and then interprets each token in one of two ways: as a command or as an expression. The difference is subtle: expressions support logic and flow control statements (such as
if, foreach, andthrow) while commands do not. You will often want to control the way that Windows PowerShell interprets your statements, so lists the available options.Table : Windows PowerShell evaluation controls StatementExampleExplanationPrecedence control:()PS >5 * (1 + 2) 15 PS >(dir).Count 2276
Forces the evaluation of a command or expression, similar to how parentheses force the order of evaluation in a math expression.Expression subparse: $()PS >"The answer is (2+2)" The answer is (2+2) PS >"The answer is $(2+2)" The answer is 4 PS >$value = 10 PS >$result = $( >> if($value -gt 0) { $true } else { $false } >> ) >> PS >$result TrueForces the evaluation of a command or expression, similar to how parentheses force the order of evaluation in a mathematical expression. However, a subparse is as powerful as a subprogram, and is required only when it contains logic or flow control statements. This statement is also used to expand dynamic information inside a string.List evaluation:@()PS >"Hello".Length 5 PS >@("Hello").Length 1 PS >(Get-ChildItem). Count 12 PS >(Get-ChildItem *.txt).Count PS >@(Get-ChildItem *.txt).Count 1Forces an expression to be evaluated as a list. If it is already a list, it will remain a list. If it is not, PowerShell temporarily treats it as one.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Comments
- InhaltsvorschauTo create single-line comments, begin a line with the # character. Windows PowerShell does not support multiline comments, but you can deactivate larger regions of your script by placing them in a here string:
# This is a regular comment # Start of the here string $null = @" function MyTest { "This should not be considered a function" } $myVariable = 10; "@ # End of the here string # This is regular script againSee "Strings" to learn more about here strings.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Variables
- InhaltsvorschauWindows PowerShell provides several ways to define and access variables, as summarized in .
Table : Windows PowerShell variable syntaxes SyntaxMeaning$simpleVariable = "Value"A simple variable name. The variable name must consist of alphanumeric characters. Variable names are not case sensitive.${arbitrary!@#@#`{var`}iable} = "Value"An arbitrary variable name. The variable name must be surrounded by curly braces, but may contain any characters. Curly braces in the variable name must be escaped with a backtick (`).${c:\filename.extension}Variable "Get and Set Content" syntax. This is similar to the arbitrary variable name syntax. If the name corresponds to a valid PowerShell path, you can get and set the content of the item at that location by reading and writing to the variable.[datatype] $variable = "Value"Strongly typed variable. Ensures that the variable may contain only data of the type you declare. PowerShell throws an error if it cannot coerce the data to this type when you assign it.$SCOPE:variableGets or sets the variable at that specific scope. Valid scope names areglobal(to make a variable available to the entire shell),script(to make a variable available only to the current script),local(to make a variable available only to the current scope and subscopes), andprivate(to make a variable available only to the current scope). The default scope is the current scope:globalwhen defined interactively in the shell,scriptwhen defined outside any functions or script blocks in a script, andlocalelsewhere.New-Item Variable:\variable–ValuevalueCreates a new variable using the Variable Provider.Get-Item Variable:\variableGet-VariablevariableGets the variable using the Variable Provider orGet-Variablecmdlet. This lets you access extra information about the variable, such as its options and description.New-Variablevariable-Optionoption-ValuevalueCreates a variable using theNew-Variablecmdlet. This lets you provide extra information about the variable, such as its options and description.Unlike some languages, PowerShell rounds (not truncates) numbers when it converts them to theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Booleans
- InhaltsvorschauBoolean (true or false) variables are most commonly initialized to their literal values of
$trueand$false. When it evaluates variables as part of a Boolean expression (for example, anifstatement), though, PowerShell maps them to a suitable Boolean representation, as listed in .Table : Windows PowerShell Boolean interpretations ResultBoolean representation$trueTrue$falseFalse$nullFalseNonzero numberTrueZeroFalseNonempty stringTrueEmpty stringFalseNonempty arrayTrueEmpty arrayFalseHashtable (either empty or not)TrueEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Strings
- InhaltsvorschauWindows PowerShell offers several facilities for working with plain-text data.To define a literal string (one in which no variable or escape expansion occurs), enclose it in single quotes:
$myString = 'hello 't $ENV:SystemRoot'
$myStringgets the actual value ofhello 't $ENV:SystemRoot.To define an expanding string (one in which variable and escape expansion occurs), enclose it in double quotes:$myString = "hello 't $ENV:SystemRoot"
$myStringgets a value similar tohello C:\WINDOWS.To include a single quote in a single-quoted string or a double quote in a double-quoted string, you may include two of the quote characters in a row:PS >"Hello ""There""!" Hello "There"! PS >'Hello ''There''!' Hello 'There'!
To include a complex expression inside an expanding string, use a subexpression. For example:$prompt = "$(Get-Location) >"
$promptgets a value similar toc:\temp >.Accessing the properties of an object requires a subexpression:$output = "Current script name is: $($myInvocation.MyCommand.Path)"$outputgets a value similar toCurrent script name is c:\Test-Script.ps1.To define a here string (one that may span multiple lines), place the two characters @" at the beginning, and the two characters "@ on their own line at the end.For example:$myHereString = @" This text may span multiple lines, and may contain "quotes". "@
Here strings may be of either the literal (single-quoted) or expanding (double quoted) variety.Windows PowerShell supports escape sequences inside strings, as listed in .Table : Windows PowerShell escape sequences SequenceMeaning`0The null character. Often used as a record separator.`aThe alarm character. Generates a beep when displayed on the console.`bThe backspace character. The previous character remains in the string but is overwritten when displayed on the console.`fA form feed. Creates a page break when printed on most printers.`nA newline.`rA carriage return. Newlines in PowerShell are indicated entirely by the`ncharacter, so this is rarely required.`tA tab.`vA vertical tab.''(Two single quotes)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Numbers
- InhaltsvorschauPowerShell offers several options for interacting with numbers and numeric data.To define a variable that holds numeric data, simply assign it as you would other variables. PowerShell automatically stores your data in a format that is sufficient to accurately hold it.
$myInt = 10
$myIntgets the value of10, as a (32-bit) integer.$myDouble = 3.14
$myDoublegets the value of3.14, as a (53-bit, 9 bits of precision) double.To explicitly assign a number as a long (64-bit) integer or decimal (96-bit, 96 bits of precision), use the long and decimal suffixes:$myLong = 2147483648L
$myLonggets the value of2147483648, as a long integer.$myDecimal = 0.999D
$myDecimalgets the value of0.999.PowerShell also supports scientific notation:$myPi = 3141592653e-9
$myPigets the value of3.141592653.The data types in PowerShell (integer, long integer, double, and decimal) are built on the .NET data types of the same name.Since computer administrators rarely get the chance to work with numbers in even powers of ten, PowerShell offers the numeric constants ofgb, mb, andkbto represent gigabytes, megabytes, and kilobytes, respectively:PS >$downloadTime = (1gb + 250mb) / 120kb PS >$downloadTime 10871.4666666667
To directly enter a hexadecimal number, use the hexadecimal prefix0x:$myErrorCode = 0xFE4A
$myErrorCodegets the integer value65098.The PowerShell scripting language does not natively support other number bases, but its support for interaction with the .NET Framework enables conversion to and from binary, octal, decimal, and hexadecimal:$myBinary = [Convert]::ToInt32("101101010101", 2)$myBinarygets the integer value of2901.$myOctal = [Convert]::ToInt32("1234567", 8)$myOctalgets the integer value of342391.$myHexString = [Convert]::ToString(65098, 16)
$myHexStringgets the string value offe4a.$myBinaryString = [Convert]::ToString(12345, 2)
$myBinaryStringgets the string value of11000000111001.See "Working with the .NET Framework," later in this chapter, to learn more about using PowerShell to interact with the .NET Framework.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Arrays and Lists
- InhaltsvorschauPowerShell arrays hold lists of data. The @() (array cast) syntax tells PowerShell to treat the contents between the parentheses as an array. To create an empty array, type:
$myArray = @()
To define a nonempty array, use a comma to separate its elements:$mySimpleArray = 1,"Two",3.14
Arrays may optionally be only a single element long:$myList = ,"Hello"
Or, alternatively (using the array cast syntax):$myList = @("Hello")Elements of an array do not need to be all of the same data type, unless you declare it as a strongly typed array. In the following example, the outer square brackets define a strongly typed variable (as mentioned in "Variables," earlier in this chapter), andint[]represents an array of integers:[int[]] $myArray = 1,2,3.14
In this mode, PowerShell throws an error if it cannot convert any of the elements in your list to the required data type. In this case, it rounds3.14to the integer value of3.PS >$myArray[2] 3
To ensure that PowerShell treats collections of uncertain length (such as history lists or directory listings) as a list, use the list evaluation syntax @(…) described in "Commands and Expressions," earlier in this chapter.Arrays can also be multidimensional "jagged" arrays—arrays within arrays:$multiDimensional = @( (1,2,3,4), (5,6,7,8) )$multiDimensional[0][1]returns2, coming from row 0, column 1.$multiDimensional[1][3]returns8, coming from row 1, column 3.To define a multidimensional array that is not jagged, create a multidimensional instance of the .NET type. For integers, that would be an array ofSystem.Int32:$multidimensional = New-Object "Int32[,]" 2,4 $multidimensional[0,1] = 2 $multidimensional[1,3] = 8
To access a specific element in an array, use the [] operator. PowerShell numbers your array elements starting at 0. Using$myArray = 1,2,3,4,5,6as an example:$myArray[0]
Returns1, the first element in the array.$myArray[2]
Returns3, the third element in the array.$myArray[-1]
Returns6, the last element in the array.$myArray[-2]
Returns5, the second-to-last element in the array.You can also access ranges of elements in your array:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Hashtables (Associative Arrays)
- InhaltsvorschauPowerShell hashtables (or associative arrays) let you associate keys with values. To define a hashtable, use the syntax:
$myHashtable = @{}You can initialize a hashtable with its key/value pairs when you create it. PowerShell assumes that the keys are strings, but the values may be any data type.$myHashtable = @{ Key1 = "Value1"; "Key 2" = 1,2,3; 3.14 = "Pi" }To access or modify a specific element in an associative array, you may use either the array-access or property-access syntax:$myHashtable["Key1"]
Returns"Value1".$myHashtable."Key 2"
Returns the array1,2,3.$myHashtable["New Item"] = 5
Adds"New Item"to the hashtable.$myHashtable."New Item" = 5
Also adds"New Item"to the hashtable.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - XML
- InhaltsvorschauPowerShell supports XML as a native data type. To create an XML variable, cast a string to the
[xml]type:$myXml = [xml] @" <AddressBook> <Person contactType="Personal"> <Name>Lee</Name> <Phone type="home">555-1212</Phone> <Phone type="work">555-1213</Phone> </Person> <Person contactType="Business"> <Name>Ariel</Name> <Phone>555-1234</Phone> </Person> </AddressBook> "@PowerShell exposes all child nodes and attributes as properties. When it does this, PowerShell automatically groups children that share the same node type:$myXml.AddressBook
Returns an object that contains aPersonproperty.$myXml.AddressBook.Person
Returns a list ofPersonnodes. EachPersonnode exposescontactType, Name, andPhoneas properties.$myXml.AddressBook.Person[0]
Returns the firstPersonnode.$myXml.AddressBook.Person[0].ContactType
ReturnsPersonalas the contact type of the firstPersonnode.The XML data type wraps the .NETXmlDocumentandXmlElementclasses. Unlike most PowerShell .NET wrappers, this wrapper does not expose the properties from the underlying class because they may conflict with the dynamic properties that PowerShell adds for node names.To access properties of the underlying class, use thePsBaseproperty. For example:$myXml.PsBase.InnerXml
See "Working with the .NET Framework," later in this chapter, to learn more about using PowerShell to interact with the .NET Framework.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Simple Operators
- InhaltsvorschauOnce you've defined your data, the next step is to work with it.The arithmetic operators let you perform mathematical operations on your data, as shown in .
Table : Windows PowerShell arithmetic operators OperatorMeaning+The addition operator:$leftValue + $rightValueWhen used with numbers, returns their sum.When used with strings, returns a new string created by appending the second string to the first.When used with arrays, returns a new array created by appending the second array to the first.When used with hashtables, returns a new hashtable created by merging the two hashtables. Since hashtable keys must be unique, PowerShell returns an error if the second hashtable includes any keys already defined in the first hashtable.When used with any other type, PowerShell uses that type's addition operator (op_Addition) if it implements one.-The subtraction operator:$leftValue - $rightValueWhen used with numbers, returns their difference.This operator does not apply to strings.This operator does not apply to arrays.This operator does not apply to hashtables.When used with any other type, PowerShell uses that type's subtraction operator (op_Subtraction) if it implements one.*The multiplication operator:$leftValue * $rightValueWhen used with numbers, returns their product.When used with strings ("=" * 80), returns a new string created by appending the string to itself the number of times you specify.When used with arrays (1..3 * 7), returns a new array created by appending the array to itself the number of times you specify.This operator does not apply to hashtables.When used with any other type, PowerShell uses that type's multiplication operator (op_Multiply) if it implements one./The division operator:$leftValue / $rightValueWhen used with numbers, returns their quotient.This operator does not apply to strings.This operator does not apply to arrays.This operator does not apply to hashtables.When used with any other type, PowerShell uses that type's multiplication operator (op_Division) if it implements one.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Comparison Operators
- InhaltsvorschauThe PowerShell comparison operators, listed in , let you compare expressions against each other. By default, PowerShell's comparison operators are case insensitive. For all operators where case sensitivity applies, the
-iprefix makes this case insensitivity explicit, while the-cprefix performs a case-sensitive comparison.Table : Windows PowerShell comparison operators OperatorMeaning-eqThe equality operator:$leftValue -eq $rightValue
For all primitive types, returns$trueif $leftValue and $rightValue are equal.When used with arrays, returns all elements in $leftValue that are equal to $rightValue.When used with any other type, PowerShell uses that type'sEquals()method if it implements one.-neThe negated equality operator:$leftValue -ne $rightValue
For all primitive types, returns$trueif $leftValue and $rightValue are not equal.When used with arrays, returns all elements in $leftValue that are not equal to $rightValue.When used with any other type, PowerShell returns the negation of that type'sEquals()method if it implements one.-geThe greater-than-or-equal to operator:$leftValue -ge $rightValue
For all primitive types, returns$trueif $leftValue is greater than or equal to $rightValue.When used with arrays, returns all elements in $leftValue that are greater than or equal to $rightValue.When used with any other type, PowerShell returns the result of that object'sCompare()method if it implements one. If the method returns a number greater than or equal to 0, the operator returns$true.-gtThe greater-than operator:$leftValue -gt $rightValue
For all primitive types, returns$trueif $leftValue is greater than $rightValue.When used with arrays, returns all elements in $leftValue that are greater than $rightValue.When used with any other type, PowerShell returns the result of that object'sCompare()method if it implements one. If the method returns a number greater than 0, the operator returns$true.-ltThe less-than operator:$leftValue -lt $rightValue
For all primitive types, returns$trueifEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Conditional Statements
- InhaltsvorschauConditional statements in PowerShell let you change the flow of execution in your script.
if(condition) { statement block } elseif(condition) { statement block } else { statement block }If condition evaluates to$true, then PowerShell executes the statement block you provide. Then, it resumes execution at the end of theif / elseif / elsestatement list. PowerShell requires the enclosing braces around the statement block even if the statement block contains only one statement.See "Simple Operators" and "Comparison Operators," both earlier in this chapter, for a discussion of how PowerShell evaluates expressions as conditions.If condition evaluates to$false, then PowerShell evaluates any following (optional)elseifconditions until one matches. If one matches, PowerShell executes the statement block associated with that condition, then resumes execution at the end of theif / elseif / elsestatement list.For example:$textToMatch = Read-Host "Enter some text" $matchType = Read-Host "Apply Simple or Regex matching?" $pattern = Read-Host "Match pattern" if($matchType -eq "Simple") { $textToMatch -like $pattern } elseif($matchType -eq "Regex") { $textToMatch -match $pattern } else { Write-Host "Match type must be Simple or Regex" }If none of the conditions evaluate to$true, then PowerShell executes the statement block associated with the (optional)elseclause, then resumes execution at the end of theif / elseif / elsestatement list.switch options expression { comparison value { statement block } -or- { comparison expression } { statement block } (...) default { statement block } }or:switch options -file filename { comparison value { statement block } -or- { comparison expression } { statement block } (...) default { statement block } }When PowerShell evaluates aswitchstatement, it evaluates expression against the statements in the switch body. If expression is a list of values, PowerShell evaluates each item against the statements in the switch body. If you specify theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Looping Statements
- InhaltsvorschauLooping statements in PowerShell let you execute groups of statements multiple times.
:loop_label for(initialization; condition; increment) { statement block }When PowerShell executes aforstatement, it first executes the expression given by initialization. It next evaluates condition. If condition evaluates to$true, PowerShell executes the given statement block. It then executes the expression given by increment. PowerShell continues to execute the statement block and increment statement as long as condition evaluates to$true.For example:for($counter = 0; $counter -lt 10; $counter++) { Write-Host "Processing item $counter" }Thebreakandcontinuestatements (discussed later in the chapter) can specify the loop_label of any enclosing looping statement as their target.:loop_label foreach(variable in expression) { statement block }When PowerShell executes aforeachstatement, it executes the pipeline given by expression—for example,Get-Process|Where-Object{$_.Handles -gt 500 }or1..10. For each item produced by the expression, it assigns that item to the variable specified by variable and then executes the given statement block. For example:$handleSum = 0; foreach($process in Get-Process | Where-Object { $_.Handles -gt 500 }) { $handleSum += $process.Handles } $handleSumThebreakandcontinuestatements (discussed later in the chapter) can specify the loop_label of any enclosing looping statement as their target.:loop_label while(condition) { statement block }When PowerShell executes awhilestatement, it first evaluates the expression given by condition. If this expression evaluates to$true, PowerShell executes the given statement block. PowerShell continues to execute the statement block as long as condition evaluates to$true. For example:$command = ""; while($command -notmatch "quit") { $command = Read-Host "Enter your command" }Thebreakandcontinuestatements (discussed later in this chapter) can specify the loop_label of any enclosing looping statement as their target.:loop_label do { statement block } while(condition)or::loop_label do { statement block } until(condition)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Working with the .NET Framework
- InhaltsvorschauOne feature that gives PowerShell its incredible reach into both system administration and application development is its capability to leverage Microsoft's enormous and broad .NET Framework.Work with the .NET Framework in PowerShell comes mainly by way of one of two tasks: calling methods or accessing properties.To call a static method on a class, type:
[ClassName]::MethodName(parameter list)
For example:PS >[System.Diagnostics.Process]::GetProcessById(0)
gets the process with the ID of0and displays the following output:Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 0 0 0 16 0 0 IdleTo call a method on an instance of an object, type:$objectReference.MethodName(parameter list)
For example:PS >$process = [System.Diagnostics.Process]:: GetProcessById(0) PS >$process.Refresh()
This stores the process with the ID of0into the$processvariable. It then calls theRefresh()instance method on that specific process.To access a static property on a class, type:[ClassName]::PropertyNameor:[ClassName]::PropertyName = valueFor example, the[System.DateTime]class provides aNowstatic property that returns the current time:PS >[System.DateTime]::Now Sunday, July 16, 2006 2:07:20 PM
Although rare, some types let you set the value of some static properties.To access an instance property on an object, type:$objectReference.PropertyNameor:$objectReference.PropertyName = value
For example:PS >$today = [System.DateTime]::Now PS >$today.DayOfWeek Sunday
This stores the current date in the$todayvariable. It then calls theDayOfWeekinstance property on that specific date.The two primary avenues for learning about classes and types are theGet-Membercmdlet and the documentation for the .NET Framework.The Get-Member cmdlet
To learn what methods and properties a given type supports, pass it through theGet-Membercmdlet, as shown in .Table : Working with the Get-Member cmdlet ActionResult[typename]| Get-Member -StaticAll the static methods and properties of a given type.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Writing Scripts, Reusing Functionality
- InhaltsvorschauWhen you want to start packaging and reusing your commands, the best place to put them is in scripts and functions. A script is a text file that contains a sequence of PowerShell commands. A function is also a sequence of PowerShell commands but is usually used within a script to break it into smaller, more easily understood segments.To write a script, write your PowerShell commands in a text editor and save the file with a .ps1 extension.There are two ways to execute a script: by invoking it or by dot-sourcing it.
Invoking
Invoking a script runs the commands inside it. Unless explicitly defined with theGLOBALscope keyword, variables and functions defined in the script do not persist once the script exits.You invoke a script by using the invoke/call operator (&) with the script name as the parameter:& "C:\Script Directory\Run-Commands.ps1" Parameters
You can use either a fully qualified path or a path relative to the current location. If the script is in the current directory, you must explicitly say so:.\Run-Commands.ps1 Parameters
If the path contains no spaces, you may omit both the quotes and invoke the operator.Dot-sourcing
Dot-sourcing a script runs the commands inside it. Unlike invoking a script, variables and functions defined in the script do persist after the script exits.You dot-source a script by using the dot operator (.) and providing the script name as the parameter:. "C:\Script Directory\Run-Commands.ps1" Parameters
You can use either a fully qualified path or a path relative to the current location. If the script is in the current directory, you must explicitly say so:. .\Run-Commands.ps1 Parameters
If the path contains no spaces, you may omit the quotes.By default, a security feature in PowerShell called the Execution Policy prevents scripts from running. When you want to enable scripting in PowerShell, you must change this setting. To understand the different execution policies available to you, type Get-Help about_signing. After selecting an execution policy, use theSet-ExecutionPolicycmd-let to configure it:Set-ExecutionPolicy RemoteSignedPowerShell offers several options for processing input to a script.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Managing Errors
- InhaltsvorschauPowerShell supports two classes of errors: nonterminating and terminating. It collects both types of errors as a list in the
$errorautomatic variable.Most errors are nonterminating errors, in that they do not halt execution of the current cmdlet, script, function, or pipeline. When a command outputs an error (via PowerShell's error-output facilities), PowerShell writes that error to a stream called the error output stream.You can output a nonterminating error using theWrite-Errorcmdlet (or theWriteError()API when writing a cmdlet).The$ErrorActionPreferenceautomatic variable lets you control how PowerShell handles nonterminating errors. It supports the following values, as shown in .Table : $ErrorActionPreference automatic variable values ValueMeaningSilentlyContinueDo not display errors.StopTreat nonterminating errors as terminating errors.ContinueDisplay errors, but continue execution of the current cmdlet, script, function, or pipeline. This is the default.InquireDisplay a prompt that asks how PowerShell should treat this error.Most cmdlets let you configure this explicitly by passing one of the above values to itsErrorActionparameter.A terminating error halts execution of the current cmdlet, script, function, or pipeline. If a command (such as a cmdlet or .NET method call) generates a structured exception (for example, if you provide a method with parameters outside their valid range), PowerShell exposes this as a terminating error. PowerShell also generates a terminating error if it fails to parse an element of your script, function, or pipeline.You can generate a terminating error in your script using thethrowkeyword:throw messageIn your own scripts and cmdlets, generate terminating errors only when the fundamental intent of the operation is impossible to accomplish. For example, failing to execute a command on a remote server should be considered a nonterminating error, while failing to connect to the remote server altogether should be considered a terminating error.PowerShell lets you intercept terminating errors if you define aEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Formatting Output
- Inhaltsvorschau
Pipeline | Formatting CommandWhen objects reach the end of the output pipeline, PowerShell converts them to text to make them suitable for human consumption. PowerShell supports several options to help you control this formatting process, as listed in .Table : PowerShell formatting commands Formatting commandResultFormat-Table PropertiesFormats the properties of the input objects as a table, including only the object properties you specify. If you do not specify a property list, PowerShell picks a default set.In addition to supplying object properties, you may also provide advanced formatting statements:PS > Get-Process | ` Format-Table -Auto Name,` @{Label="HexId"; Expression={ "{0:x}" -f $_.Id} Width=4 Align="Right" }The advanced formatting statement is a hashtable with the keysLabelandExpression(or any short form of them). The value of theExpressionkey should be a script block that returns a result for the current object (represented by the $_ variable).For more information about theFormat-Tablecmdlet, typeGet-Help Format-Table.Format-List PropertiesFormats the properties of the input objects as a list, including only the object properties you specify. If you do not specify a property list, PowerShell picks a default set.TheFormat-Listcmdlet supports the advanced formatting statements as used by theFormat-Tablecmdlet.TheFormat-Listcmdlet is the one you will use most often to get a detailed summary of an object's properties.The commandFormat-List *returns all properties but does not include those that PowerShell hides by default. The commandFormat-List * -Forcereturns all properties.For more information about theFormat-Listcmdlet, typeGet-Help Format-List.Format-Wide PropertyFormats the properties of the input objects in an extremely terse summary view. If you do not specify a property, PowerShell picks a default.In addition to supplying object properties, you may also provide advanced formatting statements:PS >Get-Process | ` Format-Wide -Auto ` @{ Expression={ "{0:x}" -f $_.Id} }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Capturing Output
- InhaltsvorschauThere are several ways to capture the output of commands in PowerShell, as listed in .
Table : Capturing output in PowerShell CommandResult$variable = CommandStores the objects produced by the PowerShell command into $variable.$variable = Command| Out-StringStores the visual representation of the PowerShell command into $variable. This is the PowerShell command after it's been converted to human-readable output.$variable = NativeCommandStores the (string) output of the native command into $variable. PowerShell stores this as a list of strings—one for each line of output from the native command.Command-OutVariablevariableFor most commands, stores the objects produced by the PowerShell command into $variable. The parameter-OutVariablecan also be written-Ov.Command > FileRedirects the visual representation of the PowerShell (or standard output of a native command) into File, overwriting File if it exists. Errors are not captured by this redirection.Command >> FileRedirects the visual representation of the PowerShell (or standard output of a native command) into File, appending to File if it exists. Errors are not captured by this redirection.Command 2> FileRedirects the errors from the PowerShell or native command into File, overwriting File if it exists.Command 2>> FileRedirects the errors from the PowerShell or native command into File, appending to File if it exists.Command > File 2>&1Redirects both the error and standard output streams of the PowerShell or native command into File, overwriting File if it exists.Command >> File 2>&1Redirects both the error and standard output streams of the PowerShell or native command into File, appending to File if it exists.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tracing and Debugging
- InhaltsvorschauThe three facilities for tracing and debugging in PowerShell are the
Set-PsDebugcmdlet, theTrace-Commandcmdlet, and the verbose cmdlet output.TheSet-PsDebugcmdlet lets you control tracing, stepping, and strict mode in PowerShell. lists the parameters of theSet-PsDebugcmdlet.Table : Parameters of the Set-PsDebug cmdlet ParameterDescriptionTraceSets the amount of tracing detail that PowerShell outputs when running commands.A value of1outputs all lines as PowerShell evaluates them. A value of2outputs all lines as PowerShell evaluates them, along with information about variable assignments, function calls, and scripts. A value of0disables tracing.StepEnables and disables per-command stepping. When enabled, PowerShell prompts you before it executes a command.StrictEnables and disables strict mode. When enabled, PowerShell throws a terminating error if you attempt to reference a variable that you have not yet defined.OffTurns off tracing, stepping, and strict mode.Trace-Command CommandDiscovery -PsHost { gci c:\ }TheTrace-Commandcmdlet exposes diagnostic and support information for PowerShell commands. PowerShell groups its diagnostic information into categories called trace sources.A full list of trace sources is available through theGet-TraceSourcecmdlet.For more information about theTrace-Commandcmdlet, type Get-Help Trace-Command.Cmdlet -Verbose
PowerShell commands can generate verbose output using theWrite-Verbosecmdlet (if written as a script), or theWriteVerbose()API (when written as a cmdlet).The$VerbosePreferenceautomatic variable lets you control how PowerShell handles verbose output. It supports the values listed in .Table : VerbosePreference automatic variable values ValueMeaningSilentlyContinueDo not display verbose output. This is the default.StopTreat verbose output as a terminating error.ContinueDisplay verbose output and continue execution of the current cmdlet, script, function, or pipeline.InquireDisplay a prompt that asks how PowerShell should treat this verbose output.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Common Customization Points
- InhaltsvorschauAs useful as it is out of the box, PowerShell offers several avenues for customization and personalization.The Windows PowerShell user interface offers several features to make your shell experience more efficient.
Adjust your window size
In the System menu (right-click the PowerShell icon at the top left of the console window), select Properties → Layout. The Window Size options let you control the actual window size (how big the window appears on screen), while the Screen Buffer Size options let you control the virtual window size (how much content the window can hold). If the screen buffer size is larger than the actual window size, the console window changes to include scrollbars. Increase the virtual window height to make PowerShell store more output from earlier in your session. If you launch PowerShell from the Start menu, PowerShell launches with some default modifications to the window size.Make text selection easier
In the System menu, click Options → QuickEdit Mode. QuickEdit mode lets you use the mouse to efficiently copy and paste text into or out of your PowerShell console. If you launch PowerShell from the Start menu, PowerShell launches with QuickEdit mode enabled.Use hotkeys to operate the shell more efficiently
The Windows PowerShell console supports many hotkeys that help make operating the console more efficient, as shown in .Table : Windows PowerShell hotkeys HotkeyMeaningWindows key + r, and then type powershellLaunch Windows PowerShell.Up arrowScan backward through your command history.Down arrowScan forward through your command history.Page UpDisplay the first command in your command history.Page DownDisplay the last command in your command history.Left arrowMove cursor one character to the left on your command line.Right arrowMove cursor one character to the right on your command line. If at the end of the line, it inserts a character from the text of your last command at that position.HomeMove the cursor to the beginning of the command line.EndMove the cursor to the end of the command line.Control + left arrowEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 3: Regular Expression Reference
- InhaltsvorschauRegular expressions play an important role in most text parsing and text matching tasks. They form an important underpinning of the
-matchoperator, theswitchstatement, theSelect-Stringcmdlet, and more. Tables through list commonly used regular expressions.Table : Character classes: Patterns that represent sets of characters Character classMatches.Any character except for a newline. If the regular expression uses theSingleLineoption, it matches any character.PS >"T" -match '.' True
[characters]Any character in the brackets. For example: [aeiou].PS >"Test" -match '[Tes]' True
[^characters]Any character not in the brackets. For example: [^aeiou].PS >"Test" -match '[^Tes]' False
[start-end]Any character between the charactersstartandend, inclusive. You may include multiple character ranges between the brackets. For example, [a-eh-j].PS >"Test" -match '[e-t]' True
[^start-end]Any character not between any of the character rangesstartthroughend, inclusive. You may include multiple character ranges between the brackets. For example, [^a-eh-j].PS >"Test" -match '[^e-t]' False
\p{character class}Any character in the Unicode group or block range specified by {character class}.PS >"+" -match '\p{Sm}' True\P{character class}Any character not in the Unicode group or block range specified by {character class}.PS >"+" -match '\P{Sm}' False\wAny word character.PS >"a" -match '\w' True
\WAny nonword character.PS >"!" -match '\W' True
\sAny whitespace character.PS >"`t" -match '\s' True
\SAny nonwhitespace character.PS >" `t" -match '\S' False
\dAny decimal digit.PS >"5" -match '\d' True
\DAny nondecimal digit.PS >"!" -match '\D' True
Table : Quantifiers: Expressions that enforce quantity on the preceding expression QuantifierMeaning<none>One match.PS >"T" -match 'T' True
*Zero or more matches, matching as much as possible.PS >"A" -match 'T*' True PS >"TTTTT" -match '^T*$' True
+One or more matches, matching as much as possible.PS >"A" -match 'T+' False PS >"TTTTT" -match '^T+$' True
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 4: PowerShell Automatic Variables
- InhaltsvorschauPowerShell defines and populates several variables automatically. These variables let you access information about the execution environment, PowerShell preferences, and more.provides a listing of these automatic variables and their meanings.
Table : Windows PowerShell automatic variables: Variables automatically used and set by Windows PowerShell VariableMeaning$$Last token of the last line received by the shell.$?Success/fail status of the last operation.$^First token of the last line received by the shell.$_Current pipeline object in a pipelined script block.$argsArray of parameters passed to the script, function, or script block.$confirmPreferencePreference that controls the level of impact that operations may have before requesting confirmation. Supports the valuesnone, low, medium, high. A value ofnonedisables confirmation messages.$consoleFilenameFilename of the PowerShell console file that configured this session, if one was used.$currentlyExecutingCommandCurrently executing command, when in a suspended prompt.$debugPreferencePreference that controls how PowerShell should handle debug output written by a script or cmdlet. Supports the valuesSilentlyContinue, Continue, Inquire, andStop.$errorArray that holds the terminating and nonterminating errors generated in the shell.$errorActionPreferencePreference that controls how PowerShell should handle error output written by a script or cmdlet. Supports the valuesSilentlyContinue, Continue, Inquire, andStop.$errorViewPreference that controls how PowerShell should output errors in the shell. Supports the values ofNormalandCategoryView(a more succinct and categorical view of the error).$executionContextMeans by which scripts can access the APIs typically used by cmdlets and providers.$falseVariable that represents the Boolean valueFalse.$foreachEnumerator within aforeachloop.$formatEnumerationLimitLimit on how deep into an object the formatting and output facilities travel before outputting an object.$homeUser's home directory.$hostMeans by which scripts can access the APIs and implementation details of the current host and user interface.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 5: Standard PowerShell Verbs
- InhaltsvorschauCmdlets and scripts should be named using a Verb-Noun syntax, for example,
Get-ChildItem. The official guidance is that, with rare exception, cmdlets should use the standard PowerShell verbs. They should avoid any synonyms or concepts that can be mapped to the standard. This allows administrators to quickly understand a set of cmdlets that use a new noun.Verbs should be phrased in the present tense, and nouns should be singular. Tables through list the different categories of standard PowerShell verbs.Table : Standard Windows PowerShell common verbs VerbMeaningSynonymsAddAdds a resource to a container, or attaches an element to another element.Append, Attach, Concatenate, InsertClearRemoves all elements from a container.Flush, Erase, Release, Unmark, Unset, NullifyCopyCopies a resource to another name or container.Duplicate, Clone, ReplicateGetRetrieves data.Read, Open, Cat, Type, Dir, Obtain, Dump, Acquire, Examine, Find, SearchHideMakes a display not visible.SuppressJoinJoins a resource.Combine, Unite, Connect, AssociateLockLocks a resource.Restrict, BarMoveMoves a resource.Transfer, Name, MigrateNewCreates a new resource.Create, Generate, Build, Make, AllocatePushPuts an item onto the top of a stack.Put, Add, CopyPopRemoves an item from the top of a stack.Remove, PasteRemoveRemoves a resource from a container.Delete, KillRenameGives a resource a new name.Ren, SwapSearchFinds a resource (or summary information about that resource) in a collection. Does not actually retrieve the resource, but provides information to be used when retrieving it.Find, Get, Grep, SelectSelectCreates a subset of data from a larger data set.Pick, Grep, FilterSetPlaces data.Write, Assign, ConfigureShowRetrieves, formats, and displays information.Display, ReportSplitSeparates data into smaller elements.Divide, Chop, ParseUnlockUnlocks a resource.Free, UnrestrictUseApplies or associates a resource with a context.With, HavingTable : Standard Windows PowerShell communication verbs Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 6: Selected .NET Classes and Their Uses
- InhaltsvorschauTables through provide pointers to types in the .NET Framework that usefully complement the functionality that PowerShell provides. For detailed descriptions and documentation, search the official documentation at .
Table : Windows PowerShell ClassDescriptionSystem.Management.Automation.PSObjectRepresents a PowerShell object to which you can add notes, properties, and more.Table : Utility ClassDescriptionSystem.DateTimeRepresents an instant in time, typically expressed as a date and time of day.System.GuidRepresents a globally unique identifier (GUID).System.MathProvides constants and static methods for trigonometric, logarithmic, and other common mathematical functions.System.RandomRepresents a pseudorandom number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness.System.ConvertConverts a base data type to another base data type.System.EnvironmentProvides information about, and means to manipulate, the current environment and platform.System.ConsoleRepresents the standard input, output, and error streams for console applications.System.Text.RegularExpressions.RegexRepresents an immutable regular expression.System.Diagnostics.DebugProvides a set of methods and properties that help debug your code.System.Diagnostics.EventLogProvides interaction with Windows event logs.System.Diagnostics.ProcessProvides access to local and remote processes, and enables you to start and stop local system processes.System.Diagnostics.StopwatchProvides a set of methods and properties that you can use to accurately measure elapsed time.System.Media.SoundPlayerControls playback of a sound from a .wav file.Table : Collections and object utilities ClassDescriptionSystem.ArrayProvides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the Common Language Runtime.System.EnumProvides the base class for enumerations.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 7: WMI Reference
- InhaltsvorschauThe Windows Management Instrumentation (WMI) facilities in Windows offer thousands of classes that provide information of interest to administrators. lists the categories and subcategories covered by WMI and can be used to get a general idea of the scope of WMI classes. provides a selected subset of the most useful WMI classes. For more information about a category, search the official WMI documentation at .
Table : WMI class categories and subcategories CategorySubcategoryComputer System HardwareCooling device, input device, mass storage, motherboard, controller and port, networking device, power, printing, telephony, video, and monitorOperating SystemCOM, desktop, drivers, filesystem, job objects, memory and page files, multimedia audio/visual, networking, operating system events, operating system settings, processes, registry, scheduler jobs, security, services, shares, Start menu, storage, users, Windows NT event log, Windows product activationWMI Service ManagementWMI configuration, WMI managementGeneralInstalled applications, performance counter, security descriptorTable : Selected WMI classes ClassDescriptionWin32_BaseBoardRepresents a baseboard, which is also known as a motherboard or system board.Win32_BIOSRepresents the attributes of the computer system's basic input/output services (BIOS) that are installed on a computer.Win32_BootConfigurationRepresents the boot configuration of a Windows system.Win32_CDROMDriveRepresents a CD-ROM drive on a Windows computer system. Be aware that the name of the drive does not correspond to the logical drive letter assigned to the device.Win32_ComputerSystemRepresents a computer system in a Windows environment.Win32_ProcessorRepresents a device that can interpret a sequence of instructions on a computer running on a Windows operating system. On a multiprocessor computer, one instance of theWin32_Processorclass exists for each processor.Win32_ComputerSystemProductRepresents a product. This includes software and hardware used on this computer system.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 8: Selected COM Objects and Their Uses
- InhaltsvorschauAs an extensibility and administration interface, many applications expose useful functionality through COM objects. While PowerShell handles many of these tasks directly, many COM objects still provide significant value.lists a selection of the COM objects most useful to system administrators.
Table : COM identifiers and descriptions IdentifierDescriptionAccess.ApplicationAllows for interaction and automation of Microsoft Access.Agent.ControlAllows for the control of Microsoft Agent 3D-animated characters.AutoItX3.Control(Nondefault.) Provides access to Windows Automation via theAutoItadministration tool.CEnroll.CEnrollProvides access to certificate enrollment services.CertificateAuthority.RequestProvides access to a request to a certificate authority.COMAdmin.COMAdminCatalogProvides access to and management of the Windows COM+ catalog.Excel.ApplicationAllows for interaction and automation of Microsoft Excel.Excel.SheetAllows for interaction with Microsoft Excel worksheets.HNetCfg.FwMgrProvides access to the management functionality of the Windows Firewall.HNetCfg.HNetShareProvides access to the management functionality of Windows Connection Sharing.HTMLFileAllows for interaction and authoring of a new Internet Explorer document.InfoPath.ApplicationAllows for interaction and automation of Microsoft InfoPath.InternetExplorer.ApplicationAllows for interaction and automation of Microsoft Internet Explorer.IXSSO.QueryAllows for interaction with Microsoft Index Server.IXSSO.UtilProvides access to utilities used along with theIXSSO.Queryobject.LegitCheckControl.LegitCheckProvides access to information about Windows Genuine Advantage status on the current computer.MakeCab.MakeCabProvides functionality to create and manage cabinet (.cab) files.MAPI.SessionProvides access to a MAPI (Messaging Application Programming Interface) session, such as folders, messages, and the address book.Messenger.MessengerAppAllows for interaction and automation of Messenger.Microsoft.FeedsManagerAllows for interaction with the Microsoft RSS feed platform.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 9: .NET String Formatting
- InhaltsvorschauThe format string supported by the format (
-f) operator is a string that contains format items. Each format item takes the form of:{index[,alignment][:formatString]}<index> represents the zero-based index of the item in the object array following the format operator.<alignment> is optional and represents the alignment of the item. A positive number aligns the item to the right of a field of the specified width. A negative number aligns the item to the left of a field of the specified width.<formatString> is optional and formats the item using that type's specific format string syntax.lists the standard numeric format strings. All format specifiers may be followed by a number between 0 and 99 to control the precision of the formatting.Table : Standard numeric format strings Format specifier (Name)DescriptionExampleCorc(Currency)A currency amount.PS >"{0:C}" -f 1.23 $1.23Dord(Decimal)A decimal amount (for integral types). The precision specifier controls the minimum number of digits in the result.PS >"{0:D4}" -f 2 0002Eore(Scientific)Scientific (exponential) notation. The precision specifier controls the number of digits past the decimal point.PS >"{0:E3}" -f [Math]::Pi 3.142E+000Forf(Fixed-point)Fixed point notation. The precision specifier controls the number of digits past the decimal point.PS >"{0:E3}" -f [Math]::Pi 3.142Gorg(General)The most compact representation (between fixed-point and scientific) of the number. The precision specifier controls the number of significant digits.PS >"{0:G3}" -f [Math]::Pi 3.14 PS >"{0:G3}" -f 1mb 1.05E+06Norn(Number)The human readable form of the number, which includes separators between number groups. The precision specifier controls the number of digits past the decimal point.PS >"{0:N4}" -f 1mb 1,048,576.0000Porp(Percent)The number (generally between 0 and 1) represented as a percentage. The precision specifier controls the number of digits past the decimal point.PS >"{0:P4}" -f 0.67 67.0000 %Rorr(Round-trip)The single or double number formatted with a precision that guarantees the string (when parsed) will result in the original number again.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - String Formatting Syntax
- InhaltsvorschauThe format string supported by the format (
-f) operator is a string that contains format items. Each format item takes the form of:{index[,alignment][:formatString]}<index> represents the zero-based index of the item in the object array following the format operator.<alignment> is optional and represents the alignment of the item. A positive number aligns the item to the right of a field of the specified width. A negative number aligns the item to the left of a field of the specified width.<formatString> is optional and formats the item using that type's specific format string syntax.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Standard Numeric Format Strings
- Inhaltsvorschaulists the standard numeric format strings. All format specifiers may be followed by a number between 0 and 99 to control the precision of the formatting.
Table : Standard numeric format strings Format specifier (Name)DescriptionExampleCorc(Currency)A currency amount.PS >"{0:C}" -f 1.23 $1.23Dord(Decimal)A decimal amount (for integral types). The precision specifier controls the minimum number of digits in the result.PS >"{0:D4}" -f 2 0002Eore(Scientific)Scientific (exponential) notation. The precision specifier controls the number of digits past the decimal point.PS >"{0:E3}" -f [Math]::Pi 3.142E+000Forf(Fixed-point)Fixed point notation. The precision specifier controls the number of digits past the decimal point.PS >"{0:E3}" -f [Math]::Pi 3.142Gorg(General)The most compact representation (between fixed-point and scientific) of the number. The precision specifier controls the number of significant digits.PS >"{0:G3}" -f [Math]::Pi 3.14 PS >"{0:G3}" -f 1mb 1.05E+06Norn(Number)The human readable form of the number, which includes separators between number groups. The precision specifier controls the number of digits past the decimal point.PS >"{0:N4}" -f 1mb 1,048,576.0000Porp(Percent)The number (generally between 0 and 1) represented as a percentage. The precision specifier controls the number of digits past the decimal point.PS >"{0:P4}" -f 0.67 67.0000 %Rorr(Round-trip)The single or double number formatted with a precision that guarantees the string (when parsed) will result in the original number again.PS >"{0:R}" -f (1mb/2.0) 524288 PS >"{0:R}" -f (1mb/9.0) 116508.44444444444Xorx(Hexadecimal)The number converted to a string of hexadecimal digits. The case of the specifier controls the case of the resulting hexadecimal digits. The precision specifier controls the minimum number of digits in the resulting string.PS >"{0:X4}" -f 1324 052CEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Custom Numeric Format Strings
- InhaltsvorschauYou may use custom numeric format strings, listed in , to format numbers in ways not supported by the standard format strings.
Table : Custom numeric format strings Format specifier (Name)DescriptionExample0(Zero placeholder)Specifies the precision and width of a number string. Zeroes not matched by digits in the original number are output as zeroes.PS >"{0:00.0}" -f 4.12341234 04.1# (Digit placeholder)Specifies the precision and width of a number string. # symbols not matched by digits in the input number are not output.PS >"{0:##.#}" -f 4.12341234 4.1. (Decimal point)Determines the location of the decimal separator.PS >"{0:##.#}" -f 4.12341234 4.1, (Thousands separator)When placed between a zero or digit placeholder before the decimal point in a formatting string, adds the separator character between number groups.PS >"{0:#,#.#}" -f 1234.121234 1,234.1, (Number scaling)When placed before the literal (or implicit) decimal point in a formatting string, divides the input by 1,000. You may apply this format specifier more than once.PS >"{0:##,,.000}" -f 1048576 1.049% (Percentage placeholder)Multiplies the input by 100 and inserts the percent sign where shown in the format specifier.PS >"{0:%##.000}" -f .68 %68.000E0E+0E-0e0e+0e-0(Scientific notation)Displays the input in scientific notation. The number of zeroes that follow theEdefine the minimum length of the exponent field.PS >"{0:##.#E000}" -f 2.71828 27.2E-001'text' "text"(Literal string)Inserts the provided text literally into the output without affecting formatting.PS >"{0:#.00'##'}" -f 2.71828 2.72##; (Section separator)Allows for conditional formatting. If your format specifier contains no section separators, then the formatting statement applies to all input. If your format specifier contains one separator (creating two sections), then the first section applies to positive numbers and zero. The second section applies to negative numbers. If your format specifier contains two separators (creating three sections), then the sections apply to positive numbers, negative numbers, and zero.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 10: .NET DateTime Formatting
- InhaltsvorschauDateTime format strings convert a
DateTimeobject to one of several standard formats, as listed in .Table : Standard DateTime format strings Format specifier (Name)DescriptionExampled(Short date)The culture's short date format.PS >"{0:d}" -f [DateTime] "01/23/4567" 1/23/4567D(Long date)The culture's long date format.PS >"{0:D}" -f [DateTime] "01/23/4567" Friday, January 23, 4567f(Full date/ short time)Combines the long date and short time format patterns.PS >"{0:f}" -f [DateTime] "01/23/4567" Friday, January 23, 4567 12:00 AMF(Full date/ long time)Combines the long date and long time format patterns.PS >"{0:F}" -f [DateTime] "01/23/4567" Friday, January 23, 4567 12:00:00 AMg(General date/ short time)Combines the short date and short time format patterns.PS >"{0:g}" -f [DateTime] "01/23/4567" 1/23/4567 12:00 AMG(General date/ long time)Combines the short date and long time format patterns.PS >"{0:G}" -f [DateTime] "01/23/4567" 1/23/4567 12:00:00 AMMorm(Month day)The culture'sMonthDayformat.PS >"{0:M}" -f [DateTime] "01/23/4567" January 23o(Round-trip date/time)The date formatted with a pattern that guarantees the string (when parsed) will result in the originalDateTimeagain.PS >"{0:o}" -f [DateTime] "01/23/4567" 4567-01-23T00:00:00.0000000Rorr(RFC1123)The standard RFC1123 format pattern.PS >"{0:R}" -f [DateTime] "01/23/4567" Fri, 23 Jan 4567 00:00:00 GMTs(Sortable)Sortable format pattern. Conforms to ISO 8601 and provides output suitable for sorting.PS >"{0:s}" -f [DateTime] "01/23/4567" 4567-01-23T00:00:00t(Short time)The culture's short time format.PS >"{0:t}" -f [DateTime] "01/23/4567" 12:00 AMT(Long time)The culture's long time format.PS >"{0:T}" -f [DateTime] "01/23/4567" 12:00:00 AMu(Universal sortable)The culture's universal sortableDateTimeformat applied to the UTC equivalent of the input.PS >"{0:u}" -f [DateTime] "01/23/4567" 4567-01-23 00:00:00ZU(Universal)The culture'sFullDate-Timeformat applied to the UTC equivalent of the input.PS >"{0:U}" -f [DateTime] "01/23/4567" Friday, January 23, 4567 8:00:00 AMEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Custom DateTime Format Strings
- InhaltsvorschauYou may use custom
DateTimeformat strings, listed in , to format dates in ways not supported by the standard format strings. Note: Single-character format specifiers are interpreted as a standardDateTimeformatting string unless used with other formatting specifiers.Table : Custom DateTime format strings Format specifierDescriptionExampledDay of the month as a number between 1 and 31. Represents single-digit days without a leading zero.PS >"{0:d dd ddd dddd}" -f [DateTime] "01/02/4567" 2 02 Fri FridayddDay of the month as a number between 1 and 31. Represents single-digit days with a leading zero.PS >"{0:d dd ddd dddd}" -f [DateTime] "01/02/4567" 2 02 Fri FridaydddAbbreviated name of the day of the week.PS >"{0:d dd ddd dddd}" -f [DateTime] "01/02/4567" 2 02 Fri FridayddddFull name of the day of the week.PS >"{0:d dd ddd dddd}" -f [DateTime] "01/02/4567" 2 02 Fri FridayfMost significant digit of the seconds fraction (milliseconds).PS >"{0:f ff fff ffff}" -f [DateTime] "01/02/4567" 0 00 000 0000ffTwo most significant digits of the seconds fraction (milliseconds).PS >"{0:f ff fff ffff}" -f [DateTime] "01/02/4567" 0 00 000 0000fffThree most significant digits of the seconds fraction (milliseconds).PS >"{0:f ff fff ffff}" -f [DateTime] "01/02/4567" 0 00 000 0000ffffFour most significant digits of the seconds fraction (milliseconds).PS >"{0:f ff fff ffff}" -f [DateTime] "01/02/4567" 0 00 000 0000fffffFive most significant digits of the seconds fraction (milliseconds).PS >"{0:fffff ffffff fffffff}" -f [DateTime] "01/02/4567" 00000 000000 0000000ffffffSix most significant digits of the seconds fraction (milliseconds).PS >"{0:fffff ffffff fffffff}" -f [DateTime] "01/02/4567" 00000 000000 0000000fffffffSeven most significant digits of the seconds fraction (milliseconds).PS >"{0:fffff ffffff fffffff}" -f [DateTime] "01/02/4567" 00000 000000 0000000FMost significant digit of the seconds fraction (milliseconds). Displays nothing if the number is zero.PS >"{0:F FF FFF FFFF}" -f [DateTime]::Now 6 66 669 6696 PS >"{0:|F FF FFF FFFF|}" -f [DateTime] "01/02/4567" | |Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Zurück zu Windows PowerShell Pocket Reference
