Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Review help-topic example code for best practices, such as avoiding unnecessary $(...) #5031

Closed
mklement0 opened this issue Oct 30, 2019 · 0 comments · Fixed by #5180
Closed
Assignees
Labels
area-language Area - PowerShell syntax and keywords

Comments

@mklement0
Copy link
Contributor

The practices shown in example code are important, because inexperienced users will naturally assume that such code reflects best practices.

This is currently not always the case, as the following example demonstrates; in addition to this specific case, I think a systematic review of example code is worth doing.


The Compare-Object topic currently contains this hashtable definition:

$objects = @{
 ReferenceObject = $(Get-Content -Path C:\Test\Testfile1.txt)
 DifferenceObject = $(Get-Content -Path C:\Test\Testfile2.txt)
}

Not only is the $(...) around the Get-Content commands unnecessary, using $(...) has the potential to modify the command's output.

Note: There is very specific Windows PowerShell bug where an if statement without an else block in a hashtable literal fails without $(...), but only if the if statement isn't the last entry.

To use a contrived example:

PS> @{ foo = $(, 1) }.foo.GetType().Name
Int32  # Single-element array was unwrapped by $()

Similarly, (...), not $(...), should be used when output from a single command or expression is passed as a command argument (e.g., Write-Output (Get-Date), not Write-Output $(Get-Date).


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-language Area - PowerShell syntax and keywords
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants