└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # PowerShell 2 | PowerShell Cheatsheet 3 | 4 | PowerShell for beginners 5 | =================== 6 | ---------- 7 | `This document is getting updated time-to-time. Become a watcher to get updates.` 8 | 9 | PowerShell is a windows command-line shell designed especially for system administrators. It was built on top of the .NET Framework common language runtime (CLR) and the .NET Framework. So, it accepts and returns .NET Framework objects. 10 | 11 | PowerShell works in both **INTERACTIVE** mode and **SCRIPT** mode. It possesses **cmdlet** (pronounced "command-let") for doing pre-defined tasks. 12 | 13 | 14 | ## 1. Why Should I Learn Another Language? 15 | 16 | 17 | _There wont be much gain, without any pain._ I would recommend learning powershell because of the **advantages** that it offers. 18 | > **Advantages:** 19 | 20 | > - Ease in accessing file systems 21 | > - Ability to access other data stores, such as registry and digital signature certificate stores. 22 | > - Open-source and increasing community base 23 | > - Apart from windows, it is extending support for Linux from next release. 24 | > - As PowerShell is tightly coupled with .NET framework. So, .NET objects can be used. 25 | > - Ease in working with all Microsoft products (Office suite, Client OS, Server OS, IIS, Databases, Visual Studio Suite, etc.) 26 | > - Ability to connect to existing windows administrative functionality: 27 | > - WMI 28 | > - Microsoft .NET framework 29 | > - COM (Component Object Model) 30 | > - ADSI (Active Directory Services Interface) 31 | > - Can be used to automate almost any administrative task 32 | 33 | ## 2. About PowerShell 34 | ### 2.1 PowerShell History 35 | Initially, when windows was launched for the first time, it came with the **MS-DOS**. Later, in 1981, batch script (CMD) was introduced, followed by **VBScript** in 1996 and **PowerShell** in 2006. 36 | PowerShell script have **.ps1** as the file extension. Here, the '1' in '.ps1' doesn't refer to the powerShell version; rather refers to the version of the engine, which runs the powerShell. 37 | 38 | ### 2.2 PowerShell Versions 39 | > **PowerShell 1.0** 40 | > - Installed but not enabled on windows Vista and Server 2008 41 | 42 | > **PowerShell 2.0** 43 | > - Installed by default on Windows 7 and Server 2008 R2 44 | > - The PowerShell ISE is installed by default on Windows 7 45 | > - Can be installed on Windows XP and Server 2003 or Higher 46 | 47 | > **PowerShell 3.0** 48 | > - Installed by default on Windows 8 and Server 2012 49 | > - ISE is installed by default on Windows 8 and Server 2012 GUI 50 | > - Can be installed on Windows 7 and Server 2008 or Higher 51 | > - PowerShell Remoting is enabled by default on Server 2012 52 | 53 | There exists [some differences](https://4sysops.com/wiki/differences-between-powershell-versions/) between these versions, and the latest version of PowerShell is **6.0**. 54 | The suitable PowerShell version for windows servers is: 55 | 56 | |PowerShell Version | Release Date | Default Windows Versions | Available Windows Versions| 57 | | --- | --- | --- | ---| 58 | |PowerShell 1.0 | November 2006 | Windows Server 2008 (*) | Windows XP SP2| 59 | | | | |Windows XP SP3 60 | | | | |Windows Server 2003 SP1 61 | | | | |Windows Server 2003 SP2 62 | | | | |Windows Server 2003 R2 63 | | | | |Windows Vista 64 | | | | |Windows Vista SP2 65 | | PowerShell 2.0 | October 2009 | Windows 7| 66 | | | | |Windows Server 2008 R2 (**) Windows XP SP3 67 | | | | |Windows Server 2003 SP2 68 | | | | |Windows Vista SP1 69 | | | | |Windows Vista SP2 70 | | | | |Windows Server 2008 SP1 71 | | | | |Windows Server 2008 SP2 72 | |PowerShell 3.0 | September 2012 | Windows 8| 73 | | | | |Windows Server 2012 Windows 7 SP1 74 | | | | |Windows Server 2008 SP2 75 | | | | |Windows Server 2008 R2 SP1 76 | |PowerShell 4.0 | October 2013 | Windows 8.1| 77 | | | | |Windows Server 2012 R2 Windows 7 SP1 78 | | | | |Windows Server 2008 R2 SP1 79 | | | | |Windows Server 2012 80 | |PowerShell 5.0 |February 2016 |Windows 10 |Windows 8.1| 81 | | | | |Windows Server 2012 R2 82 | 83 | Go to windows menu, and type `Windows PowerShell` (don't choose `Windows PowerShell ISE`) and open it. 84 | 85 | ### 2.3 PowerShell Environment 86 | To get the PowerShell version installed on the machine, type 87 | ```bash 88 | PS C:\> $PSVersionTable 89 | 90 | Name Value 91 | ---- ----- 92 | PSVersion 5.0.10586.672 93 | PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} 94 | BuildVersion 10.0.10586.672 95 | CLRVersion 4.0.30319.42000 96 | WSManStackVersion 3.0 97 | PSRemotingProtocolVersion 2.3 98 | SerializationVersion 1.1.0.1 99 | ``` 100 | Observe that the `PSVersion` which is `5.0` in this case. 101 | 102 | To get the Host details, 103 | ``` 104 | PS C:\> Get-Host 105 | 106 | Name : ConsoleHost 107 | Version : 5.0.10586.672 108 | InstanceId : 7756acf5-225d-40b7-ac79-173bf20eadda 109 | UI : System.Management.Automation.Internal.Host.InternalHostUserInterface 110 | CurrentCulture : en-US 111 | CurrentUICulture : en-US 112 | PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy 113 | DebuggerEnabled : True 114 | IsRunspacePushed : False 115 | Runspace : System.Management.Automation.Runspaces.LocalRunspace 116 | ``` 117 | `$env` is a predefined variable in powershell. It will store the complete windows environment information. 118 | 119 | Printing it barely doesn't result in any information. 120 | ``` 121 | PS C:\> $env 122 | 123 | PS C:\> 124 | ``` 125 | The `$env` variable must be accompanied by the other corresponding variable. 126 | ``` 127 | PS C:\> $env:COMPUTERNAME 128 | UDHAYPC 129 | 130 | PS C:\> $env:USERNAME 131 | UDHAY 132 | 133 | PS C:\> $env:USERDNSDOMAIN 134 | prakash.COM 135 | 136 | PS C:\> $env:USERPROFILE 137 | C:\Users\UDHAY 138 | 139 | PS C:\> $env:ALLUSERSPROFILE 140 | C:\ProgramData 141 | 142 | PS C:\> $env:ComSpec 143 | C:\Windows\system32\cmd.exe 144 | 145 | PS C:\> $env:HOMEPATH 146 | \Users\UDHAY 147 | 148 | PS C:\> $env:HOMEDRIVE 149 | C: 150 | 151 | PS C:\> $env:ProgramFiles 152 | C:\Program Files 153 | 154 | ``` 155 | __NOTE:__ If you dont know all the variables part of it, after `:` type `tab` key to all those variables one-by-one. 156 | 157 | ### 2.4 Support for Other Microsoft languages 158 | PowerShell used a concept called `Aliases` to support commonly used commands in other Microsoft languages like Batch Script (CMD), VBScript, etc. 159 | 160 | Commonly used Batch Script (CMD) commands such as _dir_, _ls_, _cls_, .... are supported in PowerShell. 161 | 162 | ```bash 163 | PS C:\> Clear-Host # same as cls in CMD; clears the screen 164 | ``` 165 | But, they doesn't support those commands extensively. For example, ```dir ``` will work; but not ```dir /A:D```. 166 | 167 | To _explicitly_ run the commands and/or scripts of other language in powershell, 168 | ``` 169 | $command = @' 170 | cmd.exe /C dir /A:D 171 | '@ 172 | 173 | Invoke-Expression -Command:$command 174 | ``` 175 | But, let's ignore this until we understood this language syntax and semantics. 176 | 177 | ### 2.5 Command Structure in PowerShell 178 | PowerShell possesses light-weight commands, called _cmdlets_, to do some specific tasks. 179 | 180 | They use a consistent verb-noun structure, where the verb represents the action and the noun represents the object to operate on. 181 | 182 | PowerShell cmdlets follow consistent naming patterns, ensuring that construction of a command is easy if you know the object that you want to work with. 183 | 184 | All command categories take parameters and arguments. A parameter starts with a hyphen and is used to control the behavior of the command. An argument is a data value consumed by the command. 185 | 186 | A simple PowerShell command has the following syntax: 187 | 188 | ``` 189 | command -parameter1 -parameter2 argument1, argument2 190 | ``` 191 | 192 | To get the list of `approved verbs`, 193 | ``` 194 | PS C:\> Get-Verb 195 | 196 | Verb Group 197 | ---- ----- 198 | Add Common 199 | Clear Common 200 | Close Common 201 | Copy Common 202 | Enter Common 203 | Exit Common 204 | Find Common 205 | Format Common 206 | Get Common 207 | Hide Common 208 | Join Common 209 | Lock Common 210 | Move Common 211 | New Common 212 | Open Common 213 | .... 214 | [Tailored the list] 215 | ``` 216 | The Grouping is done based on their common use. 217 | 218 | Each Windows PowerShell verb is assigned to one of the following groups. 219 | - `Common`: Define generic actions that can apply to almost any cmdlet, such as Add. 220 | - `Communications`: Define actions that apply to communications, such as Connect. 221 | - `Data`: Define actions that apply to data handling, such as Backup. 222 | - `Diagnostic`: Define actions that apply to diagnostics, such as Debug. 223 | - `Lifecycle`: Define actions that apply to the lifecycle of a cmdlet, such as Complete. 224 | - `Security`: Define actions that apply to security, such as Revoke. 225 | - `Other`: Define other types of actions. 226 | 227 | 228 | To get the list of all `nouns`, 229 | ``` 230 | PS C:\> Get-Command –Noun * 231 | 232 | CommandType Name ModuleName 233 | ----------- ---- ---------- 234 | Function Clear-Host 235 | Function Disable-PSTrace PSDiagnostics 236 | Function Disable-PSWSManCombinedTrace PSDiagnostics 237 | Function Disable-WSManTrace PSDiagnostics 238 | Function Enable-PSTrace PSDiagnostics 239 | Function Enable-PSWSManCombinedTrace PSDiagnostics 240 | Function Enable-WSManTrace PSDiagnostics 241 | Function Get-DscConfiguration PSDesiredStateConfiguration 242 | Function Get-DscLocalConfigurationManager PSDesiredStateConfiguration 243 | Function Get-DscResource PSDesiredStateConfiguration 244 | Function Get-FileHash Microsoft.PowerShell.Utility 245 | Function Get-IseSnippet ISE 246 | Function Get-LogProperties PSDiagnostics 247 | Function Get-Verb 248 | ... 249 | [Tailored the list] 250 | ``` 251 | Observe that `Get-Verb` too is a noun. 252 | 253 | Also, there is another command named `Get-Command` to get a particular set of commands. 254 | 255 | To get all the command in the current user scope in a particular windows machine, 256 | ``` 257 | PS C:\> Get-Command -All 258 | 259 | CommandType Name ModuleName 260 | ----------- ---- ---------- 261 | Alias cat -> Get-Content 262 | Alias cd -> Set-Location 263 | Alias chdir -> Set-Location 264 | Alias clc -> Clear-Content 265 | Alias clear -> Clear-Host 266 | Alias clhy -> Clear-History 267 | Alias history -> Get-History 268 | Alias icim -> CimCmdlets 269 | Function Get-IseSnippet ISE 270 | Function Get-LogProperties PSDiagnostics 271 | Function Get-User Carbon 272 | Function Get-Verb 273 | Function Invoke-AsWorkflow PSWorkflowUtility 274 | Function New-IseSnippet ISE 275 | Filter more 276 | Cmdlet Set-ADAccountControl ActiveDirectory 277 | Cmdlet Set-Alias Microsoft.PowerShell.Utility 278 | Cmdlet Set-AppLockerPolicy AppLocker 279 | Cmdlet Set-CimInstance CimCmdlets 280 | Cmdlet Set-ExecutionPolicy Microsoft.PowerShell.Security 281 | Cmdlet Set-JobTrigger PSScheduledJob 282 | Cmdlet Set-MsolAdministrativeUnit MSonline 283 | Cmdlet Set-MsolAdministrativeUnit MSOnlineExtended 284 | Cmdlet Start-BitsTransfer BitsTransfer 285 | Cmdlet Start-DscConfiguration PSDesiredStateConfiguration 286 | Cmdlet Test-PSSessionConfigurationFile Microsoft.PowerShell.Core 287 | Cmdlet Test-WSMan Microsoft.WSMan.Management 288 | Cmdlet Unlock-ADAccount ActiveDirectory 289 | Cmdlet Write-EventLog Microsoft.Powershell.Management 290 | Cmdlet Write-Host Microsoft.PowerShell.Utility 291 | ... 292 | [Tailored the list] 293 | ``` 294 | Also, the commands can be retrieved in terms of `Name`, `Verb`, `Noun`, `Module`,... 295 | 296 | PowerShell also possesses a strong and unique feature called `piping`, which we can discuss under the `piping` section. 297 | 298 | ### 2.6 Getting Help in PowerShell 299 | Once the command to work is known using `Get-Command`, the usage and syntax of that particular cmdlet can be learned using `Get-Help`. 300 | 301 | To get the help for a particular cmdlet, say `clear-Host`, 302 | ``` 303 | PS C:\> Get-Help -Name clear-Host 304 | 305 | NAME 306 | Clear-Host 307 | 308 | SYNOPSIS 309 | Clears the display in the host program. 310 | 311 | 312 | SYNTAX 313 | Clear-Host [] 314 | 315 | 316 | DESCRIPTION 317 | The Clear-Host function removes all text from the current display, including commands and output that might have accumulated. When complete, it 318 | displays the command prompt. You can use the function name or its alias, CLS. 319 | 320 | Clear-Host affects only the current display. It does not delete saved results or remove any items from the session. Session-specific items, such 321 | as variables and functions, are not affected by this function. 322 | 323 | Because the behavior of the Clear-Host function is determined by the host program, Clear-Host might work differently in different host programs. 324 | 325 | 326 | RELATED LINKS 327 | Online version: http://technet.microsoft.com/library/hh852689(v=wps.630).aspx 328 | Get-Host 329 | Out-Host 330 | Read-Host. Write-Host 331 | 332 | REMARKS 333 | To see the examples, type: "get-help Clear-Host -examples". 334 | For more information, type: "get-help Clear-Host -detailed". 335 | For technical information, type: "get-help Clear-Host -full". 336 | For online help, type: "get-help Clear-Host -online" 337 | 338 | ``` 339 | Observe the 6 fields (`Name`, `Synopsis`, `syntax`, `Description`, `Related Links`, `Remarks`). These are common for all the results of `get-Help` 340 | 341 | If usage by example is needed, 342 | ``` 343 | PS C:\> Get-Help -Name clear-Host -Examples 344 | 345 | NAME 346 | Clear-Host 347 | 348 | SYNOPSIS 349 | Clears the display in the host program. 350 | 351 | -------------------------- EXAMPLE 1 -------------------------- 352 | 353 | C:\PS>cls 354 | 355 | # Before 356 | 357 | PS C:\>Get-Process 358 | 359 | Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName 360 | ------- ------ ----- ----- ----- ------ -- ----------- 361 | 843 33 14428 22556 99 17.41 1688 CcmExec 362 | 44 6 2196 4964 52 0.23 692 conhost 363 | 646 12 2332 4896 49 1.12 388 csrss 364 | 189 11 2860 7084 114 0.66 2896 csrss 365 | 78 11 1876 4008 42 0.22 4000 csrss 366 | 76 7 1848 5064 54 0.08 1028 dwm 367 | 610 41 23952 44048 208 4.40 2080 explorer 368 | 0 0 0 24 0 0 Idle 369 | 182 32 7692 15980 91 0.23 3056 LogonUI 370 | 186 25 7832 16068 91 0.27 3996 LogonUI 371 | 1272 32 11512 20432 58 25.07 548 lsass 372 | 267 10 3536 6736 34 0.80 556 lsm 373 | 137 17 3520 7472 61 0.05 1220 msdtc 374 | 447 31 70316 84476 201 1,429.67 836 MsMpEng 375 | 265 18 7136 15628 134 2.20 3544 msseces 376 | 248 16 6476 4076 76 0.22 1592 NisSrv 377 | 368 25 61312 65508 614 1.78 848 powershell 378 | 101 8 2304 6624 70 0.64 3648 rdpclip 379 | 258 15 6804 12156 50 2.65 536 services 380 | ... 381 | 382 | PS C:\> cls 383 | #After 384 | 385 | PS C:> 386 | 387 | 388 | Description 389 | 390 | ----------- 391 | 392 | This command uses the CLS alias of Clear-Host to clear the current display. 393 | ``` 394 | To update the help (ensure proper internet connect, as it downloads from PowerShell site), 395 | ``` 396 | PS C:\> Update-Help 397 | 398 | PS C:\> 399 | 400 | ``` 401 | ### 2.7 Importance of Execution Policy 402 | By default, the `Execution Policy` is set to 'Restricted'. It is recommended to change it to `Resmote Signed`. 403 | 404 | |Execution Policy | It's importance | 405 | | --- | --- | 406 | |Restricted | You can run commands, but you can't run scripts | 407 | |All Signed | You can run commands, but you can only run digitally signed scripts| 408 | |Remote Signed | You can run commands, local scripts and only scripts downloaded from the internet if they are digitally signed| 409 | |Unrestricted | You can run commands and scripts with or without digital signatures| 410 | |Bypass | Nothing is blocked and there are no warnings or prompts| 411 | 412 | In windows menu, type `Windows PowerShell`, right-click on it and click `Run as Administrator`. Then type the below command to the `ExecutionPolicy` on that machine for that user. 413 | ``` 414 | PS C:\> Get-ExecutionPolicy 415 | Restricted 416 | ``` 417 | By default, it will give the execution policy associated with the user who executed this command. 418 | ``` 419 | PS C:\> Get-ExecutionPolicy -Scope CurrentUser 420 | Restricted 421 | ``` 422 | Also, replace the `CurrentUser` in the above command with a specific username on that machine, to know the execution policy associated with that user. 423 | 424 | To Change the execution policy, to say `unrestricted`, 425 | ``` 426 | PS C:\> Set-ExecutionPolicy -ExecutionPolicy "unrestricted" -Scope CurrentUser 427 | 428 | Execution Policy Change 429 | The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose 430 | you to the security risks described in the about_Execution_Policies help topic at 431 | http://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy? 432 | [Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y 433 | PS C:\> 434 | 435 | ``` 436 | ## 3. Working with PowerShell 437 | ### 3.1 Getting Started 438 | As it is customary to start with 'Hello world' when learning any language, Lets start with it. 439 | 440 | ```bash 441 | 442 | PS C:\> Write-Host "Hello World!" 443 | Hello World! 444 | PS C:\> Write-Host 'Hello World!' 445 | Hello World! 446 | PS C:\> 'Hello World!' 447 | Hello World! 448 | ``` 449 | Observe that the string 'Hello World!' is printed on the console in three ways. But, single (') and double(") quotes won't work exactly same in all cases. we can discuss about it in later section. 450 | 451 | Single-line comment 452 | ```bash 453 | PS C:\> # Comments begin with a # (aka hashtag or pound sign) 454 | PS C:\> 455 | ``` 456 | Multi-line comment 457 | ``` 458 | PS C:\> <# 459 | >> Comment blocks use angle brackets with comment sign 460 | >> They can be multiline 461 | >> #> 462 | PS C:\> 463 | ``` 464 | Regions are not logical, but representational blocks of code. 465 | 466 | __NOTE:__ Regions have their importance in powershell ISE only. They are used to divide the script into logical code blocks. 467 | 468 | ``` 469 | PS C:\> #region 470 | PS C:\> # Put your code here 471 | PS C:\> #endregion 472 | PS C:\> 473 | ``` 474 | These regions can also be named. 475 | ``` 476 | PS C:\> #region The Region Title is Optional 477 | PS C:\> 478 | PS C:\> # some code here 479 | PS C:\> 480 | PS C:\> #endregion The Region Title is Optional 481 | PS C:\> 482 | ``` 483 | 484 | **Special Characters in PowerShell** 485 | 486 | |Special Character | Meaning| 487 | | --- | --- | 488 | |" | The beginning( or end) of quoted text. Used to represent strings | 489 | |' | The beginning( or end) of quoted text. Used to represent strings. special characters lose their significance within single quotes| 490 | |# | The beginning of a comment | 491 | |$ | The beginning of a variable | 492 | |& | Reserved for future use | 493 | |()| Parentheses used for subexpressions| 494 | |{}| Script block | 495 | |; | Statement Separator | 496 | || | Pipeline seperator| 497 | |` | Escape Character| 498 | |? | Alias operator for Where-Object| 499 | |% | Alias Operator for for-loop| 500 | 501 | All variables start with a $. 502 | ``` 503 | PS C:\> $hi = "Hello World" 504 | ``` 505 | Printing the value in variable 506 | ``` 507 | PS C:\> $hi 508 | Hello World 509 | ``` 510 | This is a shortcut to Write-Host 511 | ``` 512 | PS C:\> Write-Host $hi 513 | Hello World 514 | ``` 515 | Variables are objects, and to get their data type, 516 | ``` 517 | PS C:\> $hi.GetType() 518 | 519 | IsPublic IsSerial Name BaseType 520 | -------- -------- ---- -------- 521 | True True String System.Object 522 | ``` 523 | 524 | __GetType()__ is one method, applicable on '$hi' object 525 | 526 | To display all the members of this variable (object) 527 | ``` 528 | PS C:\> $hi | Get-Member 529 | 530 | 531 | TypeName: System.String 532 | 533 | Name MemberType Definition 534 | ---- ---------- ---------- 535 | Clone Method System.Object Clone(), System.Object ICloneable.Clone() 536 | CompareTo Method int CompareTo(System.Object value), int CompareTo(string strB), int IComparab... 537 | Contains Method bool Contains(string value) 538 | CopyTo Method void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int co... 539 | EndsWith Method bool EndsWith(string value), bool EndsWith(string value, System.StringCompari... 540 | Equals Method bool Equals(System.Object obj), bool Equals(string value), bool Equals(string... 541 | GetEnumerator Method System.CharEnumerator GetEnumerator(), System.Collections.IEnumerator IEnumer... 542 | GetHashCode Method int GetHashCode() 543 | GetType Method type GetType() 544 | GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode() 545 | IndexOf Method int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf... 546 | IndexOfAny Method int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), i... 547 | Insert Method string Insert(int startIndex, string value) 548 | IsNormalized Method bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normaliz... 549 | LastIndexOf Method int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int... 550 | LastIndexOfAny Method int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startI... 551 | Normalize Method string Normalize(), string Normalize(System.Text.NormalizationForm normalizat... 552 | PadLeft Method string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar) 553 | PadRight Method string PadRight(int totalWidth), string PadRight(int totalWidth, char padding... 554 | Remove Method string Remove(int startIndex, int count), string Remove(int startIndex) 555 | Replace Method string Replace(char oldChar, char newChar), string Replace(string oldValue, s... 556 | Split Method string[] Split(Params char[] separator), string[] Split(char[] separator, int... 557 | StartsWith Method bool StartsWith(string value), bool StartsWith(string value, System.StringCom... 558 | Substring Method string Substring(int startIndex), string Substring(int startIndex, int length) 559 | ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider) 560 | ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider) 561 | ToChar Method char IConvertible.ToChar(System.IFormatProvider provider) 562 | ToCharArray Method char[] ToCharArray(), char[] ToCharArray(int startIndex, int length) 563 | ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatProvider provider) 564 | ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatProvider provider) 565 | ToDouble Method double IConvertible.ToDouble(System.IFormatProvider provider) 566 | ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvider provider) 567 | ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider provider) 568 | ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider provider) 569 | ToLower Method string ToLower(), string ToLower(cultureinfo culture) 570 | ToLowerInvariant Method string ToLowerInvariant() 571 | ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider provider) 572 | ToSingle Method float IConvertible.ToSingle(System.IFormatProvider provider) 573 | ToString Method string ToString(), string ToString(System.IFormatProvider provider), string I... 574 | ToType Method System.Object IConvertible.ToType(type conversionType, System.IFormatProvider... 575 | ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvider provider) 576 | ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvider provider) 577 | ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvider provider) 578 | ToUpper Method string ToUpper(), string ToUpper(cultureinfo culture) 579 | ToUpperInvariant Method string ToUpperInvariant() 580 | Trim Method string Trim(Params char[] trimChars), string Trim() 581 | TrimEnd Method string TrimEnd(Params char[] trimChars) 582 | TrimStart Method string TrimStart(Params char[] trimChars) 583 | Chars ParameterizedProperty char Chars(int index) {get;} 584 | Length Property int Length {get;} 585 | ``` 586 | Using some of those members 587 | ``` 588 | PS C:\> $hi.ToLower() 589 | hello world 590 | 591 | PS C:\> $hi.ToUpper() 592 | HELLO WORLD 593 | 594 | PS C:\> $hi.Length # No () as it is Property; not method 595 | 11 596 | 597 | PS C:\> $hi.Replace("World", "PowerShell") 598 | Hello PowerShell 599 | 600 | ``` 601 | Types are mutable. Their data types can also be changed 602 | ``` 603 | 604 | PS C:\> $hi = 5 605 | 606 | PS C:\> $hi.GetType() 607 | 608 | IsPublic IsSerial Name BaseType 609 | -------- -------- ---- -------- 610 | True True Int32 System.ValueType 611 | PS C:\> $hi | Get-Member 612 | 613 | 614 | TypeName: System.Int32 615 | 616 | Name MemberType Definition 617 | ---- ---------- ---------- 618 | CompareTo Method int CompareTo(System.Object value), int CompareTo(int value), int IComparable.CompareTo(System.Obj... 619 | Equals Method bool Equals(System.Object obj), bool Equals(int obj), bool IEquatable[int].Equals(int other) 620 | GetHashCode Method int GetHashCode() 621 | GetType Method type GetType() 622 | GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode() 623 | ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider) 624 | ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider) 625 | ToChar Method char IConvertible.ToChar(System.IFormatProvider provider) 626 | ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatProvider provider) 627 | ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatProvider provider) 628 | ToDouble Method double IConvertible.ToDouble(System.IFormatProvider provider) 629 | ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvider provider) 630 | ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider provider) 631 | ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider provider) 632 | ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider provider) 633 | ToSingle Method float IConvertible.ToSingle(System.IFormatProvider provider) 634 | ToString Method string ToString(), string ToString(string format), string ToString(System.IFormatProvider provider... 635 | ToType Method System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider) 636 | ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvider provider) 637 | ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvider provider) 638 | ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvider provider) 639 | ``` 640 | Variables can also be **strongly-typed**. 641 | ``` 642 | PS C:\> [System.Int32]$myint = 42 643 | 644 | PS C:\> $myint 645 | 42 646 | 647 | PS C:\> $myint.GetType() 648 | 649 | IsPublic IsSerial Name BaseType 650 | -------- -------- ---- -------- 651 | True True Int32 System.ValueType 652 | PS C:\> $myint = "This won't work" 653 | Cannot convert value "This won't work" to type "System.Int32". Error: "Input string was not in a correct format." 654 | At line:1 char:1 655 | + $myint = "This won't work" 656 | + ~~~~~~~~~~~~~~~~~~~~~~~~~~ 657 | + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException 658 | + FullyQualifiedErrorId : RuntimeException 659 | ``` 660 | There are shortcuts for most .NET data types. 661 | ``` 662 | PS C:\> [int] $myotherint = 42 663 | 664 | PS C:\> $myotherint.GetType() 665 | 666 | IsPublic IsSerial Name BaseType 667 | -------- -------- ---- -------- 668 | True True Int32 System.ValueType 669 | PS C:\> [string] $mystring="PowerShell" 670 | 671 | PS C:\> $mystring.GetType() 672 | 673 | IsPublic IsSerial Name BaseType 674 | -------- -------- ---- -------- 675 | True True String System.Object 676 | ``` 677 | Others include short, float, decimal, single, bool, byte, etc. 678 | 679 | Not just variables have types - so do static values. 680 | ``` 681 | PS C:\> "PowerShell Rocks".GetType() 682 | 683 | IsPublic IsSerial Name BaseType 684 | -------- -------- ---- -------- 685 | True True String System.Object 686 | 687 | ``` 688 | Accessing methods on objects 689 | ``` 690 | PS C:\> "PowerShell Rocks".ToUpper() 691 | POWERSHELL ROCKS 692 | 693 | PS C:\> "PowerShell Rocks".Contains("PowerShell") 694 | True 695 | ``` 696 | For non-strings you need to wrap in () so PS will evaluate as an object. 697 | ``` 698 | PS C:\> (33).GetType() 699 | 700 | IsPublic IsSerial Name BaseType 701 | -------- -------- ---- -------- 702 | True True Int32 System.ValueType 703 | 704 | ``` 705 | #### Logical Operations 706 | 707 | |Operator | Importance | 708 | | --- | --- | 709 | | -eq | Equal to | 710 | | -ne | Not equal to| 711 | | -lt | Less Than| 712 | | -gt | Greater then| 713 | | -le | Less than or equal to| 714 | | -ge | Greater then or equal to| 715 | | 716 | | -in | See if value in an array| 717 | | -Like | Like wildcard pattern matching| 718 | | -NotLike | Not Like | 719 | | -Match | Matches based on regular expressions| 720 | | -NotMatch | Non-Matches based on regular expressions| 721 | ``` 722 | PS C:\> $var = 33 723 | 724 | PS C:\> $var -gt 30 725 | True 726 | 727 | PS C:\> $var -lt 30 728 | False 729 | 730 | PS C:\> $var -eq 33 731 | True 732 | ``` 733 | Calculations are like any other language. 734 | ``` 735 | PS C:\> $var = 3 * 11 # Also uses +, -, and / 736 | 737 | PS C:\> $var 738 | 33 739 | ``` 740 | Supports post unary operators ++ and -- 741 | ``` 742 | PS C:\> $var++ 743 | 744 | PS C:\> $var 745 | 34 746 | ``` 747 | And pre unary operators as well 748 | ``` 749 | PS C:\> ++$var 750 | 751 | PS C:\> $var 752 | 35 753 | 754 | PS C:\> $var = 33 755 | 756 | PS C:\> $post = $var++ 757 | 758 | PS C:\> write-Host $post, $var 759 | 33 34 760 | 761 | PS C:\> 762 | PS C:\> $var = 33 763 | 764 | PS C:\> $pre = ++$var 765 | 766 | PS C:\> write-Host $pre, $var 767 | 34 34 768 | ``` 769 | Be __cautious__ of __Implicit__ Type Conversions 770 | ``` 771 | PS C:\> "42" -eq 42 772 | True 773 | 774 | PS C:\> 42 -eq "42" 775 | True 776 | ``` 777 | Whatever is on the right is converted to the data type on the left can lead to some odd conversions. 778 | ``` 779 | PS C:\> 42 -eq "042" # True because the string on the right is coverted to an int 780 | True 781 | 782 | PS C:\> "042" -eq 42 # False because int on the right is converted to a string 783 | False 784 | ``` 785 | #### Built in variables 786 | ```bash 787 | PS C:\> # Booleans ( False and true) 788 | 789 | PS C:\> $false 790 | False 791 | 792 | PS C:\> $true 793 | True 794 | 795 | PS C:\> $NULL # null type 796 | 797 | PS C:\> Write-Host $NuLL 798 | ``` 799 | Observe that nothing is display; even methods like GetType() doesn't work on this object. 800 | 801 | To get the current working directory, 802 | ``` 803 | PS C:\> $pwd 804 | 805 | Path 806 | ---- 807 | C:\ 808 | ``` 809 | To get the Users Home Directory, 810 | ``` 811 | PS C:\> $Home 812 | C:\Users\praud01 813 | ``` 814 | Information about a users scripting environment 815 | ``` 816 | PS C:\> $host # It is alias for Get-Host 817 | 818 | 819 | Name : Windows PowerShell ISE Host 820 | Version : 5.0.10586.672 821 | InstanceId : 4e61fcaa-4155-4b95-aaa9-1b9c3186ed82 822 | UI : System.Management.Automation.Internal.Host.InternalHostUserInterface 823 | CurrentCulture : en-US 824 | CurrentUICulture : en-US 825 | PrivateData : Microsoft.PowerShell.Host.ISE.ISEOptions 826 | DebuggerEnabled : True 827 | IsRunspacePushed : False 828 | Runspace : System.Management.Automation.Runspaces.LocalRunspace 829 | 830 | PS C:\> 831 | 832 | PS C:\> $PID # It results the process ID 833 | 12844 834 | ``` 835 | Info about the current version of Powershell 836 | ``` 837 | PS C:\> $PSVersionTable 838 | 839 | Name Value 840 | ---- ----- 841 | PSVersion 5.0.10586.672 842 | PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} 843 | BuildVersion 10.0.10586.672 844 | CLRVersion 4.0.30319.42000 845 | WSManStackVersion 3.0 846 | PSRemotingProtocolVersion 2.3 847 | SerializationVersion 1.1.0.1 848 | 849 | 850 | 851 | PS C:\> $_ # Current Object; Used in loops to get the iterating object. 852 | 853 | PS C:\> # Useful, mainly, in loops and exceptions 854 | 855 | PS C:\> Set-Location "C:\Python27\Scripts" 856 | 857 | PS C:\Python27\Scripts> # set-Location works in the same way as chdir 858 | 859 | PS C:\Python27\Scripts> Get-ChildItem | Where-Object {$_.Name -like "*.cmd"} 860 | 861 | 862 | Directory: C:\Python27\Scripts 863 | 864 | 865 | Mode LastWriteTime Length Name 866 | ---- ------------- ------ ---- 867 | -a---- 08-Mar-17 4:00 AM 1432 aws.cmd 868 | -a---- 08-Mar-17 4:05 AM 24 hjson.cmd 869 | -a---- 24-Jan-17 5:59 PM 151 wmitest.cmd 870 | 871 | 872 | 873 | PS C:\Python27\Scripts> set-location c:\ 874 | 875 | PS C:\> 876 | ``` 877 | #### Using the *-Variable cmdlets 878 | ```bash 879 | PS C:\> # Normal variable usage 880 | 881 | PS C:\> $normal = 33 882 | 883 | PS C:\> $normal 884 | 33 885 | 886 | PS C:\> $text = "In The Morning" 887 | 888 | PS C:\> $text 889 | In The Morning 890 | 891 | PS C:\> # Long version of $var1 = 33 892 | 893 | PS C:\> New-Variable -Name var1 -Value 33 894 | 895 | PS C:\> $var1 896 | 33 897 | ``` 898 | __NOTE:__ If you try to use New-Variable and it already exists, you get an error. 899 | 900 | Try again with $var1 already existing. 901 | ``` 902 | PS C:\> New-Variable -Name var1 -Value 99 903 | New-Variable : A variable with name 'var1' already exists. 904 | At line:1 char:1 905 | + New-Variable -Name var1 -Value 99 906 | + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 907 | + CategoryInfo : ResourceExists: (var1:String) [New-Variable], SessionStateException 908 | + FullyQualifiedErrorId : VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand 909 | 910 | 911 | PS C:\> $var1 912 | 33 913 | 914 | PS C:\> # Displays the variable and it's value 915 | 916 | PS C:\> Get-Variable var -valueonly 917 | 34 918 | 919 | PS C:\> Get-Variable var 920 | 921 | Name Value 922 | ---- ----- 923 | var 34 924 | 925 | PS C:\> Get-Variable # Without params it shows all variables 926 | 927 | Name Value 928 | ---- ----- 929 | $ var 930 | ? True 931 | ^ Get-Variable 932 | APM_DATAPOINT_SOURCE public class APM_DATAPOINT_CLASS {... 933 | args {} 934 | ATC_BASIC_ATTRIB_LIST {name, applicationName, backendName, components...} 935 | ATC_DO_NOT_PUBLISH_ATTRIB_LIST {name, applicationName, backendName, components...} 936 | AWS_APM_XML_FILE \DefaultValues.xml 937 | AWS_GLOBAL_VAR_FILE \AWSGlobalVariables.ps1 938 | btn System.Windows.Forms.Button, Text: 939 | CLWORKSTATION_JAR_PATH \CLWorkstation.jar 940 | CONFIG_CLASS_SOURCE public class CONFIG_CLASS {... 941 | ConfirmPreference High 942 | ConsoleFileName 943 | CW_ALARM_SOURCE public class CW_ALARM_CLASS {... 944 | CW_METRIC_SOURCE public class CW_METRIC_CLASS {... 945 | DebugPreference SilentlyContinue 946 | EC2_CLASS_SOURCE public class EC2_CLASS {... 947 | Error {A variable with name 'var1' already exists., A variable with name 'var' already exists., ... 948 | ErrorActionPreference Continue 949 | ErrorView NormalView 950 | ExecutionContext System.Management.Automation.EngineIntrinsics 951 | false False 952 | foreach 953 | form System.Windows.Forms.Form, Text: 954 | FormatEnumerationLimit 4 955 | hi 5 956 | HOME C:\Users\praud01 957 | Host System.Management.Automation.Internal.Host.InternalHost 958 | i 22 959 | InformationPreference SilentlyContinue 960 | input System.Collections.ArrayList+ArrayListEnumeratorSimple 961 | Matches {0} 962 | MaximumAliasCount 4096 963 | MaximumDriveCount 4096 964 | MaximumErrorCount 256 965 | MaximumFunctionCount 4096 966 | MaximumHistoryCount 4096 967 | MaximumVariableCount 4096 968 | myint 42 969 | MyInvocation System.Management.Automation.InvocationInfo 970 | myotherint 42 971 | mystring PowerShell 972 | NestedPromptLevel 0 973 | normal 33 974 | null 975 | OutputEncoding System.Text.SBCSCodePageEncoding 976 | path 977 | PID 12844 978 | Playlisturl https://www.youtube.com/watch?v=yKstEJKdc4o 979 | post 33 980 | pre 34 981 | processName 982 | profile C:\Users\praud01\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1 983 | ProgressPreference Continue 984 | PSBoundParameters {} 985 | PSCommandPath 986 | PSCulture en-US 987 | PSDefaultParameterValues {} 988 | PSEmailServer 989 | PSHOME C:\Windows\System32\WindowsPowerShell\v1.0 990 | psISE Microsoft.PowerShell.Host.ISE.ObjectModelRoot 991 | PSScriptRoot 992 | PSSessionApplicationName wsman 993 | PSSessionConfigurationName http://schemas.microsoft.com/powershell/Microsoft.PowerShell 994 | PSSessionOption System.Management.Automation.Remoting.PSSessionOption 995 | PSUICulture en-US 996 | psUnsupportedConsoleApplica... {wmic, wmic.exe, cmd, cmd.exe...} 997 | PSVersionTable {PSVersion, PSCompatibleVersions, BuildVersion, CLRVersion...} 998 | PWD C:\ 999 | ShellId Microsoft.PowerShell 1000 | StackTrace at CallSite.Target(Closure , CallSite , Object )... 1001 | talkIt System.__ComObject 1002 | text In The Morning 1003 | true True 1004 | var 34 1005 | var1 33 1006 | VerbosePreference SilentlyContinue 1007 | video @{innerText=9:53; URL=http://www.youtube.com/watch?v=6VK4TN6Umfk} 1008 | VideoUrls {@{innerText=5:08; URL=http://www.youtube.com/watch?v=GpLUAhoj9XQ}, @{innerText=4:19; URL=... 1009 | WarningPreference Continue 1010 | WhatIfPreference False 1011 | XML_CONFIG_OBJECT CONFIG_CLASS 1012 | ``` 1013 | Assigning a new value to an existing variable 1014 | 1015 | Method 1: 1016 | ``` 1017 | PS C:\> $var1 = "In The Morning" 1018 | ``` 1019 | Method 2: 1020 | ``` 1021 | PS C:\> Set-Variable -Name var1 -Value "In The Morning" 1022 | 1023 | PS C:\> $var1 1024 | In The Morning 1025 | 1026 | PS C:\> Set-Variable -Name var99 -Value "In The Morning" 1027 | ``` 1028 | Observe that set-variable works on objects that aren't created yet. 1029 | 1030 | To clear the contents of a variable, 1031 | ``` 1032 | PS C:\> Clear-Variable -Name var1 # Same as $var1 = $null 1033 | 1034 | PS C:\> $var1 1035 | 1036 | PS C:\> 1037 | 1038 | ``` 1039 | To set the variable to null object, 1040 | ``` 1041 | PS C:\> $var1 -eq $null 1042 | True 1043 | 1044 | ``` 1045 | Even though the object contains null, it still exists. 1046 | ``` 1047 | PS C:\> Get-Variable var1 1048 | 1049 | Name Value 1050 | ---- ----- 1051 | var1 1052 | 1053 | ``` 1054 | ## 4. Working with Strings 1055 | String Quoting 1056 | ```bash 1057 | PS C:\> "This is a string" 1058 | This is a string 1059 | PS C:\> 'This is a string too!' 1060 | This is a string too! 1061 | ``` 1062 | Mixed quoted 1063 | ``` 1064 | PS C:\> 'I just wanted to say "Hello World", OK?' 1065 | I just wanted to say "Hello World", OK? 1066 | PS C:\> "I can't believe how cool Powershell is!" 1067 | I can't believe how cool Powershell is! 1068 | ``` 1069 | You can also double quote to get quotes in strings 1070 | ``` 1071 | PS C:\> "I just wanted to say ""Hello World"", OK?" 1072 | I just wanted to say "Hello World", OK? 1073 | PS C:\> 'I can''t believe how cool Powershell is!' 1074 | I can't believe how cool Powershell is! 1075 | ``` 1076 | Escape Sequences - use the backtick ` 1077 | 1078 | backspace `b (does not work in ISE, only the regular script window) 1079 | ``` 1080 | PS C:\> "Power`bShell" 1081 | PoweShell 1082 | ``` 1083 | newline `n 1084 | ``` 1085 | PS C:\> "Power`nShell" 1086 | Power 1087 | Shell 1088 | ``` 1089 | carriage return `r (doesn't really show anything) 1090 | ``` 1091 | PS C:\> "Power`rShell" 1092 | Shell 1093 | ``` 1094 | crlf `r`n 1095 | ``` 1096 | PS C:\> "Power`r`nShell" 1097 | Power 1098 | Shell 1099 | ``` 1100 | tabs 1101 | ``` 1102 | PS C:\> "Power`tShell" 1103 | Power Shell 1104 | ``` 1105 | .Replace is case-sensitive 1106 | ``` 1107 | PS C:\> 'Hello wOrld'.Replace('o', '1') 1108 | Hell1 wOrld 1109 | ``` 1110 | -Replace is case-insentive 1111 | ``` 1112 | PS C:\> 'Hello wOrld' -Replace 'o', '1' 1113 | Hell1 w1rld 1114 | ``` 1115 | But, we need to be careful when working with special characters. 1116 | ``` 1117 | PS C:\> 'Hello wOrld.'.Replace('.', '1') # Replaces only the dot(.) character 1118 | Hello wOrld1 1119 | PS C:\> 'Hello wOrld.' -Replace '.', '1' # Replaced the complete string. Assumes '.' as regex character 1120 | 111111111111 1121 | PS C:\> 1122 | PS C:\> 'Hello wOrld.' -Replace [Regex]::Escape('.'), '1' # To escape a regex character 1123 | Hello wOrld1 1124 | PS C:\> 'Hello wOrld.' -Replace '\.', '1' # Regex characters can also be escaped with '\' 1125 | Hello wOrld1 1126 | PS C:\> 'Hello wOrld\' -Replace '\\', '1' # '\' character will be escaped with another '\' 1127 | Hello wOrld1 1128 | ``` 1129 | `Here Strings` are used when working with large blocks of text. 1130 | ``` 1131 | PS C:\> $heretext = @" 1132 | >> Some text here 1133 | >> Some more here 1134 | >> a bit more 1135 | >> 1136 | >> a blank line above 1137 | >> "@ 1138 | PS C:\> $heretext 1139 | Some text here 1140 | Some more here 1141 | a bit more 1142 | 1143 | a blank line above 1144 | ``` 1145 | The @ and quote must be last on starting line then first on ending line, also works with single quotes. 1146 | ``` 1147 | PS C:\> $moreheretext = @' 1148 | >> Here we go again 1149 | >> another line here 1150 | >> let's indent this 1151 | >> 1152 | >> a blank line above 1153 | >> '@ 1154 | ``` 1155 | Note how the nested ' is handled OK, no double quoting needed. 1156 | ``` 1157 | PS C:\> $moreheretext 1158 | Here we go again 1159 | another line here 1160 | let's indent this 1161 | 1162 | a blank line above 1163 | PS C:\> 1164 | ``` 1165 | To understand the importance of here strings, lets work with a multiple line string. 1166 | 1167 | Without here strings 1168 | ``` 1169 | PS C:\> $sql = 'SELECT col1' ` 1170 | >> + ' , col2' ` 1171 | >> + ' , col3' ` 1172 | >> + ' FROM someTable ' ` 1173 | >> + ' WHERE col1 = ''a value'' ' 1174 | PS C:\> 1175 | PS C:\> $sql 1176 | SELECT col1 , col2 , col3 FROM someTable WHERE col1 = 'a value' 1177 | ``` 1178 | With here strings 1179 | ``` 1180 | PS C:\> $sql = @' 1181 | >> SELECT col1 1182 | >> , col2 1183 | >> , col3 1184 | >> FROM someTable 1185 | >> WHERE col1 = 'a value' 1186 | >> '@ 1187 | PS C:\> $sql 1188 | SELECT col1 1189 | , col2 1190 | , col3 1191 | FROM someTable 1192 | WHERE col1 = 'a value' 1193 | ``` 1194 | #### String Interpolation 1195 | ``` 1196 | PS C:\> Set-Location C:\Python27\Scripts\ 1197 | ``` 1198 | Take the output of Get-ChildItem, which is an object, and gets that objects count property. 1199 | ``` 1200 | PS C:\Python27\Scripts> $items = (Get-ChildItem).Count 1201 | PS C:\Python27\Scripts> $items 1202 | 207 1203 | ``` 1204 | Take the output of Get-Location and store it in a variable. 1205 | ``` 1206 | PS C:\Python27\Scripts> $loc = Get-Location 1207 | PS C:\Python27\Scripts> $loc 1208 | 1209 | Path 1210 | ---- 1211 | C:\Python27\Scripts 1212 | 1213 | ``` 1214 | Use these variables in a string 1215 | ``` 1216 | PS C:\Python27\Scripts> "There are $items items are in the folder $loc." 1217 | There are 207 items are in the folder C:\Python27\Scripts. 1218 | ``` 1219 | To actually display the variable, escape it with a backtick, 1220 | ``` 1221 | PS C:\Python27\Scripts> "There are `$items items are in the folder `$loc." 1222 | There are $items items are in the folder $loc. 1223 | ``` 1224 | String interpolation only works with double quotes 1225 | ``` 1226 | PS C:\Python27\Scripts> 'There are $items items are in the folder $loc.' 1227 | There are $items items are in the folder $loc. 1228 | ``` 1229 | String Interpolation works with here strings 1230 | ``` 1231 | PS C:\Python27\Scripts> $hereinterpolation = @" 1232 | >> Items`tFolder 1233 | >> -----`t---------------------- 1234 | >> $items`t`t$loc 1235 | >> 1236 | >> "@ 1237 | PS C:\Python27\Scripts> $hereinterpolation 1238 | Items Folder 1239 | ----- ---------------------- 1240 | 207 C:\Python27\Scripts 1241 | 1242 | PS C:\Python27\Scripts> $hereinterpolation = @' 1243 | >> Items`tFolder 1244 | >> -----`t---------------------- 1245 | >> $items`t`t$loc 1246 | >> 1247 | >> '@ 1248 | PS C:\Python27\Scripts> 1249 | PS C:\Python27\Scripts> $hereinterpolation 1250 | Items`tFolder 1251 | -----`t---------------------- 1252 | $items`t`t$loc 1253 | 1254 | ``` 1255 | Observe that it didn't work for here strings defined with single quotes. 1256 | 1257 | Expressions used within strings, need to be wrapped in $(). 1258 | ``` 1259 | PS C:\Python27\Scripts> "There are $((Get-ChildItem).Count) items are in the folder $(Get-Location)." 1260 | There are 207 items are in the folder C:\Python27\Scripts. 1261 | 1262 | PS C:\Python27\Scripts> "Today is $(Get-Date). Be well." 1263 | Today is 05/03/2017 12:43:17. Be well. 1264 | 1265 | PS C:\Python27\Scripts> "The 15% tip of a 33.33 dollar bill is $(33.33 * 0.15) dollars" 1266 | The 15% tip of a 33.33 dollar bill is 4.9995 dollars 1267 | ``` 1268 | String Formatting - C# like syntax is supported. In C# you'd use: 1269 | ``` 1270 | PS C:\Python27\Scripts> [string]::Format("There are {0} items.", $items) 1271 | There are 207 items. 1272 | ``` 1273 | Powershell shortcut 1274 | ``` 1275 | PS C:\Python27\Scripts> "There are {0} items." -f $items 1276 | There are 207 items. 1277 | 1278 | PS C:\Python27\Scripts> "There are {0} items in the location {1}." -f $items, $loc 1279 | There are 207 items in the location C:\Python27\Scripts. 1280 | 1281 | PS C:\Python27\Scripts> "There are {0} items in the location {1}. Wow, {0} is a lot of items!" -f $items, $loc 1282 | There are 207 items in the location C:\Python27\Scripts. Wow, 207 is a lot of items! 1283 | 1284 | ``` 1285 | #### Pre-defined formats 1286 | >- N - Numbers 1287 | >- C - Currency 1288 | >- P - Percentage 1289 | >- X - Hex 1290 | >- D - Decimal 1291 | 1292 | `N - Number` 1293 | ``` 1294 | PS C:\> "N0 {0:N0} formatted" -f 12345678.119 1295 | N0 12,345,678 formatted 1296 | PS C:\> "N1 {0:N1} formatted" -f 12345678.119 1297 | N1 12,345,678.1 formatted 1298 | PS C:\> "N2 {0:N2} formatted" -f 12345678.119 1299 | N2 12,345,678.12 formatted 1300 | PS C:\> "N2 {0:N9} formatted" -f 12345678.119 1301 | N2 12,345,678.119000000 formatted 1302 | PS C:\> "N0 {0:N0} formatted" -f 123.119 1303 | N0 123 formatted 1304 | PS C:\> "N0 {0,8:N0} formatted" -f 123.119 1305 | N0 123 formatted 1306 | ``` 1307 | `C - Currency` 1308 | ``` 1309 | PS C:\> "C0 {0:C0} formatted" -f 12345678.1234 1310 | C0 $12,345,678 formatted 1311 | PS C:\> "C1 {0:C1} formatted" -f 12345678.1234 1312 | C1 $12,345,678.1 formatted 1313 | PS C:\> "C2 {0:C2} formatted" -f 12345678.1234 1314 | C2 $12,345,678.12 formatted 1315 | ``` 1316 | `P - Percentage` 1317 | ``` 1318 | PS C:\> "P0 {0:P0} formatted" -f 0.1234 1319 | P0 12 % formatted 1320 | PS C:\> "P2 {0:P2} formatted" -f 0.1234 1321 | P2 12.34 % formatted 1322 | ``` 1323 | `X - Hex` 1324 | ``` 1325 | PS C:\> "X0 0x{0:X0} formatted" -f 1234 1326 | X0 0x4D2 formatted 1327 | PS C:\> "X0 0x{0:X0} formatted" -f 0x4D2 1328 | X0 0x4D2 formatted 1329 | ``` 1330 | `D - Decimal` 1331 | ``` 1332 | PS C:\> "D0 {0:D0} formatted" -f 12345678 1333 | D0 12345678 formatted 1334 | PS C:\> "D8 {0:D8} formatted" -f 123 1335 | D8 00000123 formatted 1336 | PS C:\> "D0 {0:D0} formatted" -f 123 1337 | D0 123 formatted 1338 | PS C:\> "D0 {0,8:D0} formatted" -f 123 1339 | D0 123 formatted 1340 | ``` 1341 | Note, decimal only supports ints. This causes an error: 1342 | ``` 1343 | PS C:\> "D0 {0:D0} formatted" -f 123.1 1344 | Error formatting a string: Format specifier was invalid.. 1345 | At line:1 char:1 1346 | + "D0 {0:D0} formatted" -f 123.1 1347 | + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1348 | + CategoryInfo : InvalidOperation: (D0 {0:D0} formatted:String) [], RuntimeExcep 1349 | + FullyQualifiedErrorId : FormatError 1350 | ``` 1351 | #### Custom formatting 1352 | ``` 1353 | PS C:\> $items = 1234 1354 | PS C:\> "There are {0:#,#0} items." -f $items 1355 | There are 1,234 items. 1356 | PS C:\> "Custom 0, 25 $#,##0.0000 = {0,25:$ #,##0.0000} " -f 123456789.012000005 1357 | Custom 0, 25 $#,##0.0000 = $ 123,456,789.0120 1358 | PS C:\> "Custom 0, 25 $#,##0.0000 = {0,25:$ #,##0.00} " -f 123456789.012000005 1359 | Custom 0, 25 $#,##0.0000 = $ 123,456,789.01 1360 | PS C:\> "Custom 0, 25 $#,##0.0000 = {0,25:$ #,##0.00} " -f 123456789.012000005 1361 | Custom 0, 25 $#,##0.0000 = $ 123,456,789.01 1362 | 1363 | PS C:\> "Custom 0, 10 #,##0% = {0,10:#,##0%} " -f 0.125 1364 | Custom 0, 10 #,##0% = 13% 1365 | PS C:\> "Custom 0, 10 #,##0.00% = {0,10:#,##0.00%} " -f 0.125 1366 | Custom 0, 10 #,##0.00% = 12.50% 1367 | PS C:\> 1368 | ``` 1369 | #### Date String Formatting 1370 | * MM - Month 1371 | * mm - minute 1372 | 1373 | Custom date formatting. Note MM is Month, mm is minute 1374 | ```bash 1375 | PS C:\> "Today is {0:M/d/yyyy}. Be well." -f $(Get-Date) # Today is 3/13/2014. Be well. 1376 | Today is 5-3-2017. Be well. 1377 | 1378 | PS C:\> "Today is {0,10:MM/dd/yyyy}. Be well." -f $(Get-Date) # Today is 03/13/2014. Be well. 1379 | Today is 05-03-2017. Be well. 1380 | 1381 | PS C:\> "Today is {0,10:yyyyMMdd}. Be well." -f $(Get-Date) # Today is 20140313. Be well. 1382 | Today is 20170503. Be well. 1383 | 1384 | PS C:\> "Today is {0,10:MM/dd/yyyy hh:mm:ss}. Be well." -f $(Get-Date) # Today is 03/13/2014 12:21:19. Be well. 1385 | Today is 05-03-2017 03:51:54. Be well. 1386 | 1387 | ``` 1388 | #### Other formatting 1389 | 1390 | Calculations can be passed in as the item to be formatted 1391 | ```bash 1392 | PS C:\> "The 20% tip of a 33.33 dollar bill is {0} dollars" -f (33.33 * 0.20) # The 20% tip of a 33.33 dollar bill is 6.666 dollars 1393 | The 20% tip of a 33.33 dollar bill is 6.666 dollars 1394 | 1395 | PS C:\> "The 20% tip of a 33.33 dollar bill is {0:0.00} dollars" -f (33.33 * 0.20) # The 20% tip of a 33.33 dollar bill is 6.67 dollars 1396 | The 20% tip of a 33.33 dollar bill is 6.67 dollars 1397 | 1398 | ``` 1399 | #### String operator -like 1400 | * It works using Wildcards 1401 | ```bash 1402 | PS C:\> "PowerShell" -like "Power*" 1403 | True 1404 | 1405 | PS C:\> "PowerShell" -like "Python*" 1406 | False 1407 | 1408 | PS C:\> "PowerShell" -like "?owerShell" # question marks work for single characters 1409 | True 1410 | 1411 | PS C:\> "PowerShell" -like "Power*[s-v]" # ends in a char between s and v 1412 | False 1413 | 1414 | PS C:\> "PowerShell" -like "Power*[a-c]" # ends in a char between a and c 1415 | False 1416 | 1417 | ``` 1418 | #### String operator -match 1419 | * It works using Regular Expressions 1420 | ```bash 1421 | PS C:\> "888-368-1240" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}" 1422 | True 1423 | 1424 | PS C:\> "ZZZ-368-1240" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}" 1425 | False 1426 | 1427 | PS C:\> "888.368.1240" -match "[0-9]{3}-[0-9]{3}-[0-9]{4}" 1428 | False 1429 | ``` 1430 | ## 5. Working with Arrays 1431 | #### 5.1 Simple Arrays 1432 | Creating Array(s) 1433 | ```bash 1434 | PS C:\> $array = "Narendra", "Bhahubali" 1435 | 1436 | PS C:\> $array 1437 | Narendra 1438 | Bhahubali 1439 | 1440 | PS C:\> $array[0] 1441 | Narendra 1442 | 1443 | PS C:\> $array[1] 1444 | Bhahubali 1445 | 1446 | PS C:\> $array.GetType() 1447 | 1448 | IsPublic IsSerial Name BaseType 1449 | -------- -------- ---- -------- 1450 | True True Object[] System.Array 1451 | ``` 1452 | Updating Array(s) 1453 | ``` 1454 | PS C:\> $array = "Barack", "Obama" 1455 | 1456 | PS C:\> $array 1457 | Barack 1458 | Obama 1459 | 1460 | PS C:\> $array[0] = "Power" 1461 | 1462 | PS C:\> $array[1] = "Shell" 1463 | 1464 | PS C:\> $array 1465 | Power 1466 | Shell 1467 | ``` 1468 | Formal Array Creation Syntax 1469 | ``` 1470 | PS C:\> $array = @("Power", "Shell") 1471 | 1472 | PS C:\> $array 1473 | Power 1474 | Shell 1475 | ``` 1476 | Only way to create an empty array 1477 | ``` 1478 | PS C:\> $array = @() 1479 | 1480 | PS C:\> $array.Count 1481 | 0 1482 | 1483 | PS C:\> $array += "jeffrey" 1484 | 1485 | PS C:\> $array += "snover" 1486 | 1487 | PS C:\> $array.Count 1488 | 2 1489 | 1490 | PS C:\> $array 1491 | jeffrey 1492 | snover 1493 | 1494 | PS C:\> $array = 1..5 # Can load arrays using numeric range notation 1495 | 1496 | PS C:\> $array 1497 | 1 1498 | 2 1499 | 3 1500 | 4 1501 | 5 1502 | 1503 | PS C:\> 1504 | PS C:\> # Check to see if an item exists 1505 | 1506 | PS C:\> $numbers = 1, 42, 256 1507 | 1508 | PS C:\> $numbers -contains 42 1509 | True 1510 | 1511 | PS C:\> $numbers -notcontains 99 1512 | True 1513 | 1514 | PS C:\> $numbers -notcontains 42 1515 | False 1516 | ``` 1517 | #### 5.2 Array of Arrays 1518 | Load four individual arrays 1519 | ```bash 1520 | PS C:\> $a = 1..5 1521 | 1522 | PS C:\> $b = 6..10 1523 | 1524 | PS C:\> $c = 11..15 1525 | 1526 | PS C:\> $d = 16..20 1527 | 1528 | PS C:\> write-Host "`$a = $a `n`$b = $b `n`$c = $c `n`$d = $d" 1529 | $a = 1 2 3 4 5 1530 | $b = 6 7 8 9 10 1531 | $c = 11 12 13 14 15 1532 | $d = 16 17 18 19 20 1533 | 1534 | ``` 1535 | Now create an array from the four individual ones 1536 | ``` 1537 | PS C:\> $array = $a, $b, $c, $d 1538 | 1539 | PS C:\> $array 1540 | 1 1541 | 2 1542 | 3 1543 | 4 1544 | 5 1545 | 6 1546 | 7 1547 | 8 1548 | 9 1549 | 10 1550 | 11 1551 | 12 1552 | 13 1553 | 14 1554 | 15 1555 | 16 1556 | 17 1557 | 18 1558 | 19 1559 | 20 1560 | ``` 1561 | Array will now look like 1562 | ``` 1563 | Col [0] [1] [2] [3] [4] 1564 | Row [0] 1 2 3 4 5 1565 | Row [1] 6 7 8 9 10 1566 | Row [2] 11 12 13 14 15 1567 | Row [3] 16 17 18 19 20 1568 | ``` 1569 | Reference the second item in the second array (remember arrays are 0 based) 1570 | ``` 1571 | PS C:\> $array[1][2] # Zero based array, go to 2nd row, 3rd item 1572 | 8 1573 | ``` 1574 | Take the contents of the array and join them into a single string. 1575 | ``` 1576 | PS C:\> $array[0] -join " " 1577 | 1 2 3 4 5 1578 | 1579 | PS C:\> $array[2] -join ” “ 1580 | 11 12 13 14 15 1581 | 1582 | PS C:\> $array[3] -join ” “ 1583 | 16 17 18 19 20 1584 | 1585 | PS C:\> $array[1][1] 1586 | 7 1587 | 1588 | PS C:\> $array[3][3] 1589 | 19 1590 | ``` 1591 | ## 6. Hash tables 1592 | ```bash 1593 | PS C:\> $hash = @{"Key" = "Value"; 1594 | "PowerShell" = "PowerShell.com"; 1595 | "jeffrey snover" = "PowerShell Inventor"} 1596 | 1597 | 1598 | PS C:\> $hash # Display all values 1599 | 1600 | Name Value 1601 | ---- ----- 1602 | PowerShell PowerShell.com 1603 | Key Value 1604 | jeffrey snover PowerShell Inventor 1605 | ``` 1606 | By default, the hashes doesn't store the keys in the order of assignment. 1607 | If we need to retain the assigned order, 1608 | ``` 1609 | PS C:\> $hash1 = [ordered]@{"Key" = "Value"; 1610 | >> "PowerShell" = "PowerShell.com"; 1611 | >> "jeffrey snover" = "PowerShell Inventor"} 1612 | >> 1613 | PS C:\> $hash1 1614 | 1615 | Name Value 1616 | ---- ----- 1617 | Key Value 1618 | PowerShell PowerShell.com 1619 | jeffrey snover PowerShell Inventor 1620 | 1621 | ``` 1622 | Values from hash key can be retrieved in two ways: 1623 | ``` 1624 | PS C:\> $hash["PowerShell"] # Get a single value from the key 1625 | PowerShell.com 1626 | 1627 | PS C:\> $hash."jeffrey snover" # Get single value using object syntax 1628 | PowerShell Inventor 1629 | 1630 | ``` 1631 | You can use variables as keys 1632 | ``` 1633 | PS C:\> $mykey = "PowerShell" 1634 | 1635 | PS C:\> $hash.$mykey # Using variable as a property 1636 | PowerShell.com 1637 | 1638 | PS C:\> $hash.$($mykey) # Evaluating as an expression 1639 | PowerShell.com 1640 | 1641 | PS C:\> $hash.$("Power" + "Shell") 1642 | PowerShell.com 1643 | 1644 | ``` 1645 | Adding and removing values 1646 | ``` 1647 | PS C:\> $hash # Here's what's there to start 1648 | 1649 | Name Value 1650 | ---- ----- 1651 | PowerShell PowerShell.com 1652 | Key Value 1653 | jeffrey snover PowerShell Inventor 1654 | 1655 | PS C:\> $hash["aws"] = "Amazon Web Services" # Add value using new key 1656 | 1657 | PS C:\> $hash # Show the additional row 1658 | 1659 | Name Value 1660 | ---- ----- 1661 | PowerShell PowerShell.com 1662 | aws Amazon Web Services 1663 | Key Value 1664 | jeffrey snover PowerShell Inventor 1665 | 1666 | PS C:\> $hash.Remove("jeffrey snover") # Remove by passing in key 1667 | 1668 | PS C:\> $hash 1669 | 1670 | Name Value 1671 | ---- ----- 1672 | PowerShell PowerShell.com 1673 | aws Amazon Web Services 1674 | Key Value 1675 | 1676 | ``` 1677 | See if key exists 1678 | ``` 1679 | PS C:\> $hash.Contains("aws") # Should be there 1680 | True 1681 | 1682 | PS C:\> $hash.Contains("jeffrey snover") # Gone since we just removed it 1683 | False 1684 | 1685 | ``` 1686 | See if value exists 1687 | ``` 1688 | PS C:\> $hash.ContainsValue("PowerShell.com") # Will be there 1689 | True 1690 | 1691 | PS C:\> $hash.ContainsValue("PowerShell Inventor") # Not there since it was removed 1692 | False 1693 | 1694 | ``` 1695 | List keys and values 1696 | ``` 1697 | PS C:\> $hash.Keys 1698 | PowerShell 1699 | aws 1700 | Key 1701 | 1702 | PS C:\> $hash.Values 1703 | PowerShell.com 1704 | Amazon Web Services 1705 | Value 1706 | 1707 | ``` 1708 | Find if a key or value is present 1709 | ``` 1710 | PS C:\> $hash.Keys -contains "PowerShell" 1711 | True 1712 | 1713 | PS C:\> $hash.Values -contains "PowerShell.com" 1714 | True 1715 | ``` 1716 | ## 7. Conditional Statements and Loops 1717 | #### 7.1 if/else condition 1718 | ```bash 1719 | PS C:\> $var = 2 1720 | if ($var -eq 1) # Be sure to use -eq instead of = 1721 | { 1722 | "If branch" 1723 | } 1724 | else 1725 | { 1726 | "else branch" 1727 | } 1728 | else branch 1729 | ``` 1730 | #### 7.2 elseif 1731 | ```bash 1732 | PS C:\> $var = 2 1733 | if ($var -eq 1) 1734 | { 1735 | "If -eq 1 branch" 1736 | } 1737 | elseif ($var -eq 2) 1738 | { 1739 | "ElseIf -eq 2 branch" 1740 | } 1741 | else 1742 | { 1743 | "else branch" 1744 | } 1745 | ElseIf -eq 2 branch 1746 | ``` 1747 | #### 7.3 Switch case 1748 | ```bash 1749 | PS C:\> # Switch statement for multiple conditions 1750 | $var = 42 # Also test with 43 and 49 1751 | switch ($var) 1752 | { 1753 | 41 {"Forty One"} 1754 | 42 {"Forty Two"} 1755 | 43 {"Forty Three"} 1756 | default {"default"} 1757 | } 1758 | Forty Two 1759 | 1760 | PS C:\> # Will match all lines that match 1761 | 1762 | PS C:\> $var = 42 1763 | switch ($var) 1764 | { 1765 | 42 {"Forty Two"} 1766 | "42" {"Forty Two String"} 1767 | default {"default"} 1768 | } 1769 | Forty Two 1770 | Forty Two String 1771 | ``` 1772 | __Note__ that type coercion will cause both 42 lines to have a match. 1773 | 1774 | To stop processing once a block is found use break 1775 | ``` 1776 | PS C:\> $var = 42 1777 | switch ($var) 1778 | { 1779 | 42 {"Forty Two"; break} 1780 | "42" {"Forty Two String"; break} 1781 | default {"default"} 1782 | } 1783 | Forty Two 1784 | ``` 1785 | __Note__, if you want to put multiple commands on a single line, use a ; to separate them 1786 | 1787 | Switch works with collections, looping and executing for each match 1788 | ``` 1789 | PS C:\> switch (3,1,2,42) 1790 | { 1791 | 1 {"One"} 1792 | 2 {"Two"} 1793 | 3 {"Three"} 1794 | default {"The default answer"} 1795 | } 1796 | Three 1797 | One 1798 | Two 1799 | The default answer 1800 | 1801 | ``` 1802 | String compares are case insensitive by default 1803 | ``` 1804 | PS C:\> switch ("PowerShell") 1805 | { 1806 | "powershell" {"lowercase"} 1807 | "POWERSHELL" {"uppercase"} 1808 | "PowerShell" {"mixedcase"} 1809 | } 1810 | lowercase 1811 | uppercase 1812 | mixedcase 1813 | 1814 | ``` 1815 | Use the -casesenstive switch to make it so 1816 | ``` 1817 | PS C:\> switch -casesensitive ("PowerShell") 1818 | { 1819 | "powershell" {"lowercase"} 1820 | "POWERSHELL" {"uppercase"} 1821 | "PowerShell" {"mixedcase"} 1822 | } 1823 | mixedcase 1824 | 1825 | ``` 1826 | Supports wildcards 1827 | ``` 1828 | PS C:\> switch -Wildcard ("Pluralsight") 1829 | { 1830 | "plural*" {"*"} 1831 | "?luralsight" {"?"} 1832 | "Pluralsi???" {"???"} 1833 | } 1834 | * 1835 | ? 1836 | ??? 1837 | 1838 | ``` 1839 | __Note__ that it will also support regex matches. 1840 | 1841 | #### 7.4 While Loop 1842 | ```bash 1843 | PS C:\> # While 1844 | 1845 | $i = 1 1846 | while ($i -le 5) 1847 | { 1848 | "`$i = $i" 1849 | $i = $i + 1 1850 | } 1851 | $i = 1 1852 | $i = 2 1853 | $i = 3 1854 | $i = 4 1855 | $i = 5 1856 | 1857 | PS C:\> # While won't execute if condition is already true 1858 | 1859 | $i = 6 1860 | while ($i -le 5) 1861 | { 1862 | "`$i = $i" 1863 | $i = $i + 1 1864 | } 1865 | 1866 | ``` 1867 | #### 7.5 do-While 1868 | ``` 1869 | PS C:\> # do-while 1870 | $i = 1 1871 | do 1872 | { 1873 | "`$i = $i" 1874 | $i++ 1875 | } while($i -le 5) 1876 | $i = 1 1877 | $i = 2 1878 | $i = 3 1879 | $i = 4 1880 | $i = 5 1881 | ``` 1882 | Do will always execute at least once 1883 | ``` 1884 | $i = 6 1885 | do 1886 | { 1887 | "`$i = $i" 1888 | $i++ 1889 | } while($i -le 5) 1890 | $i = 6 1891 | ``` 1892 | Use until to make the check more positive 1893 | ``` 1894 | $i = 1 1895 | do 1896 | { 1897 | "`$i = $i" 1898 | $i++ 1899 | } until($i -gt 5) 1900 | $i = 1 1901 | $i = 2 1902 | $i = 3 1903 | $i = 4 1904 | $i = 5 1905 | ``` 1906 | #### 7.6 for loop 1907 | ```bash 1908 | 1909 | PS C:\> for ($f = 0; $f -le 5; $f++) 1910 | { 1911 | "`$f = $f" 1912 | } 1913 | 1914 | $f = 0 1915 | $f = 1 1916 | $f = 2 1917 | $f = 3 1918 | $f = 4 1919 | $f = 5 1920 | ``` 1921 | Note the initializer can be set seperately 1922 | ``` 1923 | PS C:\> $f = 2 1924 | for (; $f -le 5; $f++) 1925 | { 1926 | "`$f = $f" 1927 | } 1928 | 1929 | $f = 2 1930 | $f = 3 1931 | $f = 4 1932 | $f = 5 1933 | ``` 1934 | Iterating over a collection 1 by 1 1935 | ``` 1936 | PS C:\> $array = 11,12,13,14,15 # Simple Array 1937 | for ($i=0; $i -lt $array.Length; $i++) 1938 | { 1939 | "`$array[$i]=" + $array[$i] 1940 | } 1941 | $array[0]=11 1942 | $array[1]=12 1943 | $array[2]=13 1944 | $array[3]=14 1945 | $array[4]=15 1946 | ``` 1947 | 1948 | #### 7.7 foreach 1949 | foreach works on a collection 1950 | ``` 1951 | PS C:\> $array = 11,12,13,14,15 # Simple Array 1952 | foreach ($item in $array) 1953 | { 1954 | "`$item = $item" 1955 | } 1956 | 1957 | $item = 11 1958 | $item = 12 1959 | $item = 13 1960 | $item = 14 1961 | $item = 15 1962 | 1963 | PS C:\> "1KB=$(1KB)" 1964 | 1KB=1024 1965 | PS C:\> "1MB=$(1MB)" 1966 | 1MB=1048576 1967 | PS C:\> "1GB=$(1GB)" 1968 | 1GB=1073741824 1969 | PS C:\> "1TB=$(1TB)" 1970 | 1TB=1099511627776 1971 | PS C:\> "1PB=$(1PB)" 1972 | 1PB=1125899906842624 1973 | 1974 | PS C:\> foreach($i in @('1KB', '1MB', '1GB', '1TB', '1PB')){Write-Host "$i =$($i)"} 1975 | 1KB =1KB 1976 | 1MB =1MB 1977 | 1GB =1GB 1978 | 1TB =1TB 1979 | 1PB =1PB 1980 | ``` 1981 | 1982 | foreach works with an array of objects 1983 | ``` 1984 | PS C:\> foreach ($file in Get-ChildItem -Path "C:\Python27") 1985 | { 1986 | $file.Name 1987 | } 1988 | DLLs 1989 | Doc 1990 | etc 1991 | include 1992 | Lib 1993 | libs 1994 | Scripts 1995 | share 1996 | tcl 1997 | Tools 1998 | LICENSE.txt 1999 | NEWS.txt 2000 | python.exe 2001 | pythonw.exe 2002 | README.txt 2003 | w9xpopen.exe 2004 | ``` 2005 | Use break to get out of the loop 2006 | ``` 2007 | PS C:\> foreach ($file in Get-ChildItem -Path "C:\Python27") 2008 | { 2009 | if ($file.Name -like "*.exe") 2010 | { 2011 | $file.Name 2012 | break # exits the loop on first hit 2013 | } 2014 | } 2015 | python.exe 2016 | ``` 2017 | Use continue to skip the rest of a loop but go onto the next iteration 2018 | ``` 2019 | PS C:\> foreach ($file in Get-ChildItem -Path "C:\Python27") 2020 | { 2021 | if ($file.Name -like "*.exe") 2022 | { 2023 | $file.Name 2024 | continue # exits the loop on first hit 2025 | "More code here" 2026 | } 2027 | "This isn't a executable file: $file" 2028 | } 2029 | This isn't a executable file: DLLs 2030 | This isn't a executable file: Doc 2031 | This isn't a executable file: etc 2032 | This isn't a executable file: include 2033 | This isn't a executable file: Lib 2034 | This isn't a executable file: libs 2035 | This isn't a executable file: Scripts 2036 | This isn't a executable file: share 2037 | This isn't a executable file: tcl 2038 | This isn't a executable file: Tools 2039 | This isn't a executable file: LICENSE.txt 2040 | This isn't a executable file: NEWS.txt 2041 | python.exe 2042 | pythonw.exe 2043 | This isn't a executable file: README.txt 2044 | w9xpopen.exe 2045 | ``` 2046 | When used in a nested loop, break exits to the outer loop 2047 | ``` 2048 | PS C:\> foreach ($outside in 1..3) 2049 | { 2050 | "`$outside=$outside" 2051 | foreach ($inside in 4..6) 2052 | { 2053 | " `$inside = $inside" 2054 | break 2055 | } 2056 | } 2057 | $outside=1 2058 | $inside = 4 2059 | $outside=2 2060 | $inside = 4 2061 | $outside=3 2062 | $inside = 4 2063 | ``` 2064 | Use loop labels to break to a certain loop 2065 | ``` 2066 | PS C:\> :outsideloop foreach ($outside in 1..3) 2067 | { 2068 | "`$outside=$outside" 2069 | foreach ($inside in 4..6) 2070 | { 2071 | " `$inside = $inside" 2072 | break outsideloop 2073 | } 2074 | } 2075 | $outside=1 2076 | $inside = 4 2077 | ``` 2078 | Using continue inside an inner loop 2079 | ``` 2080 | foreach ($outside in 1..3) 2081 | { 2082 | "`$outside=$outside" 2083 | foreach ($inside in 4..6) 2084 | { 2085 | " `$inside = $inside" 2086 | continue 2087 | "this will never execute as continue goes back to start of inner for loop" 2088 | # note, because we continue to the inside loop, the above line 2089 | # will never run but it will go thru all iterations of the inner loop 2090 | } 2091 | } 2092 | $outside=1 2093 | $inside = 4 2094 | $inside = 5 2095 | $inside = 6 2096 | $outside=2 2097 | $inside = 4 2098 | $inside = 5 2099 | $inside = 6 2100 | $outside=3 2101 | $inside = 4 2102 | $inside = 5 2103 | $inside = 6 2104 | 2105 | PS C:\> :outsideloop foreach ($outside in 1..3) 2106 | { 2107 | "`$outside=$outside" 2108 | foreach ($inside in 4..6) 2109 | { 2110 | " `$inside = $inside" 2111 | continue outsideloop 2112 | "this will never execute as continue goes back to start of inner for loop" 2113 | # here, because we break all the way to the outer loop the last two 2114 | # iterations (5 and 6) never run 2115 | } 2116 | "some more stuff here that will never run" 2117 | } 2118 | 2119 | $outside=1 2120 | $inside = 4 2121 | $outside=2 2122 | $inside = 4 2123 | $outside=3 2124 | $inside = 4 2125 | ``` 2126 | ### 7.8 Script Blocks 2127 | 2128 | A basic script block is code inside {}. The for (as well as other loops) execute a script block. 2129 | ```bash 2130 | PS C:\> for ($f = 0; $f -le 5; $f++) 2131 | { 2132 | "`$f = $f" 2133 | } 2134 | 2135 | $f = 0 2136 | $f = 1 2137 | $f = 2 2138 | $f = 3 2139 | $f = 4 2140 | $f = 5PS C:\> for ($f = 0; $f -le 5; $f++) 2141 | { 2142 | "`$f = $f" 2143 | } 2144 | 2145 | $f = 0 2146 | $f = 1 2147 | $f = 2 2148 | $f = 3 2149 | $f = 4 2150 | $f = 5 2151 | ``` 2152 | 2153 | A script block can exist on its own. 2154 | 2155 | __NOTE:__ To put multiple commands on a single line use the ; 2156 | ```bash 2157 | PS C:\> {Clear-Host; "Powershell is cool."} 2158 | Clear-Host; "Powershell is cool." 2159 | ``` 2160 | Executing only shows the contents of the block, doesn't execute it. 2161 | 2162 | To actually run it, use an ampersand & in front. 2163 | ``` 2164 | PS C:\> &{Clear-Host; "Powershell is cool."} 2165 | Powershell is cool. 2166 | ``` 2167 | You can store script blocks inside a variable 2168 | ``` 2169 | PS C:\> $cool = {Clear-Host; "Powershell is cool."} 2170 | ``` 2171 | Just entering the variable though only shows the contents, doesn't run it. 2172 | ``` 2173 | PS C:\>Clear-Host; "Powershell is cool." 2174 | 2175 | PS C:\> & $cool # To actually run it, use the & character 2176 | Powershell is cool. 2177 | ``` 2178 | Since scripts can be put in a variable, you can do interesting things. 2179 | ``` 2180 | PS C:\> $cool = {"Powershell is cool."; " So is jeffrey snover"} 2181 | for ($i=0;$i -lt 3; $i++) 2182 | { 2183 | &$cool; 2184 | } 2185 | Powershell is cool. 2186 | So is jeffrey snover 2187 | Powershell is cool. 2188 | So is jeffrey snover 2189 | Powershell is cool. 2190 | So is jeffrey snover 2191 | ``` 2192 | ## 8. Functions 2193 | ```bash 2194 | PS C:\> $hw = { 2195 | "Hello World" 2196 | } 2197 | 2198 | PS C:\> & $hw 2199 | Hello World 2200 | ``` 2201 | Functions are basically script blocks with names. 2202 | ```bash 2203 | PS C:\> function Write-HelloWorld() 2204 | { 2205 | "Hello World" 2206 | } 2207 | ``` 2208 | Running the above simply places the function in memory for us to use. 2209 | To use it, call it like you would a cmdlet. 2210 | ```bash 2211 | PS C:\> Write-HelloWorld 2212 | Hello World 2213 | 2214 | ``` 2215 | When writing functions, use an approved verb. To get the list of approved verbs, 2216 | ```bash 2217 | PS C:\> Get-Verb 2218 | 2219 | Verb Group 2220 | ---- ----- 2221 | Add Common 2222 | Clear Common 2223 | Close Common 2224 | Copy Common 2225 | Enter Common 2226 | Exit Common 2227 | Find Common 2228 | Format Common 2229 | Get Common 2230 | Hide Common 2231 | Join Common 2232 | Lock Common 2233 | Move Common 2234 | New Common 2235 | Open Common 2236 | Optimize Common 2237 | Pop Common 2238 | Push Common 2239 | Redo Common 2240 | Remove Common 2241 | Rename Common 2242 | Reset Common 2243 | Resize Common 2244 | Search Common 2245 | Select Common 2246 | Set Common 2247 | Show Common 2248 | Skip Common 2249 | Split Common 2250 | Step Common 2251 | Switch Common 2252 | Undo Common 2253 | Unlock Common 2254 | Watch Common 2255 | Backup Data 2256 | Checkpoint Data 2257 | Compare Data 2258 | Compress Data 2259 | Convert Data 2260 | ConvertFrom Data 2261 | ConvertTo Data 2262 | Dismount Data 2263 | Edit Data 2264 | Expand Data 2265 | Export Data 2266 | Group Data 2267 | Import Data 2268 | Initialize Data 2269 | Limit Data 2270 | Merge Data 2271 | Mount Data 2272 | Out Data 2273 | Publish Data 2274 | Restore Data 2275 | Save Data 2276 | Sync Data 2277 | Unpublish Data 2278 | Update Data 2279 | Approve Lifecycle 2280 | Assert Lifecycle 2281 | Complete Lifecycle 2282 | Confirm Lifecycle 2283 | Deny Lifecycle 2284 | Disable Lifecycle 2285 | Enable Lifecycle 2286 | Install Lifecycle 2287 | Invoke Lifecycle 2288 | Register Lifecycle 2289 | Request Lifecycle 2290 | Restart Lifecycle 2291 | Resume Lifecycle 2292 | Start Lifecycle 2293 | Stop Lifecycle 2294 | Submit Lifecycle 2295 | Suspend Lifecycle 2296 | Uninstall Lifecycle 2297 | Unregister Lifecycle 2298 | Wait Lifecycle 2299 | Debug Diagnostic 2300 | Measure Diagnostic 2301 | Ping Diagnostic 2302 | Repair Diagnostic 2303 | Resolve Diagnostic 2304 | Test Diagnostic 2305 | Trace Diagnostic 2306 | Connect Communications 2307 | Disconnect Communications 2308 | Read Communications 2309 | Receive Communications 2310 | Send Communications 2311 | Write Communications 2312 | Block Security 2313 | Grant Security 2314 | Protect Security 2315 | Revoke Security 2316 | Unblock Security 2317 | Unprotect Security 2318 | Use Other 2319 | ``` 2320 | Parameters can be passed in by placing them in parenthesis. 2321 | ```bash 2322 | PS C:\> function Get-Fullname($firstName, $lastName) 2323 | { 2324 | Write-Host ($firstName + " " + $lastName) 2325 | } 2326 | ``` 2327 | __Note:__ when calling the function with parameters, do not use commas or (). 2328 | ```bash 2329 | PS C:\> function Get-Fullname($firstName, $lastName) 2330 | { 2331 | Write-Host ($firstName + " " + $lastName) 2332 | } 2333 | 2334 | PS C:\> Get-Fullname "jeffrey" "snover" 2335 | jeffrey snover 2336 | 2337 | PS C:\> 2338 | PS C:\> $myVar = "jeffrey" 2339 | 2340 | PS C:\> Get-Fullname $myVar "snover" 2341 | jeffrey snover 2342 | 2343 | PS C:\> Get-Fullname $("je" + "ffrey") "snover" 2344 | jeffrey snover 2345 | ``` 2346 | Any changes to a paramater inside a function are scoped to that function. 2347 | ```bash 2348 | PS C:\> function Set-NonRefVar($myparam) 2349 | { 2350 | $myparam = 33 2351 | "Inside function `$myparam = $myparam" 2352 | } 2353 | 2354 | PS C:\> $myparam = 42 2355 | 2356 | PS C:\> "Prior to funciton `$myparam = $myparam" 2357 | Prior to funciton $myparam = 42 2358 | 2359 | PS C:\> Set-NonRefVar($myparam) 2360 | Inside function $myparam = 33 2361 | 2362 | PS C:\> "After funciton `$myparam = $myparam" 2363 | After funciton $myparam = 42 2364 | ``` 2365 | To change a value inside a funciton, use [ref] 2366 | 2367 | Passing by reference simply requires a [ref] tag before the variable 2368 | 2369 | __Note__ however it turns it into an object, thus requiring the .Value syntax. 2370 | ```bash 2371 | PS C:\> function Set-RefVar([ref] $myparam) 2372 | { 2373 | $myparam.Value = 33 2374 | "Inside function `$myparam = $($myparam.Value)" 2375 | } 2376 | 2377 | PS C:\> $myparam = 42 2378 | 2379 | PS C:\> "Prior to funciton `$myparam = $myparam" 2380 | Prior to funciton $myparam = 42 2381 | 2382 | PS C:\> Set-RefVar ([ref] $myparam) # Must add ref to call 2383 | Inside function $myparam = 33 2384 | 2385 | PS C:\> "After funciton `$myparam = $myparam" 2386 | After funciton $myparam = 33 2387 | ``` 2388 | __NOTE:__ Altering the value of parameters is considered poor programming practice and should be avoided. Instead use return. 2389 | 2390 | ```bash 2391 | PS C:\> function Get-AValue($one, $two) 2392 | { 2393 | return $one * $two 2394 | } 2395 | 2396 | 2397 | PS C:\> Get-AValue 33 42 2398 | 1386 2399 | 2400 | PS C:\> $returnValue = Get-AValue 33 42 2401 | 2402 | PS C:\> "Returned value is $returnValue" 2403 | Returned value is 1386 2404 | ``` 2405 | Functions also support named parameters. Simply put the name of the parameter with a - 2406 | ```bash 2407 | PS C:\> $returnValue = Get-AValue -one 33 -two 42 2408 | 2409 | PS C:\> "Returned value is $returnValue" 2410 | Returned value is 1386 2411 | 2412 | ``` 2413 | With named parameters, order is no longer important. 2414 | ```bash 2415 | PS C:\> $returnValue = Get-AValue -two 42 -one 33 2416 | 2417 | PS C:\> "Returned value is $returnValue" 2418 | Returned value is 1386 2419 | 2420 | ``` 2421 | It is possible to pipeline enable your functions. These are referred to as advanced functions. 2422 | ```bash 2423 | PS C:\> function Get-EXEFiles () 2424 | { 2425 | # The begin block executes once at the start of the function 2426 | begin { $retval = "Here are some EXE files: `r`n" } 2427 | 2428 | # The process block is executed once for each object being 2429 | # passed in from the pipe 2430 | process { 2431 | if ($_.Name -like "*.exe") 2432 | { 2433 | $retval += "`t$($_.Name)`r`n" 2434 | # Note this line could also be rendered as 2435 | # $retval = $retval + "`t" + $_.Name + "`r`n" 2436 | # `t Tab Character 2437 | # `r Carriage Return 2438 | # `n Line Feed 2439 | # $( ) Tells PS to evaute the expression in () first then return it 2440 | # $_ The current object being passed in the pipeline 2441 | # .Name The name property of the current object 2442 | } 2443 | } 2444 | 2445 | # The end block executes once, after the rest of the function 2446 | end { return $retval } 2447 | } 2448 | 2449 | PS C:\> Get-ChildItem -Path "C:\Python27\" | Get-EXEFiles 2450 | Here are some EXE files: 2451 | python.exe 2452 | pythonw.exe 2453 | Removecx_Oracle.exe 2454 | w9xpopen.exe 2455 | 2456 | 2457 | PS C:\> $output = Get-ChildItem | Get-EXEFiles 2458 | 2459 | PS C:\> $output.GetType() 2460 | 2461 | IsPublic IsSerial Name BaseType 2462 | -------- -------- ---- -------- 2463 | True True String System.Object 2464 | 2465 | PS C:\> $i = 0 2466 | foreach($f in $output) 2467 | { 2468 | $i++ 2469 | "$i : $f" 2470 | } 2471 | 1 : Here are some EXE files: 2472 | 2473 | ``` 2474 | To pipeline the output, push the output in the process area. 2475 | ```bash 2476 | PS C:\> function Get-EXEFiles () 2477 | { 2478 | begin { } 2479 | 2480 | process { 2481 | if ($_.Name -like "*.exe") 2482 | { 2483 | $retval = "`tEXE file is $($_.Name)" 2484 | $retval # This is the equivalent of: return $retval 2485 | } 2486 | } 2487 | 2488 | end { } 2489 | } 2490 | 2491 | PS C:\> $output = Get-ChildItem -Path "C:\Python27" | Get-EXEFiles 2492 | 2493 | PS C:\> $output.GetType() 2494 | 2495 | IsPublic IsSerial Name BaseType 2496 | -------- -------- ---- -------- 2497 | True True Object[] System.Array 2498 | 2499 | 2500 | 2501 | PS C:\> $i = 0 2502 | 2503 | PS C:\> foreach($f in $output) 2504 | { 2505 | $i++ 2506 | "$i : $f" 2507 | } 2508 | 2509 | 1 : EXE file is python.exe 2510 | 2 : EXE file is pythonw.exe 2511 | 3 : EXE file is Removecx_Oracle.exe 2512 | 4 : EXE file is w9xpopen.exe 2513 | 2514 | PS C:\> 2515 | PS C:\> function Write-SomeText () 2516 | { 2517 | # begin { } 2518 | 2519 | process { 2520 | $retval = "Here is the output: $($_)" 2521 | $retval 2522 | } 2523 | 2524 | # end { } 2525 | } 2526 | 2527 | 2528 | 2529 | PS C:\> Get-ChildItem -Path "C:\Python27" | Get-EXEFiles | Write-SomeText 2530 | Here is the output: EXE file is python.exe 2531 | Here is the output: EXE file is pythonw.exe 2532 | Here is the output: EXE file is Removecx_Oracle.exe 2533 | Here is the output: EXE file is w9xpopen.exe 2534 | ``` 2535 | Similar to original function but truly pipelined. 2536 | ```bash 2537 | PS C:\> "Here are some PowerShell files: `r`n" 2538 | Here are some PowerShell files: 2539 | 2540 | 2541 | PS C:\> Get-ChildItem -Path "C:\Python27"| Get-PSFiles 2542 | Here are some PowerShell files: 2543 | 2544 | ``` 2545 | Advanced functions also allow parameters with extra helping hints. 2546 | ```bash 2547 | PS C:\> function Get-AValue () 2548 | { 2549 | [CmdletBinding()] # Needed to indicate this is an advanced function 2550 | param ( # Begin the parameter block 2551 | [Parameter( Mandatory = $true, 2552 | HelpMessage = 'Please enter value one.' 2553 | )] 2554 | [int] $one, 2555 | # Note in the second we are strongly typing, and are providing a default value 2556 | [Parameter( Mandatory = $false, 2557 | HelpMessage = 'Please enter value two.' 2558 | )] 2559 | [int] $two = 42 2560 | ) # End the parameter block 2561 | 2562 | begin { } 2563 | 2564 | process { 2565 | return $one * $two 2566 | } 2567 | 2568 | end { } 2569 | 2570 | } 2571 | ``` 2572 | Example 1: pass in values 2573 | ```bash 2574 | PS C:\> Get-AValue -one 33 -two 42 2575 | 1386 2576 | ``` 2577 | Example 2: pass in value for one, take default for two 2578 | ```bash 2579 | PS C:\> Get-AValue -one 33 2580 | 1386 2581 | ``` 2582 | Example 3: no params, will prompt for one and take default for two 2583 | ```bash 2584 | PS C:\> Get-AValue 2585 | cmdlet Get-AValue at command pipeline position 1 2586 | Supply values for the following parameters: 2587 | (Type !? for Help.) 2588 | one: 33 2589 | 1386 2590 | ``` 2591 | Example 4: use a string for one (generates error) 2592 | ```bash 2593 | PS C:\> Get-AValue -one "x" 2594 | Get-AValue : Cannot process argument transformation on parameter 'one'. Cannot 2595 | convert value "x" to type "System.Int32". Error: "Input string was not in a 2596 | correct format." 2597 | At line:1 char:17 2598 | + Get-AValue -one "x" 2599 | + ~~~ 2600 | + CategoryInfo : InvalidData: (:) [Get-AValue], ParameterBindingA 2601 | rgumentTransformationException 2602 | + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-AValue 2603 | ``` 2604 | ### Adding Help to Your Functions 2605 | 2606 | PowerShell is possessing a robust cmdlet for help 2607 | ```bash 2608 | PS C:\> Get-Help Get-ChildItem 2609 | 2610 | NAME 2611 | Get-ChildItem 2612 | 2613 | SYNTAX 2614 | Get-ChildItem [[-Path] ] [[-Filter] ] [-Include 2615 | ] [-Exclude ] [-Recurse] [-Depth ] [-Force] 2616 | [-Name] [-UseTransaction] [-Attributes 2617 | {ReadOnly | Hidden | System | Directory | Archive | Device | Normal | 2618 | Temporary | SparseFile | ReparsePoint | Compressed | Offline | 2619 | NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}] 2620 | [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [] 2621 | 2622 | Get-ChildItem [[-Filter] ] -LiteralPath [-Include 2623 | ] [-Exclude ] [-Recurse] [-Depth ] [-Force] 2624 | [-Name] [-UseTransaction] [-Attributes 2625 | {ReadOnly | Hidden | System | Directory | Archive | Device | Normal | 2626 | Temporary | SparseFile | ReparsePoint | Compressed | Offline | 2627 | NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}] 2628 | [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [] 2629 | 2630 | 2631 | ALIASES 2632 | gci 2633 | ls 2634 | dir 2635 | 2636 | 2637 | REMARKS 2638 | Get-Help cannot find the Help files for this cmdlet on this computer. It 2639 | is displaying only partial help. 2640 | -- To download and install Help files for the module that includes 2641 | this cmdlet, use Update-Help. 2642 | -- To view the Help topic for this cmdlet online, type: "Get-Help 2643 | Get-ChildItem -Online" or 2644 | go to http://go.microsoft.com/fwlink/?LinkID=113308. 2645 | ``` 2646 | `Help for our function` 2647 | ```bash 2648 | PS C:\> function Get-ChildName () 2649 | { 2650 | Write-Output (Get-ChildItem | Select-Object "Name") 2651 | } 2652 | 2653 | 2654 | PS C:\> Get-Help Get-ChildName 2655 | 2656 | NAME 2657 | Get-ChildName 2658 | 2659 | SYNTAX 2660 | Get-ChildName 2661 | 2662 | 2663 | ALIASES 2664 | None 2665 | 2666 | 2667 | REMARKS 2668 | None 2669 | ``` 2670 | Custom tags within a comment block that Get-Help will recognize 2671 | ``` 2672 | Note that not all of them are required 2673 | .SYNOPSIS - A brief description of the command 2674 | .DESCRIPTION - Detailed command description 2675 | .PARAMETER name - Include one description for each parameter 2676 | .EXAMPLE - Detailed examples on how to use the command 2677 | .INPUTS - What pipeline inputs are supported 2678 | .OUTPUTS - What this funciton outputs 2679 | .NOTES - Any misc notes you haven't put anywhere else 2680 | .LINK - A link to the URL for more help. Use one .LINK tag per URL 2681 | Use "Get-Help about_comment_based_help" for full list and details 2682 | ``` 2683 | ```bash 2684 | PS C:\> function Get-ChildName () 2685 | { 2686 | <# 2687 | .SYNOPSIS 2688 | Returns a list of only the names for the child items in the current location. 2689 | 2690 | .DESCRIPTION 2691 | This function is similar to Get-ChildItem, except that it returns only the name 2692 | property. 2693 | 2694 | .INPUTS 2695 | None. 2696 | 2697 | .OUTPUTS 2698 | System.String. Sends a collection of strings out the pipeline. 2699 | 2700 | .EXAMPLE 2701 | Example 1 - Simple use 2702 | Get-ChildName 2703 | 2704 | .EXAMPLE 2705 | Example 2 - Passing to another object in the pipeline 2706 | Get-ChildName | Where-Object {$_.Name -like "*.ps1"} 2707 | 2708 | .LINK 2709 | Get-ChildItem 2710 | 2711 | #> 2712 | 2713 | Write-Output (Get-ChildItem | Select-Object "Name") 2714 | 2715 | } 2716 | ``` 2717 | ```bash 2718 | PS C:\> Get-Help Get-ChildName 2719 | 2720 | NAME 2721 | Get-ChildName 2722 | 2723 | SYNOPSIS 2724 | Returns a list of only the names for the child items in the current 2725 | location. 2726 | 2727 | 2728 | SYNTAX 2729 | Get-ChildName [] 2730 | 2731 | 2732 | DESCRIPTION 2733 | This function is similar to Get-ChildItem, except that it returns only the 2734 | name 2735 | property. 2736 | 2737 | 2738 | RELATED LINKS 2739 | Get-ChildItem 2740 | 2741 | REMARKS 2742 | To see the examples, type: "get-help Get-ChildName -examples". 2743 | For more information, type: "get-help Get-ChildName -detailed". 2744 | For technical information, type: "get-help Get-ChildName -full". 2745 | For online help, type: "get-help Get-ChildName -online" 2746 | 2747 | 2748 | 2749 | 2750 | PS C:\> Get-Help Get-ChildName -full 2751 | 2752 | NAME 2753 | Get-ChildName 2754 | 2755 | SYNOPSIS 2756 | Returns a list of only the names for the child items in the current 2757 | location. 2758 | 2759 | SYNTAX 2760 | Get-ChildName [] 2761 | 2762 | 2763 | DESCRIPTION 2764 | This function is similar to Get-ChildItem, except that it returns only the 2765 | name 2766 | property. 2767 | 2768 | 2769 | PARAMETERS 2770 | 2771 | This cmdlet supports the common parameters: Verbose, Debug, 2772 | ErrorAction, ErrorVariable, WarningAction, WarningVariable, 2773 | OutBuffer, PipelineVariable, and OutVariable. For more information, 2774 | see 2775 | about_CommonParameters 2776 | (http://go.microsoft.com/fwlink/?LinkID=113216). 2777 | 2778 | INPUTS 2779 | None. 2780 | 2781 | 2782 | 2783 | 2784 | OUTPUTS 2785 | System.String. Sends a collection of strings out the pipeline. 2786 | 2787 | 2788 | 2789 | 2790 | -------------------------- EXAMPLE 1 -------------------------- 2791 | 2792 | PS C:\>Example 1 - Simple use 2793 | 2794 | 2795 | Get-ChildName 2796 | 2797 | 2798 | 2799 | 2800 | 2801 | -------------------------- EXAMPLE 2 -------------------------- 2802 | 2803 | PS C:\>Example 2 - Passing to another object in the pipeline 2804 | 2805 | 2806 | Get-ChildName | Where-Object {$_.Name -like "*.ps1"} 2807 | 2808 | 2809 | 2810 | 2811 | 2812 | 2813 | RELATED LINKS 2814 | Get-ChildItem 2815 | ``` 2816 | ## 7. Error Handling 2817 | Better Error handling is essential for managing the scripts. 2818 | ```bash 2819 | PS C:\> function divver($enum,$denom) 2820 | { 2821 | Write-Host "Divver begin." 2822 | $result = $enum / $denom 2823 | Write-Host "Result: $result" 2824 | Write-Host "Divver done." 2825 | } 2826 | 2827 | PS C:\> divver 33 3 # No Error 2828 | Divver begin. 2829 | Result: 11 2830 | Divver done. 2831 | 2832 | PS C:\> divver 33 0 # Generates Error 2833 | Divver begin. 2834 | Attempted to divide by zero. 2835 | At line:4 char:3 2836 | + $result = $enum / $denom 2837 | + ~~~~~~~~~~~~~~~~~~~~~~~~ 2838 | + CategoryInfo : NotSpecified: (:) [], RuntimeException 2839 | + FullyQualifiedErrorId : RuntimeException 2840 | 2841 | Result: 2842 | Divver done. 2843 | ``` 2844 | Handle errors using try/catch/finally 2845 | ```bash 2846 | PS C:\> function divver($enum,$denom) 2847 | { 2848 | Write-Host "Divver begin." 2849 | 2850 | try 2851 | { 2852 | $result = $enum / $denom 2853 | Write-Host "Result: $result" 2854 | } 2855 | catch 2856 | { 2857 | Write-Host "Oh NO! An error has occurred!!" 2858 | Write-Host $_.ErrorID 2859 | Write-Host $_.Exception.Message 2860 | break # With break, or omitting it, error bubbles up to parent 2861 | } 2862 | finally 2863 | { 2864 | Write-Host "Divver done." 2865 | } 2866 | } 2867 | 2868 | PS C:\> divver 33 3 # No Error 2869 | Divver begin. 2870 | Result: 11 2871 | Divver done. 2872 | 2873 | PS C:\> divver 33 0 # Generates Error 2874 | Divver begin. 2875 | Oh NO! An error has occurred!! 2876 | 2877 | Attempted to divide by zero. 2878 | Divver done. 2879 | ``` 2880 | The errors that occur mainly falls under two categories: 2881 | 2882 | a. Terminating Errors halts the command (or script execution) completely. 2883 | Ex: non-existent cmdlets, syntax errors that would prevent a cmdlet from running, or other fatal errors. 2884 | b. Non-Terminating Errors allows execution to continue despite the failure. 2885 | Ex: operational errors such file not found, permissions problems, etc. 2886 | 2887 | 2888 | When either type of error occurs during execution, it is logged to a global variable called **$Error**. 2889 | This variable is a collection of PowerShell error objects with the most recent error at index 0. 2890 | ```bash 2891 | C:\> $Error.GetType() 2892 | 2893 | Public IsSerial Name BaseType 2894 | ------ -------- ---- -------- 2895 | ue True ArrayList System.Object 2896 | 2897 | 2898 | C:\> $Error.Count 2899 | 2900 | C:\> Some-Command 2901 | me-Command : The term 'Some-Command' is not recognized as the name of a cmdlet, function, script file, or operable 2902 | ogram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 2903 | line:1 char:1 2904 | Some-Command 2905 | ~~~~~~~~~~~~ 2906 | + CategoryInfo : ObjectNotFound: (Some-Command:String) [], CommandNotFoundException 2907 | + FullyQualifiedErrorId : CommandNotFoundException 2908 | 2909 | C:\> $Error.Count 2910 | 2911 | C:\> $error[0] 2912 | me-Command : The term 'Some-Command' is not recognized as the name of a cmdlet, function, script file, or operable 2913 | ogram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 2914 | line:1 char:1 2915 | Some-Command 2916 | ~~~~~~~~~~~~ 2917 | + CategoryInfo : ObjectNotFound: (Some-Command:String) [], CommandNotFoundException 2918 | + FullyQualifiedErrorId : CommandNotFoundException 2919 | 2920 | C:\> $error[0] | Get-Member 2921 | 2922 | 2923 | TypeName: System.Management.Automation.ErrorRecord 2924 | 2925 | me MemberType Definition 2926 | -- ---------- ---------- 2927 | uals Method bool Equals(System.Object obj) 2928 | tHashCode Method int GetHashCode() 2929 | tObjectData Method void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.... 2930 | tType Method type GetType() 2931 | String Method string ToString() 2932 | tegoryInfo Property System.Management.Automation.ErrorCategoryInfo CategoryInfo {get;} 2933 | rorDetails Property System.Management.Automation.ErrorDetails ErrorDetails {get;set;} 2934 | ception Property System.Exception Exception {get;} 2935 | llyQualifiedErrorId Property string FullyQualifiedErrorId {get;} 2936 | vocationInfo Property System.Management.Automation.InvocationInfo InvocationInfo {get;} 2937 | pelineIterationInfo Property System.Collections.ObjectModel.ReadOnlyCollection[int] PipelineIterationInfo {g... 2938 | riptStackTrace Property string ScriptStackTrace {get;} 2939 | rgetObject Property System.Object TargetObject {get;} 2940 | MessageDetails ScriptProperty System.Object PSMessageDetails {get=& { Set-StrictMode -Version 1; $this.Except... 2941 | 2942 | 2943 | C:\> $error[0].InvocationInfo 2944 | 2945 | 2946 | Command : 2947 | undParameters : {} 2948 | boundArguments : {} 2949 | riptLineNumber : 1 2950 | fsetInLine : 1 2951 | storyId : 5 2952 | riptName : 2953 | ne : Some-Command 2954 | sitionMessage : At line:1 char:1 2955 | + Some-Command 2956 | + ~~~~~~~~~~~~ 2957 | ScriptRoot : 2958 | CommandPath : 2959 | vocationName : Some-Command 2960 | pelineLength : 0 2961 | pelinePosition : 0 2962 | pectingInput : False 2963 | mmandOrigin : Internal 2964 | splayScriptPosition : 2965 | 2966 | 2967 | 2968 | C:\> $error[0].Exception 2969 | e term 'Some-Command' is not recognized as the name of a cmdlet, function, script file, or operable program. Check 2970 | e spelling of the name, or if a path was included, verify that the path is correct and try again. 2971 | C:\> 2972 | C:\> $error[0].Exception.StackTrace 2973 | at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandTypes commandTypes, Sea 2974 | hResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context) 2975 | at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrig 2976 | , Nullable`1 useLocalScope) 2977 | at System.Management.Automation.ExecutionContext.CreateCommand(String command, Boolean dotSource) 2978 | at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElem 2979 | ts, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, ExecutionContext context) 2980 | at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInterna 2981 | ][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcCo 2982 | ext) 2983 | at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame) 2984 | at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) 2985 | C:\> 2986 | ``` 2987 | #### Error Action Preference 2988 | PowerShell halts execution on terminating errors. Error Action Preference allows us to specify the desired behavior for a non-terminating error; it can be scoped at the command level or all the way up to the script level. 2989 | 2990 | Available choices for error action preference: 2991 | 2992 | * SilentlyContinue – error messages are suppressed and execution continues. 2993 | * Stop – forces execution to stop, behaving like a terminating error. 2994 | * Continue – the default option. Errors will display and execution will continue. 2995 | * Inquire – prompt the user for input to see if we should proceed. 2996 | * Ignore – (new in v3) – the error is ignored and not logged to the error stream. Has very restricted usage scenarios. 2997 | 2998 | Example: Set the preference at the script scope to Stop, place the following near the top of the script file: 2999 | ```bash 3000 | PS C:\> $ErrorActionPreference = “Stop” 3001 | ``` 3002 | Example: Set the preference at the cmdlet level to Inquire, add error action switch (or alias EA): 3003 | ```bash 3004 | PS C:\> Get-ChildItem "D:\No Such Directory" -ErrorAction "Inquire" 3005 | 3006 | Confirm 3007 | Cannot find drive. A drive with the name 'D' does not exist. 3008 | [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): Y 3009 | Get-ChildItem : Cannot find drive. A drive with the name 'D' does not exist. 3010 | At line:1 char:1 3011 | + Get-ChildItem "D:\No Such Directory" -ErrorAction "Inquire" 3012 | + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3013 | + CategoryInfo : ObjectNotFound: (D:String) [Get-ChildItem], DriveNotFoundException 3014 | + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand 3015 | 3016 | ``` 3017 | 3018 | #### Try/Catch/Finally Blocks: 3019 | The behavior of try/catch is to catch terminating errors (exceptions). This means Non-terminating (operational) errors inside a try block will not trigger a Catch*. If you would like to catch all possible errors (terminating and non-terminating) – then simply set the error action preference to Stop. Remember that Stop error action forces a non-terminating error to behave like a terminating error, which means it can then be trapped in a catch block. 3020 | ```bash 3021 | PS C:\> try 3022 | { 3023 | <# 3024 | Add dangerous code here that might produce exceptions. 3025 | Place as many code statements as needed here. 3026 | Non-terminating errors must have error action preference set to Stop to be caught. 3027 | #> 3028 | 3029 | write-host “Attempting dangerous operation” 3030 | $content = get-content -Path “C:\SomeFolder\This_File_Might_Not_Exist.txt” -ErrorAction Stop 3031 | } 3032 | catch 3033 | { 3034 | <# 3035 | You can have multiple catch blocks (for different exceptions), or one single catch. 3036 | The last error record is available inside the catch block under the $_ variable. 3037 | Code inside this block is used for error handling. Examples include logging an error, 3038 | sending an email, writing to the event log, performing a recovery action, etc. 3039 | In this example I’m just printing the exception type and message to the screen. 3040 | #> 3041 | 3042 | write-host “Caught an exception:” -ForegroundColor Red 3043 | write-host “Exception Type: $($_.Exception.GetType().FullName)” -ForegroundColor Red 3044 | write-host “Exception Message: $($_.Exception.Message)” -ForegroundColor Red 3045 | } 3046 | finally 3047 | { 3048 | <# 3049 | Any statements in this block will always run even if errors are caught. 3050 | This statement block is optional. Normally used for cleanup and 3051 | releasing resources that must happen even under error situations. 3052 | #> 3053 | 3054 | write-host “Finally block reached” 3055 | } 3056 | Attempting dangerous operation 3057 | Caught an exception: 3058 | Exception Type: System.Management.Automation.ItemNotFoundException 3059 | Exception Message: Cannot find path 'C:\SomeFolder\This_File_Might_Not_Exist.txt 3060 | ' because it does not exist. 3061 | Finally block reached 3062 | ``` 3063 | `Finally` block is option; but `try` and `catch` blocks are essential for handling exceptions. 3064 | 3065 | ```bash 3066 | PS C:\> write-Host $(1/0) 3067 | Attempted to divide by zero. 3068 | At line:1 char:14 3069 | + write-Host $(1/0) 3070 | + ~~~ 3071 | + CategoryInfo : NotSpecified: (:) [], RuntimeException 3072 | + FullyQualifiedErrorId : RuntimeException 3073 | 3074 | ``` 3075 | Catching this exception 3076 | ```bash 3077 | PS C:\> try 3078 | { 3079 | write-Host $(1/0) 3080 | } 3081 | catch 3082 | { 3083 | write-Host "This is an Exception" 3084 | } 3085 | 3086 | This is an Exception 3087 | ``` 3088 | Displaying the actual exception 3089 | ```bash 3090 | PS C:\> try 3091 | { 3092 | write-Host $(1/0) 3093 | } 3094 | catch 3095 | { 3096 | write-Host $_.Exception 3097 | } 3098 | 3099 | System.Management.Automation.RuntimeException: Attempted to divide by zero. ---> 3100 | System.DivideByZeroException: Attempted to divide by zero. 3101 | --- End of inner exception stack trace --- 3102 | at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(Fu 3103 | nctionContext funcContext, Exception exception) 3104 | at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(Inter 3105 | pretedFrame frame) 3106 | at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.R 3107 | un(InterpretedFrame frame) 3108 | at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.R 3109 | un(InterpretedFrame frame) 3110 | ``` 3111 | Handling the exception with the appropriate exception type: 3112 | ```bash 3113 | PS C:\> try 3114 | { 3115 | write-Host $(1/0) 3116 | } 3117 | catch [System.Management.Automation.RuntimeException] 3118 | { 3119 | write-Host "This is Run-time Exception" 3120 | } 3121 | catch 3122 | { 3123 | write-Host "Other Exception" 3124 | } 3125 | This is Run-time Exception 3126 | 3127 | ``` 3128 | To get all the exceptions 3129 | ```bash 3130 | PS C:\> [appdomain]::CurrentDomain.GetAssemblies() | ForEach { 3131 | Try { 3132 | $_.GetExportedTypes() | Where { 3133 | $_.Fullname -match 'Exception' 3134 | } 3135 | } Catch {} 3136 | } | Select FullName 3137 | 3138 | FullName 3139 | -------- 3140 | System.AggregateException 3141 | System.Exception 3142 | System.SystemException 3143 | System.OutOfMemoryException 3144 | System.StackOverflowException 3145 | System.DataMisalignedException 3146 | System.ExecutionEngineException 3147 | System.MemberAccessException 3148 | System.AccessViolationException 3149 | System.ApplicationException 3150 | System.AppDomainUnloadedException 3151 | System.ArgumentException 3152 | System.ArgumentNullException 3153 | System.ArgumentOutOfRangeException 3154 | System.ArithmeticException 3155 | System.ArrayTypeMismatchException 3156 | System.BadImageFormatException 3157 | System.CannotUnloadAppDomainException 3158 | System.TypeUnloadedException 3159 | System.ContextMarshalException 3160 | System.DivideByZeroException 3161 | System.DuplicateWaitObjectException 3162 | System.EntryPointNotFoundException 3163 | System.DllNotFoundException 3164 | System.FieldAccessException 3165 | System.FormatException 3166 | System.IndexOutOfRangeException 3167 | System.InsufficientMemoryException 3168 | System.InsufficientExecutionStackException 3169 | System.InvalidCastException 3170 | System.InvalidOperationException 3171 | System.InvalidProgramException 3172 | System.InvalidTimeZoneException 3173 | System.MethodAccessException 3174 | System.MissingFieldException 3175 | System.MissingMemberException 3176 | System.MissingMethodException 3177 | System.MulticastNotSupportedException 3178 | System.NotFiniteNumberException 3179 | System.NotImplementedException 3180 | System.NotSupportedException 3181 | System.NullReferenceException 3182 | System.ObjectDisposedException 3183 | System.OperationCanceledException 3184 | System.OverflowException 3185 | System.PlatformNotSupportedException 3186 | System.RankException 3187 | System.TimeoutException 3188 | System.TimeZoneNotFoundException 3189 | System.TypeAccessException 3190 | System.TypeInitializationException 3191 | System.TypeLoadException 3192 | System.UnauthorizedAccessException 3193 | System.UnhandledExceptionEventArgs 3194 | System.UnhandledExceptionEventHandler 3195 | System.IO.DirectoryNotFoundException 3196 | System.IO.DriveNotFoundException 3197 | System.IO.EndOfStreamException 3198 | System.IO.FileLoadException 3199 | System.IO.FileNotFoundException 3200 | System.IO.IOException 3201 | System.IO.PathTooLongException 3202 | System.IO.IsolatedStorage.IsolatedStorageException 3203 | System.Security.XmlSyntaxException 3204 | System.Security.SecurityException 3205 | System.Security.HostProtectionException 3206 | System.Security.VerificationException 3207 | System.Security.AccessControl.PrivilegeNotHeldException 3208 | System.Security.Cryptography.CryptographicException 3209 | System.Security.Cryptography.CryptographicUnexpectedOperationException 3210 | System.Security.Principal.IdentityNotMappedException 3211 | System.Security.Policy.PolicyException 3212 | System.Resources.MissingManifestResourceException 3213 | System.Resources.MissingSatelliteAssemblyException 3214 | System.Globalization.CultureNotFoundException 3215 | System.Diagnostics.Tracing.EventSourceException 3216 | System.Collections.Generic.KeyNotFoundException 3217 | System.Threading.AbandonedMutexException 3218 | System.Threading.LockRecursionException 3219 | System.Threading.SemaphoreFullException 3220 | System.Threading.SynchronizationLockException 3221 | System.Threading.ThreadAbortException 3222 | System.Threading.ThreadInterruptedException 3223 | System.Threading.ThreadStateException 3224 | System.Threading.ThreadStartException 3225 | System.Threading.WaitHandleCannotBeOpenedException 3226 | System.Threading.Tasks.TaskCanceledException 3227 | System.Threading.Tasks.TaskSchedulerException 3228 | System.Threading.Tasks.UnobservedTaskExceptionEventArgs 3229 | System.Reflection.AmbiguousMatchException 3230 | System.Reflection.CustomAttributeFormatException 3231 | System.Reflection.InvalidFilterCriteriaException 3232 | System.Reflection.ExceptionHandlingClauseOptions 3233 | System.Reflection.ExceptionHandlingClause 3234 | System.Reflection.ReflectionTypeLoadException 3235 | System.Reflection.TargetException 3236 | System.Reflection.TargetInvocationException 3237 | System.Reflection.TargetParameterCountException 3238 | System.Reflection.Emit.ExceptionHandler 3239 | System.Runtime.Serialization.SerializationException 3240 | System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute 3241 | System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs 3242 | System.Runtime.ExceptionServices.ExceptionDispatchInfo 3243 | System.Runtime.Remoting.RemotingException 3244 | System.Runtime.Remoting.ServerException 3245 | System.Runtime.Remoting.RemotingTimeoutException 3246 | System.Runtime.CompilerServices.RuntimeWrappedException 3247 | System.Runtime.InteropServices.COMException 3248 | System.Runtime.InteropServices.ExternalException 3249 | System.Runtime.InteropServices._Exception 3250 | System.Runtime.InteropServices.InvalidOleVariantTypeException 3251 | System.Runtime.InteropServices.MarshalDirectiveException 3252 | System.Runtime.InteropServices.SEHException 3253 | System.Runtime.InteropServices.InvalidComObjectException 3254 | System.Runtime.InteropServices.SafeArrayRankMismatchException 3255 | System.Runtime.InteropServices.SafeArrayTypeMismatchException 3256 | System.Text.DecoderExceptionFallback 3257 | System.Text.DecoderExceptionFallbackBuffer 3258 | System.Text.DecoderFallbackException 3259 | System.Text.EncoderExceptionFallback 3260 | System.Text.EncoderExceptionFallbackBuffer 3261 | System.Text.EncoderFallbackException 3262 | System.Windows.Forms.UnhandledExceptionMode 3263 | System.Windows.Forms.ThreadExceptionDialog 3264 | System.Windows.Forms.AxHost+InvalidActiveXStateException 3265 | System.UriFormatException 3266 | System.Configuration.ConfigurationException 3267 | System.Configuration.SettingsPropertyIsReadOnlyException 3268 | System.Configuration.SettingsPropertyNotFoundException 3269 | System.Configuration.SettingsPropertyWrongTypeException 3270 | System.Net.CookieException 3271 | System.Net.HttpListenerException 3272 | System.Net.ProtocolViolationException 3273 | System.Net.WebException 3274 | System.Net.WebExceptionStatus 3275 | System.Net.WebSockets.WebSocketException 3276 | System.Net.Mail.SmtpException 3277 | System.Net.Mail.SmtpFailedRecipientException 3278 | System.Net.Mail.SmtpFailedRecipientsException 3279 | System.Net.NetworkInformation.NetworkInformationException 3280 | System.Net.NetworkInformation.PingException 3281 | System.Net.Sockets.SocketException 3282 | System.Security.Authentication.AuthenticationException 3283 | System.Security.Authentication.InvalidCredentialException 3284 | System.Threading.BarrierPostPhaseException 3285 | System.Threading.ThreadExceptionEventArgs 3286 | System.Threading.ThreadExceptionEventHandler 3287 | System.IO.InvalidDataException 3288 | System.IO.InternalBufferOverflowException 3289 | System.ComponentModel.InvalidAsynchronousStateException 3290 | System.ComponentModel.InvalidEnumArgumentException 3291 | System.ComponentModel.LicenseException 3292 | System.ComponentModel.WarningException 3293 | System.ComponentModel.Win32Exception 3294 | System.ComponentModel.Design.CheckoutException 3295 | System.CodeDom.CodeThrowExceptionStatement 3296 | System.Text.RegularExpressions.RegexMatchTimeoutException 3297 | System.Drawing.Printing.InvalidPrinterException 3298 | System.Management.Automation.RuntimeException 3299 | System.Management.Automation.ScriptRequiresException 3300 | System.Management.Automation.RemoteException 3301 | System.Management.Automation.Runspaces.TypeTableLoadException 3302 | System.Management.Automation.ExtendedTypeSystemException 3303 | System.Management.Automation.MethodException 3304 | System.Management.Automation.MethodInvocationException 3305 | System.Management.Automation.GetValueException 3306 | System.Management.Automation.PropertyNotFoundException 3307 | System.Management.Automation.GetValueInvocationException 3308 | System.Management.Automation.SetValueException 3309 | System.Management.Automation.SetValueInvocationException 3310 | System.Management.Automation.PSInvalidCastException 3311 | System.Management.Automation.SettingValueExceptionEventArgs 3312 | System.Management.Automation.GettingValueExceptionEventArgs 3313 | Microsoft.PowerShell.Commands.HelpCategoryInvalidException 3314 | Microsoft.PowerShell.Commands.HelpNotFoundException 3315 | System.Management.Automation.Runspaces.InvalidRunspaceStateException 3316 | System.Management.Automation.Runspaces.RunspaceOpenModuleLoadException 3317 | System.Management.Automation.Runspaces.InvalidPipelineStateException 3318 | System.Management.Automation.InvalidPowerShellStateException 3319 | System.Management.Automation.Runspaces.InvalidRunspacePoolStateException 3320 | System.Management.Automation.InvalidJobStateException 3321 | System.Management.Automation.JobFailedException 3322 | System.Management.Automation.Remoting.PSRemotingDataStructureException 3323 | System.Management.Automation.Remoting.PSRemotingTransportException 3324 | System.Management.Automation.Remoting.PSRemotingTransportRedirectException 3325 | System.Management.Automation.Runspaces.RunspaceConfigurationAttributeException 3326 | System.Management.Automation.Runspaces.RunspaceConfigurationTypeException 3327 | System.Management.Automation.WildcardPatternException 3328 | System.Management.Automation.FlowControlException 3329 | System.Management.Automation.LoopFlowException 3330 | System.Management.Automation.BreakException 3331 | System.Management.Automation.ContinueException 3332 | System.Management.Automation.ExitException 3333 | System.Management.Automation.ScriptBlockToPowerShellNotSupportedException 3334 | System.Management.Automation.PSSecurityException 3335 | System.Management.Automation.Runspaces.PSConsoleLoadException 3336 | System.Management.Automation.Runspaces.PSSnapInException 3337 | System.Management.Automation.CommandNotFoundException 3338 | System.Management.Automation.ApplicationFailedException 3339 | System.Management.Automation.CmdletInvocationException 3340 | System.Management.Automation.CmdletProviderInvocationException 3341 | System.Management.Automation.PipelineStoppedException 3342 | System.Management.Automation.PipelineClosedException 3343 | System.Management.Automation.ActionPreferenceStopException 3344 | System.Management.Automation.ParentContainsErrorRecordException 3345 | System.Management.Automation.RedirectedException 3346 | System.Management.Automation.ScriptCallDepthException 3347 | System.Management.Automation.PipelineDepthException 3348 | System.Management.Automation.HaltCommandException 3349 | System.Management.Automation.Host.HostException 3350 | System.Management.Automation.Host.PromptingException 3351 | System.Management.Automation.MetadataException 3352 | System.Management.Automation.ValidationMetadataException 3353 | System.Management.Automation.ArgumentTransformationMetadataException 3354 | System.Management.Automation.ParsingMetadataException 3355 | System.Management.Automation.PSArgumentException 3356 | System.Management.Automation.PSArgumentNullException 3357 | System.Management.Automation.PSArgumentOutOfRangeException 3358 | System.Management.Automation.PSInvalidOperationException 3359 | System.Management.Automation.PSNotImplementedException 3360 | System.Management.Automation.PSNotSupportedException 3361 | System.Management.Automation.PSObjectDisposedException 3362 | System.Management.Automation.ParameterBindingException 3363 | System.Management.Automation.ParseException 3364 | System.Management.Automation.IncompleteParseException 3365 | System.Management.Automation.ProviderInvocationException 3366 | System.Management.Automation.SessionStateException 3367 | System.Management.Automation.SessionStateOverflowException 3368 | System.Management.Automation.SessionStateUnauthorizedAccessException 3369 | System.Management.Automation.ProviderNotFoundException 3370 | System.Management.Automation.ProviderNameAmbiguousException 3371 | System.Management.Automation.DriveNotFoundException 3372 | System.Management.Automation.ItemNotFoundException 3373 | System.Management.Automation.Runspaces.FormatTableLoadException 3374 | System.Management.Instrumentation.InstrumentationBaseException 3375 | System.Management.Instrumentation.InstrumentationException 3376 | System.Management.Instrumentation.InstanceNotFoundException 3377 | System.Diagnostics.Eventing.Reader.EventLogException 3378 | System.Diagnostics.Eventing.Reader.EventLogNotFoundException 3379 | System.Diagnostics.Eventing.Reader.EventLogReadingException 3380 | System.Diagnostics.Eventing.Reader.EventLogProviderDisabledException 3381 | System.Diagnostics.Eventing.Reader.EventLogInvalidDataException 3382 | System.ComponentModel.Composition.CompositionContractMismatchException 3383 | System.ComponentModel.Composition.ImportCardinalityMismatchException 3384 | System.ComponentModel.Composition.ChangeRejectedException 3385 | System.ComponentModel.Composition.CompositionException 3386 | System.ComponentModel.Composition.Primitives.ComposablePartException 3387 | System.Windows.ExceptionRoutedEventArgs 3388 | System.Windows.ResourceReferenceKeyNotFoundException 3389 | System.Windows.Data.UpdateSourceExceptionFilterCallback 3390 | System.Windows.Data.ValueUnavailableException 3391 | System.Windows.Markup.XamlParseException 3392 | System.Windows.Controls.ExceptionValidationRule 3393 | System.Windows.Controls.PrintDialogException 3394 | System.Security.RightsManagement.RightsManagementException 3395 | System.Windows.Threading.DispatcherUnhandledExceptionEventArgs 3396 | System.Windows.Threading.DispatcherUnhandledExceptionEventHandler 3397 | System.Windows.Threading.DispatcherUnhandledExceptionFilterEventArgs 3398 | System.Windows.Threading.DispatcherUnhandledExceptionFilterEventHandler 3399 | System.IO.FileFormatException 3400 | System.Windows.Media.InvalidWmpVersionException 3401 | System.Windows.Media.ExceptionEventArgs 3402 | System.Windows.Media.Animation.AnimationException 3403 | System.Xaml.XamlException 3404 | System.Xaml.XamlParseException 3405 | System.Xaml.XamlObjectWriterException 3406 | System.Xaml.XamlDuplicateMemberException 3407 | System.Xaml.XamlInternalException 3408 | System.Xaml.XamlSchemaException 3409 | System.Xaml.XamlObjectReaderException 3410 | System.Xaml.XamlXmlWriterException 3411 | System.Configuration.ConfigurationErrorsException 3412 | System.Configuration.Provider.ProviderException 3413 | System.Xml.XmlException 3414 | System.Xml.Schema.XmlSchemaException 3415 | System.Xml.Schema.XmlSchemaValidationException 3416 | System.Xml.Schema.XmlSchemaInferenceException 3417 | System.Xml.Xsl.XsltException 3418 | System.Xml.Xsl.XsltCompileException 3419 | System.Xml.XPath.XPathException 3420 | System.Runtime.Serialization.InvalidDataContractException 3421 | System.DirectoryServices.DirectoryServicesCOMException 3422 | System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundException 3423 | System.DirectoryServices.ActiveDirectory.ActiveDirectoryOperationException 3424 | System.DirectoryServices.ActiveDirectory.ActiveDirectoryServerDownException 3425 | System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectExistsException 3426 | System.DirectoryServices.ActiveDirectory.SyncFromAllServersOperationException 3427 | System.DirectoryServices.ActiveDirectory.ForestTrustCollisionException 3428 | System.Management.ManagementException 3429 | Microsoft.Management.Infrastructure.CimException 3430 | System.Configuration.Install.InstallException 3431 | System.Transactions.TransactionException 3432 | System.Transactions.TransactionAbortedException 3433 | System.Transactions.TransactionInDoubtException 3434 | System.Transactions.TransactionManagerCommunicationException 3435 | System.Transactions.TransactionPromotionException 3436 | Microsoft.PowerShell.Commands.CertificateProviderItemNotFoundException 3437 | Microsoft.PowerShell.Commands.CertificateNotFoundException 3438 | Microsoft.PowerShell.Commands.CertificateStoreNotFoundException 3439 | Microsoft.PowerShell.Commands.CertificateStoreLocationNotFoundException 3440 | Microsoft.Management.UI.Internal.FilterExceptionEventArgs 3441 | System.Windows.Automation.ProxyAssemblyNotLoadedException 3442 | System.Windows.Automation.NoClickablePointException 3443 | System.Windows.Automation.ElementNotEnabledException 3444 | System.Windows.Automation.ElementNotAvailableException 3445 | Microsoft.SqlServer.Server.InvalidUdtException 3446 | System.Data.StrongTypingException 3447 | System.Data.TypedDataSetGeneratorException 3448 | System.Data.DataException 3449 | System.Data.ConstraintException 3450 | System.Data.DeletedRowInaccessibleException 3451 | System.Data.DuplicateNameException 3452 | System.Data.InRowChangingEventException 3453 | System.Data.InvalidConstraintException 3454 | System.Data.MissingPrimaryKeyException 3455 | System.Data.NoNullAllowedException 3456 | System.Data.ReadOnlyException 3457 | System.Data.RowNotInTableException 3458 | System.Data.VersionNotFoundException 3459 | System.Data.DBConcurrencyException 3460 | System.Data.InvalidExpressionException 3461 | System.Data.EvaluateException 3462 | System.Data.SyntaxErrorException 3463 | System.Data.OperationAbortedException 3464 | System.Data.SqlTypes.SqlTypeException 3465 | System.Data.SqlTypes.SqlNullValueException 3466 | System.Data.SqlTypes.SqlTruncateException 3467 | System.Data.SqlTypes.SqlNotFilledException 3468 | System.Data.SqlTypes.SqlAlreadyFilledException 3469 | System.Data.SqlClient.SqlException 3470 | System.Data.OleDb.OleDbException 3471 | System.Data.Odbc.OdbcException 3472 | System.Data.Common.DbException 3473 | Microsoft.PowerShell.Commands.WriteErrorException 3474 | Microsoft.PowerShell.Commands.StringManipulation.FlashExtractWrapper.FlashEx... 3475 | Microsoft.PowerShell.Commands.StringManipulation.FlashExtractWrapper.FlashEx... 3476 | Microsoft.PowerShell.Commands.StringManipulation.FlashExtractWrapper.Templat... 3477 | Microsoft.PowerShell.Commands.ProcessCommandException 3478 | Microsoft.PowerShell.Commands.ServiceCommandException 3479 | Microsoft.PowerShell.Commands.RestartComputerTimeoutException 3480 | Microsoft.PowerShell.Cmdletization.Cim.CimJobException 3481 | Microsoft.CSharp.RuntimeBinder.RuntimeBinderException 3482 | Microsoft.CSharp.RuntimeBinder.RuntimeBinderInternalCompilerException 3483 | System.ServiceProcess.TimeoutException 3484 | ``` 3485 | 3486 | #### Handling Errors from non-PowerShell processes 3487 | when exception occurs while executing external processes like .exe execution, ..., they can be handled using **$LastExitCode** powerShell variable. 3488 | 3489 | when the launched process exits, powerShell will write the exit code directly to `$LastExitCode` 3490 | In most cases, exit code `0` means `Success`, and `1` means `failure`. 3491 | 3492 | 3493 | ## 10. Working with cmdlets 3494 | #### 10.1 Finding and Learning Commands 3495 | #### 10.2 Working with the Pipeline 3496 | #### 10.2.1 Passing Data in the Pipeline By Value 3497 | #### 10.3 Selecting, Sorting, and Measuring Objects 3498 | #### 10.4 Converting, Exporting, and Importing Objects 3499 | #### 10.5 Filtering and Validating Objects Out of the Pipeline 3500 | TODO Filter-Object 3501 | 3502 | Where-Object 3503 | ``` 3504 | PS C:\> (1..15) | Where-Object { $_ -gt 10 } 3505 | 11 3506 | 12 3507 | 13 3508 | 14 3509 | 15 3510 | PS C:\> (1..15).Where{ $_ -gt 10 } # Possible from version 4.0 3511 | 11 3512 | 12 3513 | 13 3514 | 14 3515 | 15 3516 | ``` 3517 | #### 10.6 Enumerating Objects in the Pipeline 3518 | #### 10.7 Formatting Output 3519 | #### 10.7.1 Using Basic Formatting 3520 | #### 10.7.2 Using Advanced Formatting 3521 | #### 10.7.3 Redirecting Formatted Output 3522 | #### 10.8 Working with date and time 3523 | #### 10.9 File Handling 3524 | 3525 | #### 10.10 Aliases in PowerShell 3526 | TODO creating , reading and writing to files 3527 | 3528 | 3529 | To get all the profiles in the machine 3530 | ``` 3531 | PS C:\> Resolve-Path -Path C:\users\*\Desktop -ErrorAction SilentlyContinue 3532 | 3533 | Path 3534 | ---- 3535 | C:\users\Administrator.JAINABHISHEK\Desktop 3536 | C:\users\JAINABHISHEK\Desktop 3537 | C:\users\Public\Desktop 3538 | 3539 | ``` 3540 | To get only the names, and not the paths, 3541 | ``` 3542 | PS C:\> Resolve-Path -Path C:\users\*\Desktop -ErrorAction SilentlyContinue | 3543 | >> ForEach-Object { 3544 | >> $_.Path.Split('\')[-2] 3545 | >> } 3546 | >> 3547 | Administrator.JAINABHISHEK 3548 | JAINABHISHEK 3549 | Public 3550 | 3551 | ``` 3552 | 3553 | ## 11. Working with Windows Interfaces 3554 | #### 11.1 Managing services and Processes 3555 | #### 11.2 working with WMI and Other windows APIs 3556 | #### 11.3 Working with MS Word, MS Excel and Speach products 3557 | ## 12. Windows Remoting 3558 | #### 12.1 Working with winrm service 3559 | #### 12.2 Connecting to the remote windows server and managing the services 3560 | #### 12.3 Connecting to the remote Linux server and managing the services 3561 | ## 13. Advanced PowerShell Techniques 3562 | #### 13.1 Using Background Jobs and Scheduled Jobs 3563 | #### 13.2 Using PSProviders and PSDrives 3564 | 3565 | ## 14. Other Modules 3566 | #### 14.1 ShowUI 3567 | ``` 3568 | PS C:\> $User = [ordered]@{ 3569 | FirstName = "jain" 3570 | LastName = "abhishek" 3571 | BirthDate = [DateTime] 3572 | UserName = "jainabhishek" 3573 | } 3574 | 3575 | $data = Get-Input $User -Show 3576 | Write-Host $data 3577 | #System.Collections.Hashtable 3578 | 3579 | PS C:\> $data 3580 | 3581 | Name Value 3582 | ---- ----- 3583 | UserName jainabhishek 3584 | FirstName jain 3585 | LastName abhishek 3586 | BirthDate 6/16/2017 2:52:11 PM 3587 | ``` 3588 | --------------------------------------------------------------------------------