8000 PSScriptAnalyzer fixes by category by bergmeister · Pull Request #4261 · PowerShell/PowerShell · GitHub
[go: up one dir, main page]

Skip to content

PSScriptAnalyzer fixes by category #4261

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

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletions build.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ Fix steps:
log "Run dotnet restore"

$srcProjectDirs = @($Options.Top, "$PSScriptRoot/src/TypeCatalogGen", "$PSScriptRoot/src/ResGen")
$testProjectDirs = Get-ChildItem "$PSScriptRoot/test/*.csproj" -Recurse | % { [System.IO.Path]::GetDirectoryName($_) }
$testProjectDirs = Get-ChildItem "$PSScriptRoot/test/*.csproj" -Recurse | ForEach-Object { [System.IO.Path]::GetDirectoryName($_) }

$RestoreArguments = @("--verbosity")
if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
Expand All @@ -292,7 +292,7 @@ Fix steps:
$RestoreArguments += "quiet"
}

($srcProjectDirs + $testProjectDirs) | % { Start-NativeExecution { dotnet restore $_ $RestoreArguments } }
($srcProjectDirs + $testProjectDirs) | ForEach-Object { Start-NativeExecution { dotnet restore $_ $RestoreArguments } }
}

# handle ResGen
Expand Down Expand Up @@ -354,9 +354,9 @@ Fix steps:

# Compile native resources
$currentLocation = Get-Location
@("nativemsh/pwrshplugin") | % {
@("nativemsh/pwrshplugin") | ForEach-Object {
$nativeResourcesFolder = $_
Get-ChildItem $nativeResourcesFolder -Filter "*.mc" | % {
Get-ChildItem $nativeResourcesFolder -Filter "*.mc" | ForEach-Object {
$command = @"
cmd.exe /C cd /d "$currentLocation" "&" "$($vcVarsPath)\vcvarsall.bat" "$NativeHostArch" "&" mc.exe -o -d -c -U "$($_.FullName)" -h "$nativeResourcesFolder" -r "$nativeResourcesFolder"
"@
Expand Down Expand Up @@ -394,7 +394,7 @@ cmd.exe /C cd /d "$location" "&" "$($vcVarsPath)\vcvarsall.bat" "$NativeHostArch

# Copy the binaries from the local build directory to the packaging directory
$dstPath = ($script:Options).Top
$FilesToCopy | % {
$FilesToCopy | ForEach-Object {
$srcPath = Join-Path (Join-Path (Join-Path (Get-Location) "bin") $msbuildConfiguration) "$clrTarget/$_"
log " Copying $srcPath to $dstPath"
Copy-Item $srcPath $dstPath
Expand Down Expand Up @@ -460,7 +460,7 @@ cmd.exe /C cd /d "$location" "&" "$($vcVarsPath)\vcvarsall.bat" "$NativeHostArch
# publish netcoreapp2.0 reference assemblies
try {
Push-Location "$PSScriptRoot/src/TypeCatalogGen"
$refAssemblies = Get-Content -Path "powershell.inc" | ? { $_ -like "*microsoft.netcore.app*" } | % { $_.TrimEnd(';') }
$refAssemblies = Get-Content -Path "powershell.inc" | Where-Object { $_ -like "*microsoft.netcore.app*" } | ForEach-Object { $_.TrimEnd(';') }
$refDestFolder = Join-Path -Path $publishPath -ChildPath "ref"

if (Test-Path $refDestFolder -PathType Container) {
Expand Down Expand Up @@ -611,7 +611,7 @@ function New-PSOptions {
}

if (-not $Runtime) {
$Runtime = dotnet --info | % {
$Runtime = dotnet --info | ForEach-Object {
if ($_ -match "RID") {
$_ -split "\s+" | Select-Object -Last 1
}
Expand Down Expand Up @@ -668,7 +668,7 @@ function Get-PesterTag {
$alltags = @{}
$warnings = @()

get-childitem -Recurse $testbase -File |?{$_.name -match "tests.ps1"}| %{
get-childitem -Recurse $testbase -File |Where-Object {$_.name -match "tests.ps1"}| ForEach-Object {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a space before Where-Object and after "tests.ps1"}

$fullname = $_.fullname
$tok = $err = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($FullName, [ref]$tok,[ref]$err)
Expand All @@ -684,7 +684,7 @@ function Get-PesterTag {
$warnings += "TAGS must be static strings, error in ${fullname}, line $lineno"
}
$values = $vAst.FindAll({$args[0] -is "System.Management.Automation.Language.StringConstantExpressionAst"},$true).Value
$values | % {
$values | ForEach-Object {
if (@('REQUIREADMINONWINDOWS', 'SLOW') -contains $_) {
# These are valid tags also, but they are not the priority tags
}
Expand Down Expand Up @@ -873,7 +873,7 @@ function Start-PSPester {
{
$lines = Get-Content $outputBufferFilePath | Select-Object -Skip $currentLines
$lines | Write-Host
if ($lines | ? { $_ -eq '__UNELEVATED_TESTS_THE_END__'})
if ($lines | Where-Object { $_ -eq '__UNELEVATED_TESTS_THE_END__'})
{
break
}
Expand Down Expand Up @@ -1816,7 +1816,7 @@ function Publish-NuGetFeed
'Microsoft.WSMan.Management',
'Microsoft.WSMan.Runtime',
'Microsoft.PowerShell.SDK'
) | % {
) | ForEach-Object {
if ($VersionSuffix) {
dotnet pack "src/$_" --output $OutputPath --version-suffix $VersionSuffix /p:IncludeSymbols=true
} else {
Expand Down Expand Up @@ -1947,7 +1947,7 @@ function Copy-MappedFiles {
# Do some intelligence to prevent shooting us in the foot with CL management

# finding base-line CL
$cl = git --git-dir="$PSScriptRoot/.git" tag | % {if ($_ -match 'SD.(\d+)$') {[int]$Matches[1]} } | Sort-Object -Descending | Select-Object -First 1
$cl = git --git-dir="$PSScriptRoot/.git" tag | ForEach-Object {if ($_ -match 'SD.(\d+)$') {[int]$Matches[1]} } | Sort-Object -Descending | Select-Object -First 1
if ($cl) {
log "Current base-line CL is SD:$cl (based on tags)"
} else {
Expand Down Expand Up @@ -1979,7 +1979,7 @@ function Copy-MappedFiles {
}

end {
$map.GetEnumerator() | % {
$map.GetEnumerator() | ForEach-Object {
New-Item -ItemType Directory (Split-Path $_.Value) -ErrorAction SilentlyContinue > $null
Copy-Item $_.Key $_.Value -Verbose:([bool]$PSBoundParameters['Verbose']) -WhatIf:$WhatIf
}
Expand Down Expand Up @@ -2020,7 +2020,7 @@ function Get-Mappings

end {
$map = @{}
$mapFiles | % {
$mapFiles | ForEach-Object {
$file = $_
try {
$rawHashtable = $_ | Get-Content -Raw | ConvertFrom-Json | Convert-PSObjectToHashtable
Expand All @@ -2036,7 +2036,7 @@ function Get-Mappings
$mapRoot = $mapRoot.Replace('\', '/')
}

$rawHashtable.GetEnumerator() | % {
$rawHashtable.GetEnumerator() | ForEach-Object {
$newKey = if ($Root) { Join-Path $Root $_.Key } else { $_.Key }
$newValue = if ($KeepRelativePaths) { ($mapRoot + '/' + $_.Value) } else { Join-Path $mapRoot $_.Value }
$map[$newKey] = $newValue
Expand Down Expand Up @@ -2067,7 +2067,7 @@ function Send-GitDiffToSd {
$patchPath = (ls (Join-Path (get-command git).Source '..\..') -Recurse -Filter 'patch.exe').FullName
$m = Get-Mappings -KeepRelativePaths -Root $AdminRoot
$affectedFiles = git diff --name-only $diffArg1 $diffArg2
$affectedFiles | % {
$affectedFiles | ForEach-Object {
log "Changes in file $_"
}

Expand Down Expand Up @@ -2184,12 +2184,12 @@ function Convert-TxtResourceToXml
)

process {
$Path | % {
Get-ChildItem $_ -Filter "*.txt" | % {
$Path | ForEach-Object {
Get-ChildItem $_ -Filter "*.txt" | ForEach-Object {
$txtFile = $_.FullName
$resxFile = Join-Path (Split-Path $txtFile) "$($_.BaseName).resx"
$resourceHashtable = ConvertFrom-StringData (Get-Content -Raw $txtFile)
$resxContent = $resourceHashtable.GetEnumerator() | % {
$resxContent = $resourceHashtable.GetEnumerator() | ForEach-Object {
@'
<data name="{0}" xml:space="preserve">
<value>{1}</value>
Expand All @@ -2213,7 +2213,7 @@ function Start-XamlGen
)

Use-MSBuild
Get-ChildItem -Path "$PSScriptRoot/src" -Directory | % {
Get-ChildItem -Path "$PSScriptRoot/src" -Directory | ForEach-Object {
$XamlDir = Join-Path -Path $_.FullName -ChildPath Xamls
if ((Test-Path -Path $XamlDir -PathType Container) -and
(@(Get-ChildItem -Path "$XamlDir\*.xaml").Count -gt 0)) {
Expand All @@ -2231,7 +2231,7 @@ function Start-XamlGen
throw "No .cs or .g.resources files are generated for $XamlDir, something went wrong. Run 'Start-XamlGen -Verbose' for details."
}

$filesToCopy | % {
$filesToCopy | ForEach-Object {
$sourcePath = $_.FullName
Write-Verbose "Copy generated xaml artifact: $sourcePath -> $DestinationDir"
Copy-Item -Path $sourcePath -Destination $DestinationDir
Expand Down Expand Up @@ -2293,7 +2293,7 @@ function script:ConvertFrom-Xaml {
log "ConvertFrom-Xaml for $XamlDir"

$Pages = ""
Get-ChildItem -Path "$XamlDir\*.xaml" | % {
Get-ChildItem -Path "$XamlDir\*.xaml" | ForEach-Object {
$Page = $Script:XamlProjPage -f $_.FullName
$Pages += $Page
}
Expand Down
2 changes: 1 addition & 1 deletion demos/Apache/apache-demo.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Import-Module $PSScriptRoot/Apache/Apache.psm1

#list Apache Modules
Write-Host -Foreground Blue "Get installed Apache Modules like *proxy* and Sort by name"
Get-ApacheModule |Where {$_.ModuleName -like "*proxy*"}|Sort-Object ModuleName | Out-Host
Get-ApacheModule | Where-Object {$_.ModuleName -like "*proxy*"}|Sort-Object ModuleName | Out-Host
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add spaces in "*proxy*"}|Sort-Object.


#Graceful restart of Apache
Write-host -Foreground Blue "Restart Apache Server gracefully"
Expand Down
8 changes: 4 additions & 4 deletions demos/Azure/Azure-Demo.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Import-Module AzureRM.NetCore.Preview
Login-AzureRmAccount

### Specify a name for Azure Resource Group
$resourceGroupName = "PSAzDemo" + (New-Guid | % guid) -replace "-",""
$resourceGroupName = "PSAzDemo" + (New-Guid | ForEach-Object guid) -replace "-",""
$resourceGroupName

### Create a new Azure Resource Group
10000 Expand All @@ -26,7 +26,7 @@ New-AzureRmResourceGroup -Name $resourceGroupName -Location "West US"
### Deploy an Ubuntu 14.04 VM using Resource Manager cmdlets
### Template is available at
### http://armviz.io/#/?load=https:%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F101-vm-simple-linux%2Fazuredeploy.json
$dnsLabelPrefix = $resourceGroupName | % tolower
$dnsLabelPrefix = $resourceGroupName | ForEach-Object tolower
$dnsLabelPrefix
$password = ConvertTo-SecureString -String "PowerShellRocks!" -AsPlainText -Force
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile ./Compute-Linux.json -adminUserName psuser -adminPassword $password -dnsLabelPrefix $dnsLabelPrefix
Expand All @@ -39,7 +39,7 @@ Find-AzureRmResource -ResourceGroupName $resourceGroupName | select Name,Resourc

### Get the state of the VM we created
### Notice: The VM is in running state
Get-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName -ODataQuery '$expand=instanceView' | % properties | % instanceview | % statuses
Get-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName -ODataQuery '$expand=instanceView' | ForEach-Object properties | ForEach-Object instanceview | ForEach-Object statuses

### Discover the operations we can perform on the compute resource
### Notice: Operations like "Power Off Virtual Machine", "Start Virtual Machine", "Create Snapshot", "Delete Snapshot", "Delete Virtual Machine"
Expand All @@ -49,7 +49,7 @@ Get-AzureRmProviderOperation -OperationSearchString Microsoft.Compute/* | select
Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Compute/virtualMachines -ResourceName MyUbuntuVM -Action poweroff

### Check the VM state again. It should be stopped now.
Get-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName -ODataQuery '$expand=instanceView' | % properties | % instanceview | % statuses
Get-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName -ODataQuery '$expand=instanceView' | ForEach-Object properties | ForEach-Object instanceview | ForEach-Object statuses

### As you know, you may still be incurring charges even if the VM is in stopped state
### Deallocate the resource to avoid this charge
Expand Down
2 changes: 1 addition & 1 deletion demos/SystemD/journalctl-demo.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ Get-SystemDJournal -args "-xe" |Out-Host

#Drill into SystemD unit messages
Write-host -Foreground Blue "Get recent SystemD journal messages for services and return Unit, Message"
Get-SystemDJournal -args "-xe" | Where {$_._SYSTEMD_UNIT -like "*.service"} | Format-Table _SYSTEMD_UNIT, MESSAGE | Select-Object -first 10 | Out-Host
Get-SystemDJournal -args "-xe" | Where-Object {$_._SYSTEMD_UNIT -like "*.service"} | Format-Table _SYSTEMD_UNIT, MESSAGE | Select-Object -first 10 | Out-Host
2 changes: 1 addition & 1 deletion demos/crontab/CronTab/CronTab.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ function Remove-CronJob {
.DESCRIPTION
Removes the exactly matching cron job from the cron table
.EXAMPLE
Get-CronJob | ? {%_.Command -like 'foo *'} | Remove-CronJob
Get-CronJob | Where-Object {%_.Command -like 'foo *'} | Remove-CronJob
.RETURNVALUE
None
.PARAMETER UserName
Expand Down
2 changes: 1 addition & 1 deletion docs/KNOWNISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Removing the aliases exposes the native command experience to the PowerShell use

Currently, PowerShell only does wildcard expansion (globbing) for built-in cmdlets on Windows, and for external commands or binaries as well as cmdlets on Linux.
This means that a command like `ls *.txt` will fail because the asterisk will not be expanded to match file names.
You can work around this by doing `ls (gci *.txt | % name)` or, more simply, `gci *.txt` using the PowerShell built-in equivalent to `ls`.
You can work around this by doing `ls (gci *.txt | ForEach-Object name)` or, more simply, `gci *.txt` using the PowerShell built-in equivalent to `ls`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As we discussed, this change is not necessary. This is a one-line script to be used interactively. It's OK to use aliases to keep it concise.


See [#954](https://github.com/PowerShell/PowerShell/issues/954) to give us feedback on how to improve the globbing experience on Linux/macOS.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public abstract class ControlPanelItemBaseCommand : PSCmdlet
private static readonly string[] s_controlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" };
private const string TestHeadlessServerScript = @"
$result = $false
$serverManagerModule = Get-Module -ListAvailable | ? {$_.Name -eq 'ServerManager'}
$serverManagerModule = Get-Module -ListAvailable | Where-Object {$_.Name -eq 'ServerManager'}
if ($serverManagerModule -ne $null)
{
Import-Module ServerManager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2138,9 +2138,9 @@ private static ConcurrentDictionary<string, string> InitializeStrongNameDictiona
// 10,000 iterations of this method takes ~800 ms for a string array, and ~ 200ms for the dictionary
//
// $dlls = ((dir c:\windows\Microsoft.NET\Framework\ -fi *.dll -rec) + (dir c:\windows\assembly -fi *.dll -rec)) + (dir C:\Windows\Microsoft.NET\assembly) |
// % { [Reflection.Assembly]::LoadFrom($_.FullName) }
// ForEach-Object { [Reflection.Assembly]::LoadFrom($_.FullName) }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These changes probably should be reverted, as dir is still used here and short form of parameters are also used such as -fi, -rec and -u. It's OK to use aliases in cases like this to make it concise.

// "var strongNames = new ConcurrentDictionary<string, string>(4, $($dlls.Count), StringComparer.OrdinalIgnoreCase);" > c:\temp\strongnames.txt
// $dlls | Sort-Object -u { $_.GetName().Name} | % { 'strongNames["{0}"] = "{1}";' -f $_.FullName.Split(",", 2)[0], $_.FullName >> c:\temp\strongnames.txt }
// $dlls | Sort-Object -u { $_.GetName().Name} | ForEach-Object { 'strongNames["{0}"] = "{1}";' -f $_.FullName.Split(",", 2)[0], $_.FullName >> c:\temp\strongnames.txt }

// The default concurrent level is 4. We use the default level.
var strongNames = new ConcurrentDictionary<string, string>(4, 744, StringComparer.OrdinalIgnoreCase);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1646,7 +1646,7 @@ internal static char SetDelimiter(PSCmdlet Cmdlet, string ParameterSetName, char
if (UseCulture == true)
{
// ListSeparator is apparently always a character even though the property returns a string, checked via:
// [CultureInfo]::GetCultures("AllCultures") | % { ([CultureInfo]($_.Name)).TextInfo.ListSeparator } | ? Length -ne 1
// [CultureInfo]::GetCultures("AllCultures") | ForEach-Object { ([CultureInfo]($_.Name)).TextInfo.ListSeparator } | Where-Object Length -ne 1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here.

Delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0];
}
break; A3D6
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ Set-PSReadlineKeyHandler -Key Alt+j `
-ScriptBlock {
param($key, $arg)

$global:PSReadlineMarks.GetEnumerator() | % {
$global:PSReadlineMarks.GetEnumerator() | ForEach-Object {
[PSCustomObject]@{Key = $_.Key; Dir = $_.Value} } |
Format-Table -AutoSize | Out-Host

Expand Down
Loading
0