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 all 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
48 changes: 24 additions & 24 deletions build.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,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 @@ -300,7 +300,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 @@ -362,9 +362,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" "&" "$($vcPath)\vcvarsall.bat" "$NativeHostArch" "&" mc.exe -o -d -c -U "$($_.FullName)" -h "$nativeResourcesFolder" -r "$nativeResourcesFolder"
"@
Expand Down Expand Up @@ -402,7 +402,7 @@ cmd.exe /C cd /d "$location" "&" "$($vcPath)\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 @@ -468,7 +468,7 @@ cmd.exe /C cd /d "$location" "&" "$($vcPath)\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 @@ -632,7 +632,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 @@ -689,7 +689,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 {
$fullname = $_.fullname
$tok = $err = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($FullName, [ref]$tok,[ref]$err)
Expand All @@ -705,7 +705,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 @@ -749,7 +749,7 @@ function Publish-PSTestTools {
$tools = @(
@{Path="${PSScriptRoot}/test/tools/TestExe";Output="testexe"}
)
if ($Options -eq $null)
if ($null -eq $Options)
{
$Options = New-PSOptions
}
Expand Down Expand Up @@ -894,7 +894,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 @@ -1859,7 +1859,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 @@ -1990,7 +1990,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 @@ -2022,7 +2022,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 @@ -2063,7 +2063,7 @@ function Get-Mappings

end {
$map = @{}
$mapFiles | % {
$mapFiles | ForEach-Object {
$file = $_
try {
$rawHashtable = $_ | Get-Content -Raw | ConvertFrom-Json | Convert-PSObjectToHashtable
Expand All @@ -2079,7 +2079,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 @@ -2110,7 +2110,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 @@ -2227,12 +2227,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 @@ -2256,7 +2256,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 @@ -2274,7 +2274,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 @@ -2336,7 +2336,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 Expand Up @@ -2394,7 +2394,7 @@ function script:logerror([string]$message) {
function script:precheck([string]$command, [string]$missedMessage) {
$c = Get-Command $command -ErrorAction SilentlyContinue
if (-not $c) {
if ($missedMessage -ne $null)
if ($null -ne $missedMessage)
{
Write-Warning $missedMessage
}
Expand Down
4 changes: 2 additions & 2 deletions demos/Apache/Apache/Apache.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ Function Get-ApacheVHost{
}
}

if ($ServerName -ne $null){
if ($null -ne $ServerName){
$vHost = [ApacheVirtualHost]::New($ServerName, $ConfFile, $ListenAddress.Split(":")[0],$ListenAddress.Split(":")[1])
$ExtProps = GetVHostProps $ConfFile $ServerName $ListenAddress
$vHost.DocumentRoot = $Ext 10000 Props.DocumentRoot
Expand All @@ -206,7 +206,7 @@ Function Restart-ApacheHTTPServer{
[switch]$Graceful
)

if ($Graceful -eq $null){$Graceful = $false}
if ($null -eq $Graceful){$Graceful = $false}
$cmd = GetApacheCmd
if ($Graceful){
& $global:sudocmd $cmd -k graceful
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

#Graceful restart of Apache
Write-host -Foreground Blue "Restart Apache Server gracefully"
Expand Down
14 changes: 7 additions & 7 deletions demos/Azure/Azure-Demo.ps1
10000
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
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 @@ -35,21 +35,21 @@ New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -Templa
Get-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName

### Discover the resources we created by the previous deployment
Find-AzureRmResource -ResourceGroupName $resourceGroupName | select Name,ResourceType,Location
Find-AzureRmResource -ResourceGroupName $resourceGroupName | Select-Object Name,ResourceType,Location

### 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"
Get-AzureRmProviderOperation -OperationSearchString Microsoft.Compute/* | select OperationName,Operation
Get-AzureRmProviderOperation -OperationSearchString Microsoft.Compute/* | Select-Object OperationName,Operation

### Power Off the Virtual Machine we created
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 All @@ -59,7 +59,7 @@ Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType
Remove-AzureRmResource -ResourceName MyUbuntuVM -ResourceType Microsoft.Compute/virtualMachines -ResourceGroupName $resourceGroupName

### Look at the resources that still exists
Find-AzureRmResource -ResourceGroupName $resourceGroupName | select Name,ResourceType,Location
Find-AzureRmResource -ResourceGroupName $resourceGroupName | Select-Object Name,ResourceType,Location

### Remove the resource group and its resources
Remove-AzureRmResourceGroup -Name $resourceGroupName
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
Original file line number Diff line number Diff line change
Expand Up @@ -1967,7 +1967,7 @@ public Int16 Delay
foreach ($computerName in $array[1])
{
$ret = $null
if ($array[0] -eq $null)
if ($null -eq array[0])
{
$ret = Invoke-Command -ComputerName $computerName {$true} -SessionOption (New-PSSessionOption -NoMachineProfile) -ErrorAction SilentlyContinue
}
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 @@ -2140,7 +2140,7 @@ private static ConcurrentDictionary<string, string> InitializeStrongNameDictiona
// $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) }
// "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, 57AE StringComparer.OrdinalIgnoreCase);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public sealed class ImportPSSessionCommand : ImplicitRemotingCommandBase
$sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier)
Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue

if ($previousScript -ne $null)
if ($null -ne $previousScript)
{
& $previousScript $args
}
Expand Down Expand Up @@ -2139,11 +2139,11 @@ function Set-PSImplicitRemotingSession
[Parameter(Mandatory = $false, Position = 1)]
[bool] $createdByModule = $false)

if ($PSSession -ne $null)
if ($null -ne $PSSession)
{{
$script:PSSession = $PSSession

if ($createdByModule -and ($script:PSSession -ne $null))
if ($createdByModule -and ($null -ne $script:PSSession))
{{
$moduleName = Get-PSImplicitRemotingModuleName
$script:PSSession.Name = '{0}' -f $moduleName
Expand Down Expand Up @@ -2184,7 +2184,7 @@ private void GenerateHelperFunctionsSetImplicitRunspace(TextWriter writer)
private const string HelperFunctionsGetSessionOptionTemplate = @"
function Get-PSImplicitRemotingSessionOption
{{
if ($PSSessionOptionOverride -ne $null)
if ($null -ne $PSSessionOptionOverride)
{{
return $PSSessionOptionOverride
}}
Expand Down Expand Up @@ -2336,22 +2336,22 @@ function Get-PSImplicitRemotingSession

$savedImplicitRemotingHash = '{4}'

if (($script:PSSession -eq $null) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened'))
if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened'))
{{
Set-PSImplicitRemotingSession `
(& $script:GetPSSession `
-InstanceId {0} `
-ErrorAction SilentlyContinue )
}}
if (($script:PSSession -ne $null) -and ($script:PSSession.Runspace.RunspaceStateInfo.State -eq 'Disconnected'))
if (($null -ne $script:PSSession) -and ($script:PSSession.Runspace.RunspaceStateInfo.State -eq 'Disconnected'))
{{
# If we are handed a disconnected session, try re-connecting it before creating a new session.
Set-PSImplicitRemotingSession `
(& $script:ConnectPSSession `
-Session $script:PSSession `
-ErrorAction SilentlyContinue)
}}
if (($script:PSSession -eq $null) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened'))
if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened'))
{{
Write-PSImplicitRemotingMessage ('{1}' -f $commandName)

Expand All @@ -2370,7 +2370,7 @@ function Get-PSImplicitRemotingSession

{8}
}}
if (($script:PSSession -eq $null) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened'))
if (($null -eq $script:PSSession) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened'))
{{
throw '{3}'
}}
Expand Down
Loading
0