Skip to content

Commit 8d54c00

Browse files
authored
Merge pull request #162 from richy58729/master
Several suggestions to make it better
2 parents 530f780 + 3f9f225 commit 8d54c00

10 files changed

+90
-118
lines changed

Best-Practices/Building-Reusable-Tools.md

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,18 @@
22

33
For this discussion, it's important to have some agreed-upon terminology. While the terminology here isn't used universally, the community generally agrees that several types of "script" exist:
44

5-
1. Some scripts contain tools, when are meant to be reusable. These are typically functions or advanced functions, and they are typically contained in a script module or in a function library of some kind. These tools are designed for a high level of re-use.
6-
2. Some scripts are controllers, meaning they are intended to utilize one or more tools (functions, commands, etc) to automate a specific business process. A script is not intended to be reusable; it is intended to make use of reuse by leveraging functions and other commands
5+
1. Some scripts contain tools, which are meant to be reusable. These are typically functions or advanced functions, and they are typically contained in a script module or in a function library of some kind. These tools are designed for a high level of reuse.
6+
2. Some scripts are controllers, meaning they are intended to utilize one or more tools (functions, commands, etc) to automate a specific business process. A controller script is not intended to be reusable; it is intended to make use of reuse by leveraging functions and other commands.
77

88
For example, you might write a "New-CorpUser" script, which provisions new users. In it, you might call numerous commands and functions to create a user account, mailbox-enable them, provision a home folder, and so on. Those discrete tasks might also be used in other processes, so you build them as functions. The script is only intended to automate that one process, and so it doesn't need to exhibit reusability concepts. It's a standalone thing.
99

10-
Controllers, on the other hand, often produce output directly to the screen (when designed for interactive use), or may log to a file (when designed to run unattended).
11-
10+
Controllers often produce output directly to the screen (when designed for interactive use), or may log to a file (when designed to run unattended).
1211

1312
# TOOL-02 Make your code modular
1413

1514
Generally, people tend to feel that most working code - that is, your code which does things - should be modularized into functions and ideally stored in script modules.
1615

17-
That makes those functions more easily re-used. Those functions should exhibit a high level of reusability, such as accepting input only via parameters and producing output only as objects to the pipeline
18-
16+
That makes those functions more easily reused. Those functions should exhibit a high level of reusability, such as accepting input only via parameters and producing output only as objects to the pipeline.
1917

2018
# TOOL-03 Make tools as re-usable as possible
2119

@@ -29,9 +27,9 @@ You can get a list of the verbs by typing 'get-verb' at the command line.
2927

3028
# TOOL-05 Use PowerShell standard parameter naming
3129

32-
Tools should be consistent with PowerShell native cmdlets in regards parameter naming.
30+
Tools should be consistent with PowerShell native cmdlets in regard to parameter naming.
3331

34-
For example, use $ComputerName and $ServerInstance rather than something like $Param_Computer or $InstanceName
32+
For example, use $ComputerName and $ServerInstance rather than something like $Param_Computer or $InstanceName.
3533

3634
# TOOL-06 Tools should output raw data
3735

@@ -45,7 +43,6 @@ For example, a function named Get-DiskInfo would return disk sizing information
4543

4644
An intermediate step is useful for tools that are packaged in script modules: views. By building a manifest for the module, you can have the module also include a custom .format.ps1xml view definition file. The view can specify manipulated data values, such as the default view used by PowerShell to display the output of Get-Process. The view does not manipulate the underlying data, leaving the raw data available for any purpose.
4745

48-
4946
# WAST-01 Don't re-invent the wheel
5047

5148
There are a number of approaches in PowerShell that will "get the job done." In some cases, other community members may have already written the code to achieve your objectives. If that code meets your needs, then you might save yourself some time by leveraging it, instead of writing it yourself.
@@ -77,15 +74,12 @@ It has been argued by some that, "I didn't know such-and-such existed, so I wrot
7774

7875
On the flip side, it's important to note that writing your own code from the ground up can be useful if you are trying to learn a particular concept, or if you have specific needs that are not offered by another existing solution.
7976

80-
8177
# WAST-02 Report bugs to Microsoft
8278

8379
An exception: if you know that a built-in technique doesn't work properly (e.g., it is buggy or doesn't accomplish the exact task), then obviously it's fine to re-invent the wheel. However, in cases where you're doing so to avoid a bug or design flaw, then you should - as an upstanding member of the community - report the bug on [github.com/powershell](https://github.com/PowerShell/PowerShell/issues) also.
8480

85-
8681
TODO: The "PURE" section is dubious at best. We need to discuss it.
8782

88-
8983
# PURE-01 Use native PowerShell where possible
9084

9185
This means not using COM, .NET Framework classes, and so on when there is a native Windows PowerShell command or technique that gets the job done.
@@ -103,4 +97,3 @@ Document the reason for using tools other than PowerShell in your comments.
10397
That said, you truly become a better PowerShell person if you take the time to wrap a less-preferred way in an advanced function or cmdlet. Then you get the best of both worlds: the ability to reach outside the shell itself for functionality, while keeping the advantages of native commands.
10498

10599
Ignorance, however, is no excuse. If you've written some big wrapper function around Ping.exe simply because you were unaware of Test-Connection, then you've wasted a lot of time, and that is not commendable. Before you move on to a less-preferred approach, make sure the shell doesn't already have a way to do what you're after.
106-

Best-Practices/Output-and-Formatting.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ TODO: This whole document is STILL ROUGH DRAFT
66

77
Previous to PowerShell 5, Write-Host has no functionality at all in non-interactive scripts. It cannot be captured or redirected, and therefore should only be used in functions which are "Show"ing or "Format"ing output, or to display something as part of an interactive prompt to the user.
88

9-
That is: you should not use Write-Host to create script output unless your script (or function, or whatever) uses the Show verb (as in, Show-Performance) or the Format verb (as in, Format-Hex), or has a `-Formatted` switch parameter. You may also use it to build a interactions with the user in other cases (e.g. to write extra information to the screen before prompting the user for a choice or input).
9+
That is: you should not use Write-Host to create script output unless your script (or function, or whatever) uses the Show verb (as in, Show-Performance) or the Format verb (as in, Format-Hex), or has a `-Formatted` switch parameter. You may also use it to build interactions with the user in other cases (e.g., to write extra information to the screen before prompting the user for a choice or input).
1010

1111
Generally, you should consider the other Write-* commands first when trying to give information to the user.
1212

@@ -22,7 +22,7 @@ You should use verbose output for information that contains details about the va
2222

2323
## Use Write-Debug to give information to someone maintaining your script
2424

25-
You should use the debug output stream for output that is useful for script debugging (ie: "Now entering main loop" or "Result was null, skipping to end of loop"), or to display the value of a variable before a conditional statement, so the maintainer can break into the debugger if necessary.
25+
You should use the debug output stream for output that is useful for script debugging (e.g., "Now entering main loop" or "Result was null, skipping to end of loop"), or to display the value of a variable before a conditional statement, so the maintainer can break into the debugger if necessary.
2626

2727
> TIP: When debugging you should be aware that you can set `$DebugPreference = "Continue"` to see this information on screen without entering a breakpoint prompt.
2828
@@ -48,7 +48,7 @@ When you combine the output of multiple types objects, they should generally be
4848

4949
### Two important exceptions to the single-type rule
5050

51-
**For internal functions** it's ok to return multiple different types because they won't be "output" to the user/host, and can offer significant savings (e.g. one database call with three table joins, instead of three database calls with two or three joins each). You can then call these functions and assign the output to multiple variables, like so:
51+
**For internal functions** it's ok to return multiple different types because they won't be "output" to the user/host, and can offer significant savings (e.g., one database call with three table joins, instead of three database calls with two or three joins each). You can then call these functions and assign the output to multiple variables, like so:
5252

5353
```PowerShell
5454
$user, $group, $org = Get-UserGroupOrg

Best-Practices/Performance.md

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ If you're aware of multiple techniques to accomplish something, and you're writi
77
For example:
88

99
```PowerShell
10-
foreach($result in Do-Something) { $result.PropertyOne + $result.PropertyTwo }
10+
foreach ($result in Do-Something) { $result.PropertyOne + $result.PropertyTwo }
1111
Do-Something | ForEach-Object { $_.PropertyOne + $_.PropertyTwo }
1212
```
1313

@@ -40,7 +40,7 @@ ForEach-Object -Process {
4040
}
4141
```
4242

43-
As described elsewhere in this guide, many folks in the community would dislike this approach for aesthetic reasons. However, this approach has the advantage of utilizing PowerShell's pipeline to "stream" the content in file.txt. Provided that the fictional "Do-Something" command isn't blocking the pipeline (a la Sort-Object), the shell can send lines of content (String objects, technically) through the pipeline in a continuous stream, rather than having to buffer them all into memory.
43+
As described elsewhere in this guide, many folks in the community would dislike this approach for aesthetic reasons. However, this approach has the advantage of utilizing PowerShell's pipeline to "stream" the content in file.txt. Provided that the fictional "Do-Something" command isn't blocking the pipeline (à la Sort-Object), the shell can send lines of content (String objects, technically) through the pipeline in a continuous stream, rather than having to buffer them all into memory.
4444

4545
Some would argue that this second approach is always a poor one, and that if performance is an issue then you should devolve from a PowerShell-native approach into a lower-level .NET Framework approach:
4646

@@ -73,9 +73,8 @@ The moral here is that both aesthetic and performance are important consideratio
7373

7474
This is just a rough guideline, but as a general rule:
7575

76-
1. Language features are faster than features of the .net framework
77-
2. Compiled methods on objects and .net classes are still faster than script
76+
1. Language features are faster than features of the .NET Framework
77+
2. Compiled methods on objects and .NET classes are still faster than script
7878
3. Simple PowerShell script is still faster than calling functions or cmdlets
7979

8080
It's counter-intuitive that script is faster than calling cmdlets that are compiled, but it's frequently true, unless there is a lot of work being done by each cmdlet. The overhead of calling cmdlets and passing data around is significant. Of course, this is just a guideline, and you should always **measure**.
81-

Best-Practices/Security.md

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ param (
1616
)
1717
```
1818

19-
If you absolutely must pass a password in a plain string to a .Net API call or a third party library it is better to decrypt the credential as it is being passed instead of saving it in a variable.
19+
If you absolutely must pass a password in a plain string to a .NET API call or a third party library, it is better to decrypt the credential as it is being passed instead of saving it in a variable.
2020

2121
```PowerShell
2222
# Get the cleartext password for a method call:
23-
$Insecure.SetPassword( $Credentials.GetNetworkCredential().Password )
23+
$Insecure.SetPassword($Credentials.GetNetworkCredential().Password)
2424
```
2525

2626
#### Other Secure Strings
@@ -32,10 +32,10 @@ Note, if you ever need to turn a SecureString into a string, you can use this me
3232

3333
```PowerShell
3434
# Decrypt a secure string.
35-
$BSTR = [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($this);
36-
$plaintext = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR);
37-
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR);
38-
return $plaintext
35+
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($this)
36+
$plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
37+
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
38+
$plaintext
3939
```
4040

4141
* For credentials that need to be saved to disk, serialize the credential object using
@@ -63,4 +63,3 @@ computer where it was generated.
6363
# Read the Standard String from disk and convert to a SecureString
6464
$Secure = Get-Content -Path "${Env:AppData}\Sec.bin" | ConvertTo-SecureString
6565
```
66-

0 commit comments

Comments
 (0)