From f26d6498ebe2a6eeeec129aa6fcb004f936e7192 Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Sun, 9 Jul 2017 21:23:44 +0100 Subject: [PATCH 1/4] Fixed most PSAvoidUsingCmdletAliases warnings for ForEach-Object (%), Where-Object (?), Select-Object and a few others. Fixed some PSUseDeclaredVarsMoreThanAssignment warnings (one must be careful with them as some of those warnings are false positives) --- build.psm1 | 59 ++--- demos/Apache/Apache/Apache.psm1 | 4 +- demos/Azure/Azure-Demo.ps1 | 16 +- demos/crontab/CronTab/CronTab.psm1 | 2 +- docs/KNOWNISSUES.md | 2 +- .../commands/management/Computer.cs | 2 +- .../management/ControlPanelItemCommand.cs | 4 +- .../commands/utility/AddType.cs | 2 +- .../commands/utility/CSVCommands.cs | 2 +- .../utility/ImplicitRemotingCommands.cs | 16 +- .../commandHelpers/ShowCommandHelper.cs | 6 +- .../SamplePSReadlineProfile.ps1 | 16 +- .../WorkflowCore/ImportWorkflowCommand.cs | 12 +- .../PSDiagnostics/PSDiagnostics.psm1 | 6 +- .../Microsoft.PowerShell.ODataAdapter.ps1 | 208 +++++++-------- .../Microsoft.PowerShell.ODataUtilsHelper.ps1 | 46 ++-- .../Microsoft.PowerShell.ODataV4Adapter.ps1 | 242 +++++++++--------- .../DscSupport/CimDSCParser.cs | 20 +- .../DefaultFormatters/HelpV3_format_ps1xml.cs | 2 +- .../DefaultFormatters/Help_format_ps1xml.cs | 14 +- .../PowerShellCore_format_ps1xml.cs | 14 +- .../Utilities/MshParameterAssociation.cs | 2 +- .../CommandCompletion/CommandCompletion.cs | 4 +- .../CommandCompletion/CompletionCompleters.cs | 2 +- .../engine/EventManager.cs | 2 +- .../engine/Modules/ImportModuleCommand.cs | 4 +- .../engine/MshCommandRuntime.cs | 2 +- .../engine/ProgressRecord.cs | 2 +- .../engine/TypesV3_Ps1Xml.cs | 2 +- .../engine/Types_Ps1Xml.cs | 24 +- .../engine/Utils.cs | 2 +- .../engine/debugger/debugger.cs | 4 +- .../engine/hostifaces/PowerShell.cs | 2 +- .../engine/parser/Compiler.cs | 4 +- .../engine/parser/VariableAnalysis.cs | 2 +- .../engine/parser/ast.cs | 2 +- .../engine/remoting/client/Job.cs | 2 +- .../remoting/commands/CustomShellCommands.cs | 46 ++-- .../remoting/commands/InvokeCommandCommand.cs | 8 +- .../remoting/commands/newrunspacecommand.cs | 2 +- .../remoting/fanin/BaseTransportManager.cs | 4 +- .../engine/runtime/Operations/MiscOps.cs | 2 +- .../namespaces/FileSystemProvider.cs | 10 +- .../resources/Modules.resx | 4 +- .../networktest/DockerRemoting.Tests.ps1 | 8 +- .../Scripting.Classes.BasicParsing.Tests.ps1 | 6 +- .../Scripting.Classes.Modules.Tests.ps1 | 8 +- .../scripting.Classes.NestedModules.tests.ps1 | 2 +- .../LanguageAndParser.TestFollowup.Tests.ps1 | 6 +- .../Scripting/ActionPreference.Tests.ps1 | 2 +- .../Debugging/DebuggerScriptTests.Tests.ps1 | 54 ++-- .../Scripting/Debugging/Debugging.Tests.ps1 | 8 +- .../Debugging/DebuggingInHost.Tests.ps1 | 10 +- .../Scripting/Dynamicparameters.Tests.ps1 | 6 +- .../NativeExecution/NativeStreams.Tests.ps1 | 4 +- .../Scripting/OutErrorVariable.Tests.ps1 | 8 +- .../Scripting/ParameterBinding.Tests.ps1 | 2 +- .../Language/Scripting/ScriptHelp.Tests.ps1 | 2 +- .../Microsoft.PowerShell.Core/Job.Tests.ps1 | 2 +- .../TestGetCommand.Tests.ps1 | 2 +- ...Cmdlets.LocalAccounts.LocalGroup.Tests.ps1 | 4 +- ...s.LocalAccounts.LocalGroupMember.Tests.ps1 | 14 +- ....Cmdlets.LocalAccounts.LocalUser.Tests.ps1 | 6 +- .../Clear-Content.Tests.ps1 | 4 +- .../Get-ChildItem.Tests.ps1 | 6 +- .../Get-ComputerInfo.Tests.ps1 | 24 +- .../PSDrive.Tests.ps1 | 4 +- ...mands.Cmdlets.NoNewlineParameter.Tests.ps1 | 2 +- .../AclCmdlets.Tests.ps1 | 2 +- .../CmsMessage.Tests.ps1 | 2 +- .../certificateCommon.psm1 | 4 +- .../Export-Csv.Tests.ps1 | 2 +- .../Get-Member.Tests.ps1 | 6 +- .../Implicit.Remoting.Tests.ps1 | 196 +++++++------- .../Pester.Commands.Cmdlets.Json.Tests.ps1 | 10 +- .../RunspaceCmdlets.Tests.ps1 | 4 +- .../Select-Object.Tests.ps1 | 2 +- .../Send-MailMessage.Tests.ps1 | 6 +- .../Trace-Command.Tests.ps1 | 2 +- .../WebCmdlets.Tests.ps1 | 2 +- .../alias.tests.ps1 | 6 +- .../clixml.tests.ps1 | 4 +- .../command.tests.ps1 | 2 +- .../object.tests.ps1 | 2 +- .../xml.tests.ps1 | 2 +- .../Start-Transcript.Tests.ps1 | 4 +- .../PackageManagement.Tests.ps1 | 4 +- .../Help/HelpSystem.OnlineHelp.Tests.ps1 | 2 +- .../engine/InitialSessionState.Tests.ps1 | 6 +- .../Module/TestModuleManifest.Tests.ps1 | 2 +- .../ParameterBinding.Tests.ps1 | 4 +- .../InvokeCommandRemoteDebug.Tests.ps1 | 12 +- .../Remoting/RoleCapabilityFiles.Tests.ps1 | 6 +- .../engine/Remoting/SSHRemotingAPI.Tests.ps1 | 4 +- .../engine/SemanticVersion.Tests.ps1 | 4 +- .../Start-CodeCoverageRun.ps1 | 2 +- .../HelpersLanguage/HelpersLanguage.psm1 | 4 +- .../Modules/HttpListener/HttpListener.psm1 | 14 +- test/tools/OpenCover/OpenCover.psm1 | 18 +- tools/appveyor.psm1 | 4 +- 100 files changed, 686 insertions(+), 685 deletions(-) diff --git a/build.psm1 b/build.psm1 index de972a22384..9f7cd59152c 100644 --- a/build.psm1 +++ b/build.psm1 @@ -47,8 +47,6 @@ if ($IsLinux) { $IsCentOS = $LinuxInfo.ID -match 'centos' -and $LinuxInfo.VERSION_ID -match '7' $IsFedora = $LinuxInfo.ID -match 'fedora' -and $LinuxInfo.VERSION_ID -ge 24 $IsOpenSUSE = $LinuxInfo.ID -match 'opensuse' - $IsOpenSUSE13 = $IsOpenSUSE -and $LinuxInfo.VERSION_ID -match '13' - ${IsOpenSUSE42.1} = $IsOpenSUSE -and $LinuxInfo.VERSION_ID -match '42.1' $IsRedHatFamily = $IsCentOS -or $IsFedora -or $IsOpenSUSE # Workaround for temporary LD_LIBRARY_PATH hack for Fedora 24 @@ -283,7 +281,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) { @@ -292,7 +290,7 @@ Fix steps: $RestoreArguments += "quiet" } - ($srcProjectDirs + $testProjectDirs) | % { Start-NativeExecution { dotnet restore $_ $RestoreArguments } } + ($srcProjectDirs + $testProjectDirs) | ForEach-Object { Start-NativeExecution { dotnet restore $_ $RestoreArguments } } } # handle ResGen @@ -354,9 +352,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" "@ @@ -394,7 +392,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 @@ -460,7 +458,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) { @@ -516,6 +514,7 @@ function Compress-TestContent { function New-PSOptions { [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] param( [ValidateSet("Linux", "Debug", "Release", "CodeCoverage", "")] [string]$Configuration, @@ -611,7 +610,7 @@ function New-PSOptions { } if (-not $Runtime) { - $Runtime = dotnet --info | % { + $Runtime = dotnet --info | ForEach-Object { if ($_ -match "RID") { $_ -split "\s+" | Select-Object -Last 1 } @@ -668,7 +667,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) @@ -684,7 +683,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 } @@ -728,7 +727,7 @@ function Publish-PSTestTools { $tools = @( @{Path="${PSScriptRoot}/test/tools/TestExe";Output="testexe"} ) - if ($Options -eq $null) + if ($null -eq $Options) { $Options = New-PSOptions } @@ -873,7 +872,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 } @@ -881,7 +880,7 @@ function Start-PSPester { $count = ($lines | measure-object).Count if ($count -eq 0) { - sleep 1 + Start-Sleep 1 } else { @@ -1816,7 +1815,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 { @@ -1869,7 +1868,7 @@ function Start-DevPowerShell { $env:DEVPATH = $binDir if ($ZapDisable) { - $env:COMPLUS_ZapDisable = 1 + [Environment]::SetEnvironmentVariable('COMPLUS_ZapDisable', 1) } if ($FullCLR -and (-not (Test-Path $binDir\powershell.exe.config))) { @@ -1947,7 +1946,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 { @@ -1979,7 +1978,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 } @@ -1989,6 +1988,7 @@ function Copy-MappedFiles { function Get-Mappings { [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] param( [Parameter(ValueFromPipeline=$true)] [string[]]$Path = "$PSScriptRoot", @@ -2020,7 +2020,7 @@ function Get-Mappings end { $map = @{} - $mapFiles | % { + $mapFiles | ForEach-Object { $file = $_ try { $rawHashtable = $_ | Get-Content -Raw | ConvertFrom-Json | Convert-PSObjectToHashtable @@ -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 @@ -2064,10 +2064,10 @@ function Send-GitDiffToSd { ) # this is only for windows, because you cannot have SD enlistment on Linux - $patchPath = (ls (Join-Path (get-command git).Source '..\..') -Recurse -Filter 'patch.exe').FullName + $patchPath = (Get-ChildItem (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 $_" } @@ -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 { @' {1} @@ -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)) { @@ -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 @@ -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 } @@ -2351,7 +2351,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 } @@ -2604,6 +2604,7 @@ function New-MSIPackage function New-AppxPackage { [CmdletBinding()] + [OutputType([String])] param ( # Name of the Package diff --git a/demos/Apache/Apache/Apache.psm1 b/demos/Apache/Apache/Apache.psm1 index 5537fd124f3..a572561f103 100644 --- a/demos/Apache/Apache/Apache.psm1 +++ b/demos/Apache/Apache/Apache.psm1 @@ -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 = $ExtProps.DocumentRoot @@ -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 diff --git a/demos/Azure/Azure-Demo.ps1 b/demos/Azure/Azure-Demo.ps1 index a7245e1e548..fff69b2bc0d 100644 --- a/demos/Azure/Azure-Demo.ps1 +++ b/demos/Azure/Azure-Demo.ps1 @@ -10,14 +10,14 @@ ### ### Install-Package -Name AzureRM.NetCore.Preview -Source https://www.powershellgallery.com/api/v2 -ProviderName NuGet -ExcludeVersion -Destination ### -### Ensure $env:PSModulePath is updated with the location you used to install. +### Ensure $env:PSMODULEPATH is updated with the location you used to install. Import-Module AzureRM.NetCore.Preview ### Supply your Azure Credentials 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 @@ -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 @@ -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 @@ -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 diff --git a/demos/crontab/CronTab/CronTab.psm1 b/demos/crontab/CronTab/CronTab.psm1 index d7063331268..ee90c69f782 100644 --- a/demos/crontab/CronTab/CronTab.psm1 +++ b/demos/crontab/CronTab/CronTab.psm1 @@ -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 diff --git a/docs/KNOWNISSUES.md b/docs/KNOWNISSUES.md index a6fd57bd9a1..56f23a735ea 100644 --- a/docs/KNOWNISSUES.md +++ b/docs/KNOWNISSUES.md @@ -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`. See [#954](https://github.com/PowerShell/PowerShell/issues/954) to give us feedback on how to improve the globbing experience on Linux/macOS. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 3f92fb8049b..1e6b7e1392d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -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 } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs index a709d21d08d..bc97e568377 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs @@ -92,8 +92,8 @@ 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'} -if ($serverManagerModule -ne $null) +$serverManagerModule = Get-Module -ListAvailable | Where-Object {$_.Name -eq 'ServerManager'} +if ($null -ne $serverManagerModule) { Import-Module ServerManager $Gui = (Get-WindowsFeature Server-Gui-Shell).Installed diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 5d498c3e831..c182a1f9066 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -2140,7 +2140,7 @@ private static ConcurrentDictionary 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(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(4, 744, StringComparer.OrdinalIgnoreCase); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs index 6313a9a5ddc..e116f160fad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs @@ -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 Delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0]; } break; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 1bea462d7f4..9befdddee03 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -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 } @@ -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 ($null -ne $createdByModule -and ($script:PSSession)) {{ $moduleName = Get-PSImplicitRemotingModuleName $script:PSSession.Name = '{0}' -f $moduleName @@ -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 }} @@ -2336,14 +2336,14 @@ 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 ` @@ -2351,7 +2351,7 @@ function Get-PSImplicitRemotingSession -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) @@ -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}' }} diff --git a/src/Microsoft.PowerShell.GraphicalHost/commandHelpers/ShowCommandHelper.cs b/src/Microsoft.PowerShell.GraphicalHost/commandHelpers/ShowCommandHelper.cs index 93e94551b23..294b179ed5c 100644 --- a/src/Microsoft.PowerShell.GraphicalHost/commandHelpers/ShowCommandHelper.cs +++ b/src/Microsoft.PowerShell.GraphicalHost/commandHelpers/ShowCommandHelper.cs @@ -183,7 +183,7 @@ Function GetParameterInfo $validateSetAttributes = $parameter.Attributes | Where { [ValidateSet].IsAssignableFrom($_.GetType()) } - if (($validateSetAttributes -ne $null) -and ($validateSetAttributes.Count -gt 0)) + if (($null -ne $validateSetAttributes) -and ($validateSetAttributes.Count -gt 0)) { $hasParameterSet = $true $validValues = $validateSetAttributes[0].ValidValues @@ -213,7 +213,7 @@ Function GetParameterSets catch [System.Management.Automation.PSNotSupportedException] { } catch [System.Management.Automation.PSNotImplementedException] { } - if (($parameterSets -eq $null) -or ($parameterSets.Count -eq 0)) + if (($null -eq $parameterSets) -or ($parameterSets.Count -eq 0)) { return (,@()) } @@ -239,7 +239,7 @@ Function GetModuleInfo [System.Management.Automation.CommandInfo] $cmdInfo ) - if ($cmdInfo.ModuleName -ne $null) + if ($null -ne $cmdInfo.ModuleName) { $moduleName = $cmdInfo.ModuleName } diff --git a/src/Microsoft.PowerShell.PSReadLine/SamplePSReadlineProfile.ps1 b/src/Microsoft.PowerShell.PSReadLine/SamplePSReadlineProfile.ps1 index 18eda65c2b7..cfde8a0c817 100644 --- a/src/Microsoft.PowerShell.PSReadLine/SamplePSReadlineProfile.ps1 +++ b/src/Microsoft.PowerShell.PSReadLine/SamplePSReadlineProfile.ps1 @@ -204,7 +204,7 @@ Set-PSReadlineKeyHandler -Key Backspace ` } } - if ($toMatch -ne $null -and $line[$cursor-1] -eq $toMatch) + if ($null -ne $toMatch -and $line[$cursor-1] -eq $toMatch) { [Microsoft.PowerShell.PSConsoleReadLine]::Delete($cursor - 1, 2) } @@ -319,7 +319,7 @@ Set-PSReadlineKeyHandler -Key "Alt+'" ` } } - if ($tokenToChange -ne $null) + if ($null -ne $tokenToChange) { $extent = $tokenToChange.Extent $tokenText = $extent.Text @@ -365,10 +365,10 @@ Set-PSReadlineKeyHandler -Key "Alt+%" ` if ($token.TokenFlags -band [System.Management.Automation.Language.TokenFlags]::CommandName) { $alias = $ExecutionContext.InvokeCommand.GetCommand($token.Extent.Text, 'Alias') - if ($alias -ne $null) + if ($null -ne $alias) { $resolvedCommand = $alias.ResolvedCommandName - if ($resolvedCommand -ne $null) + if ($null -ne $resolvedCommand) { $extent = $token.Extent $length = $extent.EndOffset - $extent.StartOffset @@ -406,10 +406,10 @@ Set-PSReadlineKeyHandler -Key F1 ` $node.Extent.EndOffset -ge $cursor }, $true) | Select-Object -Last 1 - if ($commandAst -ne $null) + if ($null -ne $commandAst) { $commandName = $commandAst.GetCommandName() - if ($commandName -ne $null) + if ($null -ne $commandName) { $command = $ExecutionContext.InvokeCommand.GetCommand($commandName, 'All') if ($command -is [System.Management.Automation.AliasInfo]) @@ -417,7 +417,7 @@ Set-PSReadlineKeyHandler -Key F1 ` $commandName = $command.ResolvedCommandName } - if ($commandName -ne $null) + if ($null -ne $commandName) { Get-Help $commandName -ShowWindow } @@ -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 diff --git a/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs b/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs index d756340887a..928c358f8ff 100644 --- a/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs +++ b/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs @@ -1303,7 +1303,7 @@ ReadOnlyCollection attributeAstCollection { if ($collection['" + Constants.ComputerName + @"'] -eq '*' ) { - if ($PSParameterCollectionDefaultsMember -ne $null) + if ($null -ne $PSParameterCollectionDefaultsMember) { $msg = [Microsoft.PowerShell.Commands.ImportWorkflowCommand]::ParameterErrorMessage; throw ( New-Object System.Management.Automation.ErrorRecord $msg, StartWorkflow.InvalidArgument, InvalidArgument, $PSParameterCollection) @@ -1794,7 +1794,7 @@ internal static string AddCommonWfParameters(bool innerfunction, string workflow # Create the final parameter collection... $finalParameterCollection = $null - if ($PSParameterCollection -ne $null) + if ($PSParameterCollection) {{ $finalParameterCollection = $PSParameterCollection }} @@ -1808,9 +1808,9 @@ internal static string AddCommonWfParameters(bool innerfunction, string workflow # Start the workflow and return the job object... $debuggerActive = (@(Get-PSBreakpoint).Count -gt 0) if (($debuggerActive -eq $false) -and - ($host -ne $null) -and - ($host.Runspace -ne $null) -and - ($host.Runspace.Debugger -ne $null)) + ($null -ne $host) -and + ($null -ne $host.Runspace) -and + ($null -ne $host.Runspace.Debugger)) {{ $debuggerActive = $host.Runspace.Debugger.IsActive }} @@ -1843,7 +1843,7 @@ internal static string AddCommonWfParameters(bool innerfunction, string workflow throw (New-Object System.Management.Automation.ErrorRecord $newException, StartWorkflow.InvalidArgument, InvalidArgument, $finalParameterCollection) }} - if (-not $AsJob -and $job -ne $null) + if ($null -ne -not $AsJob -and $job) {{ try {{ diff --git a/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 b/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 index 1c67c2b7510..f7cbd4f64e3 100644 --- a/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 +++ b/src/Modules/Windows-Core+Full/PSDiagnostics/PSDiagnostics.psm1 @@ -61,17 +61,17 @@ function Start-Trace $executestring += " -ets" } - if ($OutputFilePath -ne $null) + if ($null -ne $OutputFilePath) { $executestring += " -o $OutputFilePath" } - if ($ProviderFilePath -ne $null) + if ($null -ne $ProviderFilePath) { $executestring += " -pf $ProviderFilePath" } - if ($Format -ne $null) + if ($null -ne $Format) { $executestring += " -f $Format" } diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 index 367a4acea48..22ad15fb766 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataAdapter.ps1 @@ -55,9 +55,9 @@ function ParseMetaData ) # $metaDataUri is already validated at the cmdlet layer. - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ParseMetadata") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ParseMetadata") } - if($metadataXml -eq $null) + if($null -eq $metadataXml) { $errorMessage = ($LocalizedData.InValidXmlInMetadata -f $metaDataUri) $exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception) @@ -71,7 +71,7 @@ function ParseMetaData # OData version (and hence the protocol) used in the metadata is # supported by the adapter used for executing the generated # proxy cmdlets. - if(($metadataXML -ne $null) -and ($metadataXML.Edmx -ne $null)) + if(($null -ne $metadataXML) -and ($null -ne $metadataXML.Edmx)) { if($null -eq $metadataXML.Edmx.Version) { @@ -112,7 +112,7 @@ function ParseMetaData foreach ($schema in $MetadataXML.Edmx.DataServices.Schema) { - if (($schema -ne $null) -and [string]::IsNullOrEmpty($schema.NameSpace )) + if (($null -ne $schema) -and [string]::IsNullOrEmpty($schema.NameSpace )) { $callerPSCmdlet = $callerPSCmdlet -as [System.Management.Automation.PSCmdlet] $errorMessage = ($LocalizedData.InValidSchemaNamespace -f $metaDataUri) @@ -129,13 +129,13 @@ function ParseMetaData foreach ($schema in $metadataXml.Edmx.DataServices.Schema) { - if ($schema -eq $null) + if ($null -eq $schema) { Write-Error $LocalizedData.EmptySchema continue } - if ($metadata.Namespace -eq $null) + if ($null -eq $metadata.Namespace) { $metaData.Namespace = $schema.Namespace } @@ -144,11 +144,11 @@ function ParseMetaData { $baseType = $null - if ($entityType.BaseType -ne $null) + if ($null -ne $entityType.BaseType) { # add it to the processing queue $baseType = GetBaseType $entityType $metaData - if ($baseType -eq $null) + if ($null -eq $baseType) { $entityAndComplexTypesQueue[$entityType.BaseType] += @(@{type='EntityType'; value=$entityType}) continue @@ -164,11 +164,11 @@ function ParseMetaData { $baseType = $null - if ($complexType.BaseType -ne $null) + if ($null -ne $complexType.BaseType) { # add it to the processing queue $baseType = GetBaseType $complexType $metaData - if ($baseType -eq $null) + if ($null -eq $baseType) { $entityAndComplexTypesQueue[$entityType.BaseType] += @(@{type='ComplexType'; value=$complexType}) continue @@ -251,9 +251,9 @@ function ParseMetaData foreach ($action in $schema.EntityContainer.FunctionImport) { # HttpMethod is only used for legacy Service Operations - if ($action.HttpMethod -eq $null) + if ($null -eq $action.HttpMethod) { - if ($action.IsSideEffecting -ne $null) + if ($null -ne $action.IsSideEffecting) { $isSideEffecting = $action.IsSideEffecting } @@ -276,7 +276,7 @@ function ParseMetaData { foreach ($parameter in $action.Parameter) { - if ($parameter.Nullable -ne $null) + if ($null -ne $parameter.Nullable) { $parameterIsNullable = [System.Convert]::ToBoolean($parameter.Nullable); } @@ -341,9 +341,9 @@ function VerifyMetaData ) # $metaDataUri & $cmdletAdapter is already validated at the cmdlet layer. - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "VerifyMetaData") } - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "VerifyMetaData") } - if($progressBarStatus -eq $null) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "VerifyMetaData") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "VerifyMetaData") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "VerifyMetaData") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "VerifyMetaData") } Write-Verbose $LocalizedData.VerboseVerifyingMetadata @@ -373,7 +373,7 @@ function VerifyMetaData foreach ($entitySet in $metaData.EntitySets) { - if ($entitySet.Type -eq $null) + if ($null -eq $entitySet.Type) { $errorMessage = ($LocalizedData.EntitySetUndefinedType -f $metaDataUri, $entitySet.Name) $exception = [System.InvalidOperationException]::new($errorMessage) @@ -419,7 +419,7 @@ function VerifyMetaData $generatedCommandName = $resourceNameMapping[$entitySet.Name] } - if(($currentCommand.Noun -ne $null -and $currentCommand.Noun -eq $generatedCommandName) -and + if(($null -ne $currentCommand.Noun -and $currentCommand.Noun -eq $generatedCommandName) -and ($currentCommand.Verb -eq "Get" -or $currentCommand.Verb -eq "Set" -or $currentCommand.Verb -eq "New" -or @@ -522,9 +522,9 @@ function GenerateClientSideProxyModule ) # $uri, $outputModule, $metaDataUri, $createRequestMethod, $updateRequestMethod, & $cmdletAdapter is already validated at the cmdlet layer. - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } - if($progressBarStatus -eq $null) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } # This function performs the following set of tasks # while creating the client side proxy module: @@ -547,7 +547,7 @@ function GenerateClientSideProxyModule if(Test-Path -Path $complexTypeFileDefinitionPath) { $proxyFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $complexTypeFileDefinitionPath | Get-Item - if($callerPSCmdlet -ne $null) + if($null -ne $callerPSCmdlet) { $callerPSCmdlet.WriteObject($proxyFile) } @@ -603,13 +603,13 @@ function GenerateCRUDProxyCmdlet ) # $uri, $outputModule, $metaDataUri, $createRequestMethod, $updateRequestMethod, & $cmdletAdapter is already validated at the cmdlet layer. - if($entitySet -eq $null) { throw ($LocalizedData.ArguementNullError -f "EntitySet", "GenerateClientSideProxyModule") } - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } - if($progressBarStatus -eq $null) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } + if($null -eq $entitySet) { throw ($LocalizedData.ArguementNullError -f "EntitySet", "GenerateClientSideProxyModule") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateClientSideProxyModule") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } $entitySetName = $entitySet.Name - if(($resourceNameMapping -ne $null) -and + if(($null -ne $resourceNameMapping) -and $resourceNameMapping.ContainsKey($entitySetName)) { $entitySetName = $resourceNameMapping[$entitySetName] @@ -623,7 +623,7 @@ function GenerateCRUDProxyCmdlet $xmlWriter = New-Object System.XMl.XmlTextWriter($Path,$Null) - if ($xmlWriter -eq $null) + if ($null -eq $xmlWriter) { throw ($LocalizedData.XmlWriterInitializationError -f $entitySet.Name) } @@ -645,9 +645,9 @@ function GenerateCRUDProxyCmdlet GenerateGetProxyCmdlet $xmlWriter $metaData $keys $navigationProperties $cmdletAdapter $complexTypeMapping - $nonKeyProperties = (GetAllProperties $entitySet.Type) | ? { -not $_.isKey } - $nullableProperties = $nonKeyProperties | ? { $_.isNullable } - $nonNullableProperties = $nonKeyProperties | ? { -not $_.isNullable } + $nonKeyProperties = (GetAllProperties $entitySet.Type) | Where-Object { -not $_.isKey } + $nullableProperties = $nonKeyProperties | Where-Object { $_.isNullable } + $nonNullableProperties = $nonKeyProperties | Where-Object { -not $_.isNullable } $xmlWriter.WriteStartElement('StaticCmdlets') @@ -744,8 +744,8 @@ function GenerateGetProxyCmdlet ) # $cmdletAdapter is already validated at the cmdlet layer. - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateGetProxyCmdlet") } - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateGetProxyCmdlet") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateGetProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateGetProxyCmdlet") } $xmlWriter.WriteStartElement('InstanceCmdlets') $xmlWriter.WriteStartElement('GetCmdletParameters') @@ -753,12 +753,12 @@ function GenerateGetProxyCmdlet # adding key parameters and association parameters to QueryableProperties, each in a different parameter set # to be used by GET cmdlet - if (($keys -ne $null -and $keys.Length -gt 0) -or (($navigationProperties -ne $null -and $navigationProperties.Length -gt 0) -and $cmdletAdapter -ne "NetworkControllerAdapter")) + if (($null -ne $keys -and $keys.Length -gt 0) -or (($null -ne $navigationProperties -and $navigationProperties.Length -gt 0) -and $cmdletAdapter -ne "NetworkControllerAdapter")) { $xmlWriter.WriteStartElement('QueryableProperties') $position = 0 - $keys | ? { $_ -ne $null } | % { + $keys | Where-Object { $null -ne $_ } | ForEach-Object { $xmlWriter.WriteStartElement('Property') $xmlWriter.WriteAttributeString('PropertyName', $_.Name) @@ -787,12 +787,12 @@ function GenerateGetProxyCmdlet # This behaviour is different for NetworkController specific cmdlets. if ($CmdletAdapter -ne "NetworkControllerAdapter") { - $navigationProperties | ? { $_ -ne $null } | % { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { $associatedType = GetAssociatedType $metaData $_ $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType $nvgProperty = $_ - (GetAllProperties $associatedType) | ? { $_.IsKey } | % { + (GetAllProperties $associatedType) | Where-Object { $_.IsKey } | ForEach-Object { $xmlWriter.WriteStartElement('Property') $xmlWriter.WriteAttributeString('PropertyName', $associatedEntitySet.Name + ':' + $_.Name + ':Key') @@ -898,8 +898,8 @@ function GenerateNewProxyCmdlet ) # $cmdletAdapter is already validated at the cmdlet layer. - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateNewProxyCmdlet") } - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateNewProxyCmdlet") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateNewProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateNewProxyCmdlet") } $xmlWriter.WriteStartElement('Cmdlet') $xmlWriter.WriteStartElement('CmdletMetadata') @@ -918,7 +918,7 @@ function GenerateNewProxyCmdlet # This behaviour is different for NetworkControllerCmdlets if ($CmdletAdapter -ne "NetworkControllerAdapter") { - $navigationProperties | ? { $_ -ne $null } | % { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { $associatedType = GetAssociatedType $metaData $_ $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType @@ -926,7 +926,7 @@ function GenerateNewProxyCmdlet $xmlWriter.WriteAttributeString('MethodName', "Association:Create:$($associatedEntitySet.Name)") $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) - $associatedKeys = ((GetAllProperties $associatedType) | ? { $_.isKey }) + $associatedKeys = ((GetAllProperties $associatedType) | Where-Object { $_.isKey }) AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping $xmlWriter.WriteEndElement() @@ -955,8 +955,8 @@ function GenerateRemoveProxyCmdlet ) # $metaData, $cmdletAdapter & $cmdletAdapter are already validated at the cmdlet layer. - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateRemoveProxyCmdlet") } - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateRemoveProxyCmdlet") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateRemoveProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateRemoveProxyCmdlet") } $xmlWriter.WriteStartElement('Cmdlet') $xmlWriter.WriteStartElement('CmdletMetadata') @@ -991,7 +991,7 @@ function GenerateRemoveProxyCmdlet # This behaviour is different for NetworkControllerCmdlets if ($CmdletAdapter -ne "NetworkControllerAdapter") { - $navigationProperties | ? { $_ -ne $null } | % { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { $associatedType = GetAssociatedType $metaData $_ $associatedEntitySet = GetEntitySetForEntityType $metaData $associatedType @@ -1001,7 +1001,7 @@ function GenerateRemoveProxyCmdlet $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) $associatedType = GetAssociatedType $metaData $_ - $associatedKeys = ((GetAllProperties $associatedType) | ? { $_.isKey }) + $associatedKeys = ((GetAllProperties $associatedType) | Where-Object { $_.isKey }) AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping $xmlWriter.WriteEndElement() @@ -1030,10 +1030,10 @@ function GenerateActionProxyCmdlet ) # $metaData is already validated at the cmdlet layer. - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateActionProxyCmdlet") } - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateActionProxyCmdlet") } - if($action -eq $null) { throw ($LocalizedData.ArguementNullError -f "Action", "GenerateActionProxyCmdlet") } - if($noun -eq $null) { throw ($LocalizedData.ArguementNullError -f "Noun", "GenerateActionProxyCmdlet") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateActionProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateActionProxyCmdlet") } + if($null -eq $action) { throw ($LocalizedData.ArguementNullError -f "Action", "GenerateActionProxyCmdlet") } + if($null -eq $noun) { throw ($LocalizedData.ArguementNullError -f "Noun", "GenerateActionProxyCmdlet") } $xmlWriter.WriteStartElement('Cmdlet') @@ -1048,7 +1048,7 @@ function GenerateActionProxyCmdlet $xmlWriter.WriteStartElement('Parameters') - $keys | ? { $_ -ne $null } | % { + $keys | Where-Object { $null -ne $_ } | ForEach-Object { $xmlWriter.WriteStartElement('Parameter') $xmlWriter.WriteAttributeString('ParameterName', $_.Name + ':Key') @@ -1127,18 +1127,18 @@ function GenerateServiceActionProxyCmdlet ) # $uri is already validated at the cmdlet layer. - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateServiceActionProxyCmdlet") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateServiceActionProxyCmdlet") } $xmlWriter = New-Object System.XMl.XmlTextWriter($path,$Null) - if ($xmlWriter -eq $null) + if ($null -eq $xmlWriter) { throw $LocalizedData.XmlWriterInitializationError -f "ServiceActions" } $xmlWriter = SaveCDXMLHeader $xmlWriter $uri 'ServiceActions' 'ServiceActions' - $actions = $metaData.Actions | Where-Object { $_.EntitySet -eq $null } + $actions = $metaData.Actions | Where-Object { $null -eq $_.EntitySet } if ($actions.Length -gt 0) { @@ -1189,15 +1189,15 @@ function GenerateModuleManifest [System.Management.Automation.PSCmdlet] $callerPSCmdlet ) - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateModuleManifest") } - if($modulePath -eq $null) { throw ($LocalizedData.ArguementNullError -f "ModulePath", "GenerateModuleManifest") } - if($progressBarStatus -eq $null) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateModuleManifest") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateModuleManifest") } + if($null -eq $modulePath) { throw ($LocalizedData.ArguementNullError -f "ModulePath", "GenerateModuleManifest") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateModuleManifest") } $NestedModules = @() foreach ($entitySet in $metaData.EntitySets) { $entitySetName = $entitySet.Name - if(($resourceNameMapping -ne $null) -and + if(($null -ne $resourceNameMapping) -and $resourceNameMapping.ContainsKey($entitySetName)) { $entitySetName = $resourceNameMapping[$entitySetName] @@ -1227,18 +1227,18 @@ function GetBaseType [ODataUtils.Metadata] $metaData ) - if ($metadataEntityDefinition -ne $null -and - $metaData -ne $null -and - $metadataEntityDefinition.BaseType -ne $null) + if ($null -ne $metadataEntityDefinition -and + $null -ne $metaData -and + $null -ne $metadataEntityDefinition.BaseType) { - $baseType = $metaData.EntityTypes | Where {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} - if ($baseType -eq $null) + $baseType = $metaData.EntityTypes | Where-Object {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} + if ($null -eq $baseType) { - $baseType = $metaData.ComplexTypes | Where {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} + $baseType = $metaData.ComplexTypes | Where-Object {$_.Namespace+"."+$_.Name -eq $metadataEntityDefinition.BaseType} } } - if ($baseType -ne $null) + if ($null -ne $baseType) { $baseType[0] } @@ -1260,9 +1260,9 @@ function AddDerivedTypes ) # $metaData is already validated at the cmdlet layer. - if($baseType -eq $null) { throw ($LocalizedData.ArguementNullError -f "BaseType", "AddDerivedTypes") } - if($entityAndComplexTypesQueue -eq $null) { throw ($LocalizedData.ArguementNullError -f "EntityAndComplexTypesQueue", "AddDerivedTypes") } - if($namespace -eq $null) { throw ($LocalizedData.ArguementNullError -f "Namespace", "AddDerivedTypes") } + if($null -eq $baseType) { throw ($LocalizedData.ArguementNullError -f "BaseType", "AddDerivedTypes") } + if($null -eq $entityAndComplexTypesQueue) { throw ($LocalizedData.ArguementNullError -f "EntityAndComplexTypesQueue", "AddDerivedTypes") } + if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "AddDerivedTypes") } $baseTypeFullName = $baseType.Namespace + '.' + $baseType.Name @@ -1303,8 +1303,8 @@ function ParseMetadataTypeDefinition ) # $metaData is already validated at the cmdlet layer. - if($metadataEntityDefinition -eq $null) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } - if($namespace -eq $null) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } + if($null -eq $metadataEntityDefinition) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } + if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } $newEntityType = [ODataUtils.EntityType] @{ "Namespace" = $namespace; @@ -1314,10 +1314,10 @@ function ParseMetadataTypeDefinition } # properties defined on EntityType - $newEntityType.EntityProperties = $metadataEntityDefinition.Property | % { - if ($_ -ne $null) + $newEntityType.EntityProperties = $metadataEntityDefinition.Property | ForEach-Object { + if ($null -ne $_) { - if ($_.Nullable -ne $null) + if ($null -ne $_.Nullable) { $newPropertyIsNullable = [System.Convert]::ToBoolean($_.Nullable) } @@ -1335,8 +1335,8 @@ function ParseMetadataTypeDefinition } # navigation properties defined on EntityType - $newEntityType.NavigationProperties = $metadataEntityDefinition.NavigationProperty | % { - if ($_ -ne $null) + $newEntityType.NavigationProperties = $metadataEntityDefinition.NavigationProperty | ForEach-Object { + if ($null -ne $_) { ($AssociationNamespace, $AssociationName) = SplitNamespaceAndName $_.Relationship [ODataUtils.NavigationProperty] @{ @@ -1371,7 +1371,7 @@ function GetAllProperties [switch] $IncludeOnlyNavigationProperties ) - if($entityType -eq $null) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetAllProperties") } + if($null -eq $entityType) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetAllProperties") } $requestedProperties = @() @@ -1380,7 +1380,7 @@ function GetAllProperties # $IncludeOnlyNavigationProperties switch parameter is used then follow # the same routine for navigation properties. $currentEntityType = $entityType - while($currentEntityType -ne $null) + while($null -ne $currentEntityType) { if($IncludeOnlyNavigationProperties.IsPresent) { @@ -1410,7 +1410,7 @@ function SplitNamespaceAndName [string] $fullyQualifiedName ) - if($fullyQualifiedName -eq $null) { throw ($LocalizedData.ArguementNullError -f "FUllyQualifiedName", "SplitNamespaceAndName") } + if($null -eq $fullyQualifiedName) { throw ($LocalizedData.ArguementNullError -f "FUllyQualifiedName", "SplitNamespaceAndName") } $sa = $fullyQualifiedName -split "(.*)\.(.*)" @@ -1447,11 +1447,11 @@ function GetEntitySetForEntityType ) # $metaData is already validated at the cmdlet layer. - if($entityType -eq $null) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetEntitySetForEntityType") } + if($null -eq $entityType) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetEntitySetForEntityType") } - $result = $metaData.EntitySets | ? { ($_.Type.Namespace -eq $entityType.Namespace) -and ($_.Type.Name -eq $entityType.Name) } + $result = $metaData.EntitySets | Where-Object { ($_.Type.Namespace -eq $entityType.Namespace) -and ($_.Type.Name -eq $entityType.Name) } - if (($result.Count -eq 0) -and ($entityType.BaseType -ne $null)) + if (($result.Count -eq 0) -and ($null -ne $entityType.BaseType)) { GetEntitySetForEntityType $metaData $entityType.BaseType } @@ -1490,7 +1490,7 @@ function ProcessStreamHelper Write-Verbose -Message $verboseMessage ProgressBarHelper $progressBarActivityName $status $previousSegmentWeight $currentSegmentWeight $totalNumberofEntries $currentEntryCount $proxyFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $path | Get-Item - if($callerPSCmdlet -ne $null) + if($null -ne $callerPSCmdlet) { $callerPSCmdlet.WriteObject($proxyFile) } @@ -1511,10 +1511,10 @@ function GetAssociatedType ) # $metaData is already validated at the cmdlet layer. - if($navProperty -eq $null) { throw ($LocalizedData.ArguementNullError -f "NavigationProperty", "GetAssociatedType") } + if($null -eq $navProperty) { throw ($LocalizedData.ArguementNullError -f "NavigationProperty", "GetAssociatedType") } $associationName = $navProperty.AssociationName - $association = $Metadata.Associations | ? { $_.Name -eq $associationName } + $association = $Metadata.Associations | Where-Object { $_.Name -eq $associationName } $associationType = $association.Type if ($associationType.Count -lt 1) @@ -1565,7 +1565,7 @@ function AddParametersNode [Hashtable] $complexTypeMapping ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } if(($keyProperties.Length -gt 0) -or ($mandatoryProperties.Length -gt 0) -or @@ -1579,17 +1579,17 @@ function AddParametersNode $pos = 0 - if ($keyProperties -ne $null) + if ($null -ne $keyProperties) { $pos = AddParametersCDXML $xmlWriter $keyProperties $pos $true $prefixForKeys ":Key" $complexTypeMapping } - if ($mandatoryProperties -ne $null) + if ($null -ne $mandatoryProperties) { $pos = AddParametersCDXML $xmlWriter $mandatoryProperties $pos $true $null $null $complexTypeMapping } - if ($otherProperties -ne $null) + if ($null -ne $otherProperties) { $pos = AddParametersCDXML $xmlWriter $otherProperties $pos $false $null $null $complexTypeMapping } @@ -1634,7 +1634,7 @@ function AddParametersCDXML [Hashtable] $complexTypeMapping ) - $properties | ? { $_ -ne $null } | % { + $properties | Where-Object { $null -ne $_ } | ForEach-Object { $xmlWriter.WriteStartElement('Parameter') $xmlWriter.WriteAttributeString('ParameterName', $_.Name + $suffix) $xmlWriter.WriteStartElement('Type') @@ -1676,9 +1676,9 @@ function GenerateComplexTypeDefinition ) #metadataUri, $OutputModule & $cmdletAdapter are already validated at the cmdlet layer. - if($typeDefinationFileName -eq $null) { throw ($LocalizedData.ArguementNullError -f "TypeDefinationFileName", "GenerateComplexTypeDefination") } - if($metaData -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateComplexTypeDefination") } - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateComplexTypeDefination") } + if($null -eq $typeDefinationFileName) { throw ($LocalizedData.ArguementNullError -f "TypeDefinationFileName", "GenerateComplexTypeDefination") } + if($null -eq $metaData) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateComplexTypeDefination") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GenerateComplexTypeDefination") } $Path = "$OutputModule\$typeDefinitionFileName" @@ -1686,14 +1686,14 @@ function GenerateComplexTypeDefinition # definition exposed in the metadata. $typesToBeGenerated = $metaData.EntityTypes+$metadata.ComplexTypes - if($typesToBeGenerated -ne $null -and $typesToBeGenerated.Count -gt 0) + if($null -ne $typesToBeGenerated -and $typesToBeGenerated.Count -gt 0) { $complexTypeMapping = @{} $entityTypeNameSpaceMapping = @{} foreach ($entityType in $typesToBeGenerated) { - if ($entityType -ne $null) + if ($null -ne $entityType) { $entityTypeFullName = $entityType.Namespace + '.' + $entityType.Name if(!$complexTypeMapping.ContainsKey($entityTypeFullName)) @@ -1731,7 +1731,7 @@ using System.Management.Automation; $entityTypeFullName = (ValidateComplexTypeIdentifier $entityType.Namespace $true $metaDataUri $callerPSCmdlet) + '.' + $entityType.Name Write-Verbose ($LocalizedData.VerboseAddingTypeDefinationToGeneratedModule -f $entityTypeFullName, "$OutputModule\$typeDefinationFileName") - if($entityType.BaseType -ne $null) + if($null -ne $entityType.BaseType) { $entityBaseFullName = (ValidateComplexTypeIdentifier $entityType.BaseType.Namespace $true $metaDataUri $callerPSCmdlet) + '.' + (ValidateComplexTypeIdentifier $entityType.BaseType.Name $false $metaDataUri $callerPSCmdlet) $output += "`r`n public class $(ValidateComplexTypeIdentifier $entityType.Name $false $metaDataUri $callerPSCmdlet) : $($entityBaseFullName)`r`n {" @@ -1803,7 +1803,7 @@ function ValidateComplexTypeIdentifier [System.Management.Automation.PSCmdlet] $callerPSCmdlet ) - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ValidateComplexTypeIdentifier") } + if($null -eq $callerPSCmdletl) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "ValidateComplexTypeIdentifier") } if($isNameSpaceName) { @@ -1853,7 +1853,7 @@ function GetKeys $key = (GetAllProperties $entitySet.Type) | Where-Object { $_.IsKey } # Get the keys with delimiters - $keys = $customUri -split "/" | % { + $keys = $customUri -split "/" | ForEach-Object { if ($_ -match '{*}') { [ODataUtils.TypeProperty] @{ @@ -1890,7 +1890,7 @@ function GetKeys # Else add the key to new key list $keyParams = $keys | ForEach-Object {$_.Name} - if ($keyParams -eq $null -Or $keyParams.Count -eq 0) { + if ($null -eq $keyParams -Or $keyParams.Count -eq 0) { $keys = $key } else { @@ -1924,7 +1924,7 @@ function GetNetworkControllerAdditionalProperties # Additional properties contains the types present as navigation properties - $additionalProperties = $navigationProperties | ? { $_ -ne $null } | %{ + $additionalProperties = $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { $typeName = GetNavigationPropertyTypeName $_ $metaData if ($_.Name -eq "Properties") { @@ -1943,7 +1943,7 @@ function GetNetworkControllerAdditionalProperties # Add etag to the additionalProperties - if ($additionalProperties -ne $null) + if ($null -ne $additionalProperties) { if ($additionalProperties.Count -eq 1) { $additionalProperties = @($additionalProperties) @@ -1984,13 +1984,13 @@ function UpdateNetworkControllerSpecificProperties ) if ($isNullable) { - $additionalProperties = $additionalProperties | ? { $_.isNullable } + $additionalProperties = $additionalProperties | Where-Object { $_.isNullable } } else { - $additionalProperties = $additionalProperties | ? { -not $_.isNullable } + $additionalProperties = $additionalProperties | Where-Object { -not $_.isNullable } } - if ($nullableProperties -eq $null) + if ($null -eq $nullableProperties) { $nullableProperties = $additionalProperties } @@ -1998,12 +1998,12 @@ function UpdateNetworkControllerSpecificProperties if ($nullableProperties.Count -eq 1) { $nullableProperties = @($nullableProperties) } - if ($additionalProperties -ne $null) { + if ($null -ne $additionalProperties) { $nullableProperties += $additionalProperties } } - if ($nullableProperties -ne $null -And $keyProperties -ne $null) + if ($null -ne $nullableProperties -And $null -ne $keyProperties) { if ($keyProperties.Count -eq 1) { $keyProperties = @($keyProperties) diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 index 6023cc67273..8a4c65424f1 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtilsHelper.ps1 @@ -276,7 +276,7 @@ function GetMetaData ) # $metaDataUri is already validated at the cmdlet layer. - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GetMetaData") } + if($null -eq $callerPSCmdletl) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GetMetaData") } Write-Verbose ($LocalizedData.VerboseReadingMetadata -f $metaDataUri) try @@ -305,7 +305,7 @@ function GetMetaData if($uri.IsFile) { - if ($credential -ne $null) + if ($null -ne $credential) { $fileExists = Test-Path -Path $metaDataUri -PathType Leaf -Credential $credential -ErrorAction Stop } @@ -331,12 +331,12 @@ function GetMetaData { $cmdParams = @{'Uri'= $metaDataUri ; 'UseBasicParsing'=$true; 'ErrorAction'= 'Stop'} - if ($credential -ne $null) + if ($null -ne $credential) { $cmdParams.Add('Credential', $credential) } - if ($headers -ne $null) + if ($null -ne $headers) { $cmdParams.Add('Headers', $headers) } @@ -351,13 +351,13 @@ function GetMetaData $callerPSCmdlet.ThrowTerminatingError($errorRecord) } - if($webResponse -ne $null) + if($null -ne $webResponse) { if ($webResponse.StatusCode -eq 200) { $metaData = $webResponse.Content - if ($metadata -eq $null) + if ($null -eq $metadata) { $errorMessage = ($LocalizedData.EmptyMetadata -f $MetadataUri) $errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataIsEmpty" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri @@ -373,7 +373,7 @@ function GetMetaData } } - if($metaData -ne $null) + if($null -ne $metaData) { try { @@ -409,8 +409,8 @@ function VerifyMetadataHelper [System.Management.Automation.PSCmdlet] $callerPSCmdlet ) - if($localizedDataErrorString -eq $null) { throw ($LocalizedData.ArguementNullError -f "localizedDataErrorString", "VerifyMetadataHelper") } - if($localizedDataWarningString -eq $null) { throw ($LocalizedData.ArguementNullError -f "localizedDataWarningString", "VerifyMetadataHelper") } + if($null -eq $localizedDataErrorString) { throw ($LocalizedData.ArguementNullError -f "localizedDataErrorString", "VerifyMetadataHelper") } + if($null -eq $localizedDataWarningString) { throw ($LocalizedData.ArguementNullError -f "localizedDataWarningString", "VerifyMetadataHelper") } if(!$allowClobber) { @@ -442,7 +442,7 @@ function CreateErrorRecordHelper [object] $targetObject ) - if($exception -eq $null) + if($null -eq $exception) { $exception = New-Object System.IO.IOException $errorMessage } @@ -467,8 +467,8 @@ function ProgressBarHelper [int] $currentEntryCount ) - if($cmdletName -eq $null) { throw ($LocalizedData.ArguementNullError -f "CmdletName", "ProgressBarHelper") } - if($status -eq $null) { throw ($LocalizedData.ArguementNullError -f "Status", "ProgressBarHelper") } + if($null -eq $cmdletName) { throw ($LocalizedData.ArguementNullError -f "CmdletName", "ProgressBarHelper") } + if($null -eq $status) { throw ($LocalizedData.ArguementNullError -f "Status", "ProgressBarHelper") } if($currentEntryCount -gt 0 -and $totalNumberofEntries -gt 0 -and @@ -493,7 +493,7 @@ function Convert-ODataTypeToCLRType [Hashtable] $complexTypeMapping ) - if($typeName -eq $null) { throw ($LocalizedData.ArguementNullError -f "TypeName", "Convert-ODataTypeToCLRType ") } + if($null -eq $typeName) { throw ($LocalizedData.ArguementNullError -f "TypeName", "Convert-ODataTypeToCLRType ") } switch ($typeName) { @@ -515,7 +515,7 @@ function Convert-ODataTypeToCLRType "Edm.DateTimeOffset" {"DateTimeOffset"} default { - if($complexTypeMapping -ne $null -and + if($null -ne $complexTypeMapping -and $complexTypeMapping.Count -gt 0 -and $complexTypeMapping.ContainsKey($typeName)) { @@ -555,8 +555,8 @@ function SaveCDXMLHeader ) # $uri & $cmdletAdapter are already validated at the cmdlet layer. - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLHeader") } - if($defaultNoun -eq $null) { throw ($LocalizedData.ArguementNullError -f "DefaultNoun", "SaveCDXMLHeader") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLHeader") } + if($null -eq $defaultNoun) { throw ($LocalizedData.ArguementNullError -f "DefaultNoun", "SaveCDXMLHeader") } if ($className -eq 'ServiceActions' -Or $cmdletAdapter -eq "NetworkControllerAdapter") { @@ -621,7 +621,7 @@ function SaveCDXMLFooter [System.Xml.XmlWriter] $xmlWriter ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLFooter") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLFooter") } $xmlWriter.WriteEndElement() $xmlWriter.WriteEndElement() @@ -653,7 +653,7 @@ function AddParametersNode [Hashtable] $complexTypeMapping ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") } if(($keyProperties.Length -gt 0) -or ($mandatoryProperties.Length -gt 0) -or @@ -667,17 +667,17 @@ function AddParametersNode $pos = 0 - if ($keyProperties -ne $null) + if ($null -ne $keyProperties) { $pos = AddParametersCDXML $xmlWriter $keyProperties $pos $true $prefixForKeys ":Key" $complexTypeMapping } - if ($mandatoryProperties -ne $null) + if ($null -ne $mandatoryProperties) { $pos = AddParametersCDXML $xmlWriter $mandatoryProperties $pos $true $null $null $complexTypeMapping } - if ($otherProperties -ne $null) + if ($null -ne $otherProperties) { $pos = AddParametersCDXML $xmlWriter $otherProperties $pos $false $null $null $complexTypeMapping } @@ -722,7 +722,7 @@ function AddParametersCDXML [Hashtable] $complexTypeMapping ) - $properties | ? { $_ -ne $null } | % { + $properties | Where-Object { $null -ne $_ } | ForEach-Object { $xmlWriter.WriteStartElement('Parameter') $xmlWriter.WriteAttributeString('ParameterName', $_.Name + $suffix) $xmlWriter.WriteStartElement('Type') @@ -763,7 +763,7 @@ function GenerateSetProxyCmdlet ) # $cmdletAdapter is already validated at the cmdlet layer. - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateSetProxyCmdlet") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateSetProxyCmdlet") } $xmlWriter.WriteStartElement('Cmdlet') $xmlWriter.WriteStartElement('CmdletMetadata') diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 index b7aa441111e..b90f7f8aaf4 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 @@ -84,7 +84,7 @@ function GetTypeInfo [Hashtable] $Headers ) - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "callerPSCmdlet", "GetTypeInfo") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "callerPSCmdlet", "GetTypeInfo") } $metadataSet = New-Object System.Collections.ArrayList $metadataXML = GetMetaData $MetadataUri $callerPSCmdlet $ODataEndpointProxyParameters.Credential $Headers $ODataEndpointProxyParameters.AllowUnsecureConnection @@ -116,7 +116,7 @@ function AddMetadataToMetadataSet $NewMetadata ) - if($NewMetadata -eq $null) { throw ($LocalizedData.ArguementNullError -f "NewMetadata", "AddMetadataToMetadataSet") } + if($null -eq $NewMetadata) { throw ($LocalizedData.ArguementNullError -f "NewMetadata", "AddMetadataToMetadataSet") } if ($NewMetadata.GetType().Name -eq 'MetadataV4') { @@ -298,17 +298,17 @@ function ParseEntityTypes [string] $Alias ) - if($SchemaXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseEntityTypes") } + if($null -eq $SchemaXML) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseEntityTypes") } foreach ($entityType in $SchemaXML.EntityType) { $baseType = $null - if ($entityType.BaseType -ne $null) + if ($null -ne $entityType.BaseType) { # add it to the processing queue $baseType = GetBaseType $entityType $Metadata $SchemaXML.Namespace $GlobalMetadata - if ($baseType -eq $null) + if ($null -eq $baseType) { $EntityAndComplexTypesQueue[$entityType.BaseType] += @(@{type='EntityType'; value=$entityType}) } @@ -340,17 +340,17 @@ function ParseComplexTypes [string] $Alias ) - if($SchemaXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseComplexTypes") } + if($null -eq $SchemaXMLl) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseComplexTypes") } foreach ($complexType in $SchemaXML.ComplexType) { $baseType = $null - if ($complexType.BaseType -ne $null) + if ($null -ne $complexType.BaseType) { # add it to the processing queue $baseType = GetBaseType $complexType $metadata $SchemaXML.Namespace $GlobalMetadata - if ($baseType -eq $null -and $entityAndComplexTypesQueue -ne $null -and $entityAndComplexTypesQueue.ContainsKey($complexType.BaseType)) + if ($null -eq $baseType -and $null -ne $entityAndComplexTypesQueue -and $entityAndComplexTypesQueue.ContainsKey($complexType.BaseType)) { $entityAndComplexTypesQueue[$complexType.BaseType] += @(@{type='ComplexType'; value=$complexType}) continue @@ -382,7 +382,7 @@ function ParseTypeDefinitions [string] $Alias ) - if($SchemaXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseTypeDefinitions") } + if($null -eq $SchemaXML) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseTypeDefinitions") } foreach ($typeDefinition in $SchemaXML.TypeDefinition) @@ -409,7 +409,7 @@ function ParseEnumTypes [ODataUtils.MetadataV4] $Metadata ) - if($SchemaXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseEnumTypes") } + if($null -eq $SchemaXML) { throw ($LocalizedData.ArguementNullError -f "SchemaXML", "ParseEnumTypes") } foreach ($enum in $SchemaXML.EnumType) { @@ -428,7 +428,7 @@ function ParseEnumTypes $newEnumType.UnderlyingType = "Edm.Int32" } - if ($newEnumType.IsFlags -eq $null) + if ($null -eq $newEnumType.IsFlags) { # If no value is specified for IsFlags, its value defaults to false. $newEnumType.IsFlags = $false @@ -450,7 +450,7 @@ function ParseEnumTypes $errorRecord = CreateErrorRecordHelper "InValidMetadata" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $detailedErrorMessage nu $PSCmdlet.ThrowTerminatingError($errorRecord) } - elseif (($element.Value -eq $null) -or ($element.Value.GetType().Name -eq "Int32" -and $element.Value -eq "")) + elseif (($null -eq $element.Value) -or ($element.Value.GetType().Name -eq "Int32" -and $element.Value -eq "")) { # If no values are specified, the members are assigned consecutive integer values in the order of their appearance, # starting with zero for the first member. @@ -486,7 +486,7 @@ function ParseSingletonTypes [ODataUtils.MetadataV4] $Metadata ) - if($SchemaEntityContainerXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaEntityContainerXML", "ParseSingletonTypes") } + if($null -eq $SchemaEntityContainerXML) { throw ($LocalizedData.ArguementNullError -f "SchemaEntityContainerXML", "ParseSingletonTypes") } foreach ($singleton in $SchemaEntityContainerXML.Singleton) { @@ -529,7 +529,7 @@ function ParseEntitySets [string] $Alias ) - if($SchemaEntityContainerXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaEntityContainerXML", "ParseEntitySets") } + if($null -eq $SchemaEntityContainerXML) { throw ($LocalizedData.ArguementNullError -f "SchemaEntityContainerXML", "ParseEntitySets") } $entityTypeToEntitySetMapping = @{}; foreach ($entitySet in $SchemaEntityContainerXML.EntitySet) @@ -570,12 +570,12 @@ function ParseActions [ODataUtils.MetadataV4] $Metadata ) - if($SchemaActionsXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaActionsXML", "ParseActions") } + if($null -eq $SchemaActionsXML) { throw ($LocalizedData.ArguementNullError -f "SchemaActionsXML", "ParseActions") } foreach ($action in $SchemaActionsXML) { # HttpMethod is only used for legacy Service Operations - if ($action.HttpMethod -eq $null) + if ($null -eq $action.HttpMethod) { $newAction = [ODataUtils.ActionV4] @{ "Namespace" = $Metadata.Namespace; @@ -587,7 +587,7 @@ function ParseActions # Actions are always SideEffecting, otherwise it's an OData function foreach ($parameter in $action.Parameter) { - if ($parameter.Nullable -ne $null) + if ($null -ne $parameter.Nullable) { $parameterIsNullable = [System.Convert]::ToBoolean($parameter.Nullable); } @@ -605,7 +605,7 @@ function ParseActions $newAction.Parameters += $newParameter } - if ($action.EntitySet -ne $null) + if ($null -ne $action.EntitySet) { $newAction.EntitySet = $metadata.EntitySets | Where-Object { $_.Name -eq $action.EntitySet } } @@ -627,12 +627,12 @@ function ParseFunctions [ODataUtils.MetadataV4] $Metadata ) - if($SchemaFunctionsXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "SchemaFunctionsXML", "ParseFunctions") } + if($null -eq $SchemaFunctionsXML) { throw ($LocalizedData.ArguementNullError -f "SchemaFunctionsXML", "ParseFunctions") } foreach ($function in $SchemaFunctionsXML) { # HttpMethod is only used for legacy Service Operations - if ($function.HttpMethod -eq $null) + if ($null -eq $function.HttpMethod) { $newFunction = [ODataUtils.FunctionV4] @{ "Namespace" = $Metadata.Namespace; @@ -665,7 +665,7 @@ function ParseFunctions # Actions are always SideEffecting, otherwise it's an OData function foreach ($parameter in $function.Parameter) { - if ($parameter.Nullable -ne $null) + if ($null -ne $parameter.Nullable) { $parameterIsNullable = [System.Convert]::ToBoolean($parameter.Nullable); } @@ -699,7 +699,7 @@ function ParseMetadata [System.Collections.ArrayList] $MetadataSet ) - if($MetadataXML -eq $null) { throw ($LocalizedData.ArguementNullError -f "MetadataXML", "ParseMetadata") } + if($null -eq $MetadataXML) { throw ($LocalizedData.ArguementNullError -f "MetadataXML", "ParseMetadata") } # This is a processing queue for those types that require base types that haven't been defined yet $entityAndComplexTypesQueue = @{} @@ -707,7 +707,7 @@ function ParseMetadata foreach ($schema in $MetadataXML.Edmx.DataServices.Schema) { - if ($schema -eq $null) + if ($null -eq $schema) { Write-Error $LocalizedData.EmptySchema continue @@ -770,8 +770,8 @@ function VerifyMetadata [string] $progressBarStatus ) - if($callerPSCmdlet -eq $null) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "VerifyMetaData") } - if($progressBarStatus -eq $null) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "VerifyMetaData") } + if($null -eq $callerPSCmdlet) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "VerifyMetaData") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "VerifyMetaData") } Write-Verbose $LocalizedData.VerboseVerifyingMetadata @@ -784,7 +784,7 @@ function VerifyMetadata { foreach ($entitySet in $metadata.EntitySets) { - if ($entitySet.Type -eq $null) + if ($null -eq $entitySet.Type) { $errorMessage = ($LocalizedData.EntitySetUndefinedType -f $metadata.MetadataUri, $entitySet.Name) $exception = [System.InvalidOperationException]::new($errorMessage) @@ -899,23 +899,23 @@ function GetBaseType [System.Collections.ArrayList] $GlobalMetadata ) - if ($metadataEntityDefinition -ne $null -and - $metaData -ne $null -and - $MetadataEntityDefinition.BaseType -ne $null) + if ($null -ne $metadataEntityDefinition -and + $null -ne $metaData -and + $null -ne $MetadataEntityDefinition.BaseType) { - $baseType = $Metadata.EntityTypes | Where { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType } - if ($baseType -eq $null) + $baseType = $Metadata.EntityTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType } + if ($null -eq $baseType) { - $baseType = $Metadata.ComplexTypes | Where { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType } + $baseType = $Metadata.ComplexTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType } } - if ($baseType -eq $null) + if ($null -eq $baseType) { # Look in other metadatas, since the class can be defined in referenced metadata foreach ($referencedMetadata in $GlobalMetadata) { - if (($baseType = $referencedMetadata.EntityTypes | Where { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType }) -ne $null -or - ($baseType = $referencedMetadata.ComplexTypes | Where { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType }) -ne $null) + if ($null -ne ($baseType = $referencedMetadata.EntityTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType }) -or + $null -ne ($baseType = $referencedMetadata.ComplexTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $MetadataEntityDefinition.BaseType -or $_.Alias + "." + $_.Name -eq $MetadataEntityDefinition.BaseType })) { # Found base class break @@ -924,7 +924,7 @@ function GetBaseType } } - if ($baseType -ne $null) + if ($null -ne $baseType) { $baseType[0] } @@ -942,14 +942,14 @@ function GetBaseTypeByName [System.Collections.ArrayList] $GlobalMetadata ) - if ($BaseTypeStr -ne $null) + if ($null -ne $BaseTypeStr) { # Look for base class definition in all referenced metadatas (including entry point) foreach ($referencedMetadata in $GlobalMetadata) { - if (($baseType = $referencedMetadata.EntityTypes | Where { $_.Namespace + "." + $_.Name -eq $BaseTypeStr -or $_.Alias + "." + $_.Name -eq $BaseTypeStr }) -ne $null -or - ($baseType = $referencedMetadata.ComplexTypes | Where { $_.Namespace + "." + $_.Name -eq $BaseTypeStr -or $_.Alias + "." + $_.Name -eq $BaseTypeStr }) -ne $null) + if ($null -ne ($baseType = $referencedMetadata.EntityTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $BaseTypeStr -or $_.Alias + "." + $_.Name -eq $BaseTypeStr }) -or + $null -ne ($baseType = $referencedMetadata.ComplexTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $BaseTypeStr -or $_.Alias + "." + $_.Name -eq $BaseTypeStr })) { # Found base class break @@ -957,7 +957,7 @@ function GetBaseTypeByName } } - if ($baseType -ne $null) + if ($null -ne $baseType) { $baseType[0] } @@ -979,9 +979,9 @@ function AddDerivedTypes { [string] $namespace ) - if($baseType -eq $null) { throw ($LocalizedData.ArguementNullError -f "BaseType", "AddDerivedTypes") } - if($entityAndComplexTypesQueue -eq $null) { throw ($LocalizedData.ArguementNullError -f "EntityAndComplexTypesQueue", "AddDerivedTypes") } - if($namespace -eq $null) { throw ($LocalizedData.ArguementNullError -f "Namespace", "AddDerivedTypes") } + if($null -eq $baseType) { throw ($LocalizedData.ArguementNullError -f "BaseType", "AddDerivedTypes") } + if($null -eq $entityAndComplexTypesQueue) { throw ($LocalizedData.ArguementNullError -f "EntityAndComplexTypesQueue", "AddDerivedTypes") } + if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "AddDerivedTypes") } $baseTypeFullName = $baseType.Namespace + '.' + $baseType.Name $baseTypeShortName = $baseType.Alias + '.' + $baseType.Name @@ -1025,22 +1025,22 @@ function ParseMetadataTypeDefinitionHelper [bool] $isEntity ) - if($metadataEntityDefinition -eq $null) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } - if($namespace -eq $null) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } + if($null -eq $metadataEntityDefinition) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } + if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } [ODataUtils.EntityTypeV4] $newEntityType = CreateNewEntityType -metadataEntityDefinition $metadataEntityDefinition -baseType $baseType -baseTypeStr $baseTypeStr -namespace $namespace -alias $alias -isEntity $isEntity - if ($baseType -ne $null) + if ($null -ne $baseType) { # Add properties inherited from BaseType ParseMetadataBaseTypeDefinitionHelper $newEntityType $baseType } # properties defined on EntityType - $newEntityType.EntityProperties += $metadataEntityDefinition.Property | % { - if ($_ -ne $null) + $newEntityType.EntityProperties += $metadataEntityDefinition.Property | ForEach-Object { + if ($null -ne $_) { - if ($_.Nullable -ne $null) + if ($null -ne $_.Nullable) { $newPropertyIsNullable = [System.Convert]::ToBoolean($_.Nullable) } @@ -1059,7 +1059,7 @@ function ParseMetadataTypeDefinitionHelper # odataId property will be inherited from base type, if it exists. # Otherwise, it should be added to current type - if ($baseType -eq $null) + if ($null -eq $baseType) { # @odata.Id property (renamed to odataId) is required for dynamic Uri creation # This property is only available when user executes auto-generated cmdlet with -AllowAdditionalData, @@ -1082,7 +1082,7 @@ function ParseMetadataTypeDefinitionHelper } } - if ($metadataEntityDefinition -ne $null -and $metadataEntityDefinition.Key -ne $null) + if ($null -ne $metadataEntityDefinition -and $null -ne $metadataEntityDefinition.Key) { foreach ($entityTypeKey in $metadataEntityDefinition.Key.PropertyRef) { @@ -1104,7 +1104,7 @@ function ParseMetadataBaseTypeDefinitionHelper [ODataUtils.EntityTypeV4] $BaseType ) - if ($EntityType -ne $null -and $BaseType -ne $null) + if ($null -ne $EntityType -and $null -ne $BaseType) { # Add properties inherited from BaseType $EntityType.EntityProperties += $BaseType.EntityProperties @@ -1195,8 +1195,8 @@ function ParseMetadataTypeDefinition [string] $baseTypeStr ) - if($metadataEntityDefinition -eq $null) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } - if($namespace -eq $null) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } + if($null -eq $metadataEntityDefinition) { throw ($LocalizedData.ArguementNullError -f "MetadataEntityDefinition", "ParseMetadataTypeDefinition") } + if($null -eq $namespace) { throw ($LocalizedData.ArguementNullError -f "Namespace", "ParseMetadataTypeDefinition") } [ODataUtils.EntityTypeV4] $newEntityType = ParseMetadataTypeDefinitionHelper -metadataEntityDefinition $metadataEntityDefinition -baseType $baseType -baseTypeStr $baseTypeStr -metadata $metadata -namespace $namespace -alias $alias -isEntity $isEntity ParseMetadataTypeDefinitionNavigationProperties -metadataEntityDefinition $metadataEntityDefinition -entityType $newEntityType @@ -1225,7 +1225,7 @@ function GenerateClientSideProxyModule $NormalizedNamespaces ) - if($progressBarStatus -eq $null) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "ProgressBarStatus", "GenerateClientSideProxyModule") } Write-Verbose ($LocalizedData.VerboseSavingModule -f $OutputModule) @@ -1258,8 +1258,8 @@ function GenerateClientSideProxyModule ProgressBarHelper "Export-ODataEndpointProxy" $progressBarStatus 40 20 $Metadata.Singletons.Count $currentEntryCount } - $actions += $Metadata.Actions | Where-Object { $_.EntitySet -eq '' -or $_.EntitySet -eq $null } - $functions += $Metadata.Functions | Where-Object { $_.EntitySet -eq '' -or $_.EntitySet -eq $null } + $actions += $Metadata.Actions | Where-Object { $_.EntitySet -eq '' -or $null -eq $_.EntitySet } + $functions += $Metadata.Functions | Where-Object { $_.EntitySet -eq '' -or $null -eq $_.EntitySet} } if ($actions.Count -gt 0 -or $functions.Count -gt 0) @@ -1305,8 +1305,8 @@ function SaveCDXML $normalizedNamespaces ) - if($EntitySet -eq $null) { throw ($LocalizedData.ArguementNullError -f "EntitySet", "GenerateClientSideProxyModule") } - if($Metadata -eq $null) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } + if($null -eq $EntitySet) { throw ($LocalizedData.ArguementNullError -f "EntitySet", "GenerateClientSideProxyModule") } + if($null -eq $Metadata) { throw ($LocalizedData.ArguementNullError -f "metadata", "GenerateClientSideProxyModule") } $entitySetName = $EntitySet.Name if(($null -ne $resourceNameMappings) -and @@ -1323,7 +1323,7 @@ function SaveCDXML $xmlWriter = New-Object System.XMl.XmlTextWriter($Path,$Null) - if ($xmlWriter -eq $null) + if ($null -eq $xmlWriter) { throw ($LocalizedData.XmlWriterInitializationError -f $EntitySet.Name) } @@ -1337,9 +1337,9 @@ function SaveCDXML SaveCDXMLInstanceCmdlets $xmlWriter $Metadata $GlobalMetadata $EntitySet.Type $keys $navigationProperties $CmdletAdapter $complexTypeMapping $false - $nonKeyProperties = $EntitySet.Type.EntityProperties | ? { -not $_.isKey } - $nullableProperties = $nonKeyProperties | ? { $_.isNullable } - $nonNullableProperties = $nonKeyProperties | ? { -not $_.isNullable } + $nonKeyProperties = $EntitySet.Type.EntityProperties | Where-Object { -not $_.isKey } + $nullableProperties = $nonKeyProperties | Where-Object { $_.isNullable } + $nonNullableProperties = $nonKeyProperties | Where-Object { -not $_.isNullable } $xmlWriter.WriteStartElement('StaticCmdlets') @@ -1400,7 +1400,7 @@ function SaveCDXML $xmlWriter.WriteEndElement() # Add URI resource path format (webservice.svc/ResourceName/ResourceId vs webservice.svc/ResourceName(QueryKeyName=ResourceId)) - if ($UriResourcePathKeyFormat -ne $null -and $UriResourcePathKeyFormat -ne '') + if ($null -ne $UriResourcePathKeyFormat -and $UriResourcePathKeyFormat -ne [string]::Empty) { $xmlWriter.WriteStartElement('Data') $xmlWriter.WriteAttributeString('Name', 'UriResourcePathKeyFormat') @@ -1460,8 +1460,8 @@ function SaveCDXMLSingletonCmdlets $normalizedNamespaces ) - if($Singleton -eq $null) { throw ($LocalizedData.ArguementNullError -f "Singleton", "SaveCDXMLSingletonCmdlets") } - if($Metadata -eq $null) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLSingletonCmdlets") } + if($null -eq $Singleton) { throw ($LocalizedData.ArguementNullError -f "Singleton", "SaveCDXMLSingletonCmdlets") } + if($null -eq $Metadata) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLSingletonCmdlets") } $singletonName = $singleton.Name $singletonType = $singleton.Type @@ -1470,7 +1470,7 @@ function SaveCDXMLSingletonCmdlets $xmlWriter = New-Object System.XMl.XmlTextWriter($Path,$Null) - if ($xmlWriter -eq $null) + if ($null -eq $xmlWriter) { throw ($LocalizedData.XmlWriterInitializationError -f $singletonName) } @@ -1478,12 +1478,12 @@ function SaveCDXMLSingletonCmdlets # Get associated EntityType $associatedEntityType = $Metadata.EntityTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $singletonType -or $_.Alias + "." + $_.Name -eq $singletonType} - if ($associatedEntityType -eq $null) + if ($null -eq $associatedEntityType) { # Look in other metadatas, since the class can be defined in referenced metadata foreach ($referencedMetadata in $GlobalMetadata) { - if (($associatedEntityType = $referencedMetadata.EntityTypes | Where { $_.Namespace + "." + $_.Name -eq $singletonType -or $_.Alias + "." + $_.Name -eq $singletonType }) -ne $null) + if ($null -ne ($associatedEntityType = $referencedMetadata.EntityTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $singletonType -or $_.Alias + "." + $_.Name -eq $singletonType })) { # Found associated class break @@ -1491,11 +1491,11 @@ function SaveCDXMLSingletonCmdlets } } - if ($associatedEntityType -ne $null) + if ($null -ne $associatedEntityType) { $xmlWriter = SaveCDXMLHeader $xmlWriter $Uri $singletonName $singletonName $CmdletAdapter - if ($associatedEntityType.BaseType -eq $null -and $associatedEntityType.BaseTypeStr -ne $null -and $associatedEntityType.BaseTypeStr -ne '') + if ($null -eq $associatedEntityType.BaseTyp -and $null -ne $associatedEntityType.BaseTypeStr -and $associatedEntityType.BaseTypeStr -ne '') { $associatedEntitybaseType = GetBaseTypeByName $associatedEntityType.BaseTypeStr $GlobalMetadata @@ -1510,9 +1510,9 @@ function SaveCDXMLSingletonCmdlets SaveCDXMLInstanceCmdlets $xmlWriter $Metadata $GlobalMetadata $associatedEntityType $keys $navigationProperties $CmdletAdapter $complexTypeMapping $true - $nonKeyProperties = $associatedEntityType.EntityProperties | ? { -not $_.isKey } - $nullableProperties = $nonKeyProperties | ? { $_.isNullable } - $nonNullableProperties = $nonKeyProperties | ? { -not $_.isNullable } + $nonKeyProperties = $associatedEntityType.EntityProperties | Where-Object { -not $_.isKey } + $nullableProperties = $nonKeyProperties | Where-Object { $_.isNullable } + $nonNullableProperties = $nonKeyProperties | Where-Object { -not $_.isNullable } $xmlWriter.WriteStartElement('StaticCmdlets') @@ -1612,8 +1612,8 @@ function SaveCDXMLInstanceCmdlets [bool] $isSingleton ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLInstanceCmdlets") } - if($Metadata -eq $null) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLInstanceCmdlets") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLInstanceCmdlets") } + if($null -eq $Metadata) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLInstanceCmdlets") } $xmlWriter.WriteStartElement('InstanceCmdlets') $xmlWriter.WriteStartElement('GetCmdletParameters') @@ -1627,10 +1627,10 @@ function SaveCDXMLInstanceCmdlets { foreach ($navProperty in $navigationProperties) { - if ($navProperty -ne $null) + if ($null -ne $navProperty) { $associatedType = GetAssociatedType $Metadata $GlobalMetadata $navProperty - $associatedTypeKeyProperties = $associatedType.EntityProperties | ? { $_.IsKey } + $associatedTypeKeyProperties = $associatedType.EntityProperties | Where-Object { $_.IsKey } # Make sure associated parameter (based on navigation property) has EntitySet or Singleton, which makes it accessible from the service root # Otherwise the Uri for associated navigation property won't be valid @@ -1660,7 +1660,7 @@ function SaveCDXMLInstanceCmdlets if ($isSingleton -eq $false) { - $keys | ? { $_ -ne $null } | % { + $keys | Where-Object { $null -ne $_ } | ForEach-Object { $xmlWriter.WriteStartElement('Property') $xmlWriter.WriteAttributeString('PropertyName', $_.Name) @@ -1786,7 +1786,7 @@ function ShouldBeAssociatedParameter ) # Check if associated type has navigation property, which links back to current type - $associatedTypeNavProperties = $AssociatedType.NavigationProperties | ? { + $associatedTypeNavProperties = $AssociatedType.NavigationProperties | Where-Object { $_.Type -eq ($EntityType.Namespace + "." + $EntityType.Name) -or $_.Type -eq ($EntityType.Alias + "." + $EntityType.Name) -or $_.Type -eq ("Collection(" + $EntityType.Namespace + "." + $EntityType.Name + ")") -or @@ -1845,8 +1845,8 @@ function SaveCDXMLNewCmdlet $complexTypeMapping ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLNewCmdlet") } - if($Metadata -eq $null) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLNewCmdlet") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLNewCmdlet") } + if($null -eq $Metadata) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLNewCmdlet") } $xmlWriter.WriteStartElement('Cmdlet') $xmlWriter.WriteStartElement('CmdletMetadata') @@ -1863,7 +1863,7 @@ function SaveCDXMLNewCmdlet $xmlWriter.WriteEndElement() - $navigationProperties | ? { $_ -ne $null } | % { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { $associatedType = GetAssociatedType $Metadata $GlobalMetadata $_ $associatedEntitySet = GetEntitySetForEntityType $Metadata $associatedType @@ -1871,7 +1871,7 @@ function SaveCDXMLNewCmdlet $xmlWriter.WriteAttributeString('MethodName', "Association:Create:$($associatedEntitySet.Name)") $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) - $associatedKeys = ($associatedType.EntityProperties | ? { $_.isKey }) + $associatedKeys = ($associatedType.EntityProperties | Where-Object { $_.isKey }) AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping @@ -1890,11 +1890,11 @@ function GetEntitySetForEntityType { [ODataUtils.EntityTypeV4] $entityType ) - if($entityType -eq $null) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetEntitySetForEntityType") } + if($null -eq $entityType) { throw ($LocalizedData.ArguementNullError -f "EntityType", "GetEntitySetForEntityType") } - $result = $Metadata.EntitySets | ? { ($_.Type.Namespace -eq $entityType.Namespace) -and ($_.Type.Name -eq $entityType.Name) } + $result = $Metadata.EntitySets | Where-Object { ($_.Type.Namespace -eq $entityType.Namespace) -and ($_.Type.Name -eq $entityType.Name) } - if (($result.Count -eq 0) -and ($entityType.BaseType -ne $null)) + if (($result.Count -eq 0) -and ($null -eq $entityType.BaseType)) { GetEntitySetForEntityType $Metadata $entityType.BaseType } @@ -1922,8 +1922,8 @@ function SaveCDXMLRemoveCmdlet $complexTypeMapping ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLRemoveCmdlet") } - if($Metadata -eq $null) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLRemoveCmdlet") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLRemoveCmdlet") } + if($null -eq $Metadata) { throw ($LocalizedData.ArguementNullError -f "Metadata", "SaveCDXMLRemoveCmdlet") } $xmlWriter.WriteStartElement('Cmdlet') $xmlWriter.WriteStartElement('CmdletMetadata') @@ -1940,7 +1940,7 @@ function SaveCDXMLRemoveCmdlet $xmlWriter.WriteEndElement() - $navigationProperties | ? { $_ -ne $null } | % { + $navigationProperties | Where-Object { $null -ne $_ } | ForEach-Object { $associatedType = GetAssociatedType $Metadata $GlobalMetadata $_ $associatedEntitySet = GetEntitySetForEntityType $Metadata $associatedType @@ -1950,7 +1950,7 @@ function SaveCDXMLRemoveCmdlet $xmlWriter.WriteAttributeString('CmdletParameterSet', $_.Name) $associatedType = GetAssociatedType $Metadata $GlobalMetadata $_ - $associatedKeys = ($associatedType.EntityProperties | ? { $_.isKey }) + $associatedKeys = ($associatedType.EntityProperties | Where-Object { $_.isKey }) AddParametersNode $xmlWriter $associatedKeys $keyProperties $null "Associated$($_.Name)" $true $true $complexTypeMapping @@ -1975,17 +1975,17 @@ function GetAssociatedType { $associationType = $associationType.Replace("Collection(", "") $associationType = $associationType.Replace(")", "") - $associatedType = $Metadata.EntityTypes | ? { $_.Name -eq $associationType } + $associatedType = $Metadata.EntityTypes | Where-Object { $_.Name -eq $associationType } - if (!$associatedType -and $GlobalMetadata -ne $null) + if (!$associatedType -and $null -ne $GlobalMetadata) { $associationFullTypeName = $navProperty.Type.Replace("Collection(", "").Replace(")", "") foreach ($referencedMetadata in $GlobalMetadata) { - if (($associatedType = $referencedMetadata.EntityTypes | Where { $_.Namespace + "." + $_.Name -eq $associationFullTypeName -or $_.Alias + "." + $_.Name -eq $associationFullTypeName }) -ne $null -or - ($associatedType = $referencedMetadata.ComplexTypes | Where { $_.Namespace + "." + $_.Name -eq $associationFullTypeName -or $_.Alias + "." + $_.Name -eq $associationFullTypeName }) -ne $null -or - ($associatedType = $referencedMetadata.EnumTypes | Where { $_.Namespace + "." + $_.Name -eq $associationFullTypeName -or $_.Alias + "." + $_.Name -eq $associationFullTypeName }) -ne $null) + if ($null -ne ($associatedType = $referencedMetadata.EntityTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $associationFullTypeName -or $_.Alias + "." + $_.Name -eq $associationFullTypeName }) -or + $null -ne ($associatedType = $referencedMetadata.ComplexTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $associationFullTypeName -or $_.Alias + "." + $_.Name -eq $associationFullTypeName }) -or + $null -ne ($associatedType = $referencedMetadata.EnumTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $associationFullTypeName -or $_.Alias + "." + $_.Name -eq $associationFullTypeName })) { # Found associated class break @@ -2022,8 +2022,8 @@ function SaveCDXMLAction [Hashtable] $complexTypeMapping ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLAction") } - if($action -eq $null) { throw ($LocalizedData.ArguementNullError -f "action", "SaveCDXMLAction") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLAction") } + if($null -eq $action) { throw ($LocalizedData.ArguementNullError -f "action", "SaveCDXMLAction") } $xmlWriter.WriteStartElement('Cmdlet') @@ -2038,7 +2038,7 @@ function SaveCDXMLAction $xmlWriter.WriteStartElement('Parameters') - $keys | ? { $_ -ne $null } | % { + $keys | Where-Object { $null -ne $_ } | ForEach-Object { $xmlWriter.WriteStartElement('Parameter') $xmlWriter.WriteAttributeString('ParameterName', $_.Name + ':Key') @@ -2110,8 +2110,8 @@ function SaveCDXMLFunction [Hashtable] $complexTypeMapping ) - if($xmlWriter -eq $null) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLFunction") } - if($function -eq $null) { throw ($LocalizedData.ArguementNullError -f "function", "SaveCDXMLFunction") } + if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLFunction") } + if($null -eq $function) { throw ($LocalizedData.ArguementNullError -f "function", "SaveCDXMLFunction") } $xmlWriter.WriteStartElement('Cmdlet') @@ -2133,7 +2133,7 @@ function SaveCDXMLFunction $xmlWriter.WriteStartElement('Parameters') - $keys | ? { $_ -ne $null } | % { + $keys | Where-Object { $null -ne $_ } | ForEach-Object { $xmlWriter.WriteStartElement('Parameter') $xmlWriter.WriteAttributeString('ParameterName', $_.Name + ':Key') @@ -2206,7 +2206,7 @@ function SaveServiceActionsCDXML $xmlWriter = New-Object System.XMl.XmlTextWriter($Path,$Null) - if ($xmlWriter -eq $null) + if ($null -eq $xmlWriter) { throw $LocalizedData.XmlWriterInitializationError -f "ServiceActions" } @@ -2218,8 +2218,8 @@ function SaveServiceActionsCDXML foreach ($Metadata in $GlobalMetadata) { - $actions += $Metadata.Actions | Where-Object { $_.EntitySet -eq '' -or $_.EntitySet -eq $null } - $functions += $Metadata.Functions | Where-Object { $_.EntitySet -eq '' -or $_.EntitySet -eq $null } + $actions += $Metadata.Actions | Where-Object { $_.EntitySet -eq [string]::Empty -or $null -eq $_.EntitySet } + $functions += $Metadata.Functions | Where-Object { $_.EntitySet -eq [string]::Empty -or $null -eq $_.EntitySet} } if ($actions.Length -gt 0 -or $functions.Length -gt 0) @@ -2232,7 +2232,7 @@ function SaveServiceActionsCDXML { foreach ($action in $actions) { - if ($action -ne $null) + if ($null -ne $action) { $xmlWriter = SaveCDXMLAction $xmlWriter $action '' $false $null $complexTypeMapping } @@ -2244,7 +2244,7 @@ function SaveServiceActionsCDXML { foreach ($function in $functions) { - if ($function -ne $null) + if ($null -ne $function) { $xmlWriter = SaveCDXMLFunction $xmlWriter $function '' $false $null $complexTypeMapping } @@ -2312,7 +2312,7 @@ function GenerateModuleManifest [string] $progressBarStatus ) - if($progressBarStatus -eq $null) { throw ($LocalizedData.ArguementNullError -f "progressBarStatus", "GenerateModuleManifest") } + if($null -eq $progressBarStatus) { throw ($LocalizedData.ArguementNullError -f "progressBarStatus", "GenerateModuleManifest") } $NestedModules = @() @@ -2389,7 +2389,7 @@ using System.ComponentModel; foreach ($entityType in $typesToBeGenerated) { - if ($entityType -ne $null) + if ($null -ne $entityType) { $entityTypeFullName = $entityType.Namespace + '.' + $entityType.Name if(!$complexTypeMapping.ContainsKey($entityTypeFullName)) @@ -2399,7 +2399,7 @@ using System.ComponentModel; # In short name we use Alias instead of Namespace # We will add short name to $complexTypeMapping to enable Alias based search - if ($entityType.Alias -ne $null -and $entityType.Alias -ne "") + if ($null -ne $entityType.Alias -and $entityType.Alias -ne "") { $entityTypeShortName = $entityType.Alias + '.' + $entityType.Name if(!$complexTypeMapping.ContainsKey($entityTypeShortName)) @@ -2412,7 +2412,7 @@ using System.ComponentModel; foreach ($enumType in $enumTypesToBeGenerated) { - if ($enumType -ne $null) + if ($null -ne $enumType) { $enumTypeFullName = $enumType.Namespace + '.' + $enumType.Name if(!$complexTypeMapping.ContainsKey($enumTypeFullName)) @@ -2420,9 +2420,9 @@ using System.ComponentModel; $complexTypeMapping.Add($enumTypeFullName, $enumType.Name) } - if (($enumType.Alias -ne $null -and $enumType.Alias -ne "") -or ($metadata.Alias -ne $null -and $metadata.Alias -ne "")) + if (($null -ne $enumType.Alias -and $enumType.Alias -ne "") -or ($null -ne $metadata.Alias -and $metadata.Alias -ne [string]::Empty)) { - if ($enumType.Alias -ne $null -and $enumType.Alias -ne "") + if ($null -ne $enumType.Alias -and $enumType.Alias -ne "") { $alias = $enumType.Alias } @@ -2442,7 +2442,7 @@ using System.ComponentModel; foreach ($typeDefinition in $typeDefinitionsToBeGenerated) { - if ($typeDefinition -ne $null) + if ($null -ne $typeDefinition) { $typeDefinitionFullName = $typeDefinition.Namespace + '.' + $typeDefinition.Name if(!$complexTypeMapping.ContainsKey($typeDefinitionFullName)) @@ -2473,7 +2473,7 @@ using System.ComponentModel; if($typesToBeGenerated.Count -gt 0 -or $enumTypesToBeGenerated.Count -gt 0) { - if ($metadata.Alias -ne $null -and $metadata.Alias -ne "") + if ($null -ne $metadata.Alias -and $metadata.Alias -ne [string]::Empty) { # Check if this namespace has to be normalized in the .Net namespace/class definitions file. $dotNetAlias = GetNamespace $metadata.Alias $normalizedNamespaces @@ -2498,7 +2498,7 @@ namespace $($dotNetNamespace) foreach ($typeDefinition in $typeDefinitionsToBeGenerated) { - if ($typeDefinition -ne $null) + if ($null -ne $typeDefinition) { Write-Verbose ($LocalizedData.VerboseAddingTypeDefinationToGeneratedModule -f $typeDefinitionFullName, "$OutputModule\$typeDefinationFileName") @@ -2516,7 +2516,7 @@ namespace $($dotNetNamespace) foreach ($enumType in $enumTypesToBeGenerated) { - if ($enumType -ne $null) + if ($null -ne $enumType) { $enumTypeFullName = $enumType.Namespace + '.' + $enumType.Name @@ -2573,20 +2573,20 @@ namespace $($dotNetNamespace) foreach ($entityType in $typesToBeGenerated) { - if ($entityType -ne $null) + if ($null -ne $entityType) { $entityTypeFullName = $entityType.Namespace + '.' + $entityType.Name Write-Verbose ($LocalizedData.VerboseAddingTypeDefinationToGeneratedModule -f $entityTypeFullName, "$OutputModule\$typeDefinationFileName") - if ($entityType.BaseTypeStr -ne $null -and $entityType.BaseTypeStr -ne '' -and $entityType.BaseType -eq $null) + if ($null -ne $entityType.BaseTypeStr -and $entityType.BaseTypeStr -ne '' -and $null -eq $entityType.BaseType) { # This class inherits from another class, but we were not able to find base class during Parsing. # We'll make another attempt. foreach ($referencedMetadata in $GlobalMetadata) { - if (($baseType = $referencedMetadata.EntityTypes | Where { $_.Namespace + "." + $_.Name -eq $entityType.BaseTypeStr -or $_.Alias + "." + $_.Name -eq $entityType.BaseTypeStr }) -ne $null -or - ($baseType = $referencedMetadata.ComplexTypes | Where { $_.Namespace + "." + $_.Name -eq $entityType.BaseTypeStr -or $_.Alias + "." + $_.Name -eq $entityType.BaseTypeStr }) -ne $null) + if ($null -ne ($baseType = $referencedMetadata.EntityTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $entityType.BaseTypeStr -or $_.Alias + "." + $_.Name -eq $entityType.BaseTypeStr }) -or + $null -ne ($baseType = $referencedMetadata.ComplexTypes | Where-Object { $_.Namespace + "." + $_.Name -eq $entityType.BaseTypeStr -or $_.Alias + "." + $_.Name -eq $entityType.BaseTypeStr })) { # Found base class $entityType.BaseType = $baseType diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 2a8d104cf2d..7422a835395 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -3578,7 +3578,7 @@ private static ScriptBlock CimKeywordImplementationFunction # walk the call stack to get at all of the enclosing configuration resource IDs $stackedConfigs = @(Get-PSCallStack | - where { ($_.InvocationInfo.MyCommand -ne $null) -and ($_.InvocationInfo.MyCommand.CommandType -eq 'Configuration') }) + where { ($null -ne $_.InvocationInfo.MyCommand) -and ($_.InvocationInfo.MyCommand.CommandType -eq 'Configuration') }) # keep all but the top-most $stackedConfigs = $stackedConfigs[0..(@($stackedConfigs).Length - 2)] # and build the complex resource ID suffix. @@ -3614,7 +3614,7 @@ function Test-DependsOn } $value['DependsOn']= $updatedDependsOn - if($DependsOn -ne $null) + if($null -ne $DependsOn) { # # Combine DependsOn with dependson from outer composite resource @@ -3683,11 +3683,11 @@ function Test-DependsOn Test-DependsOn # Check if PsDscRunCredential is being specified as Arguments to Configuration - if($PsDscRunAsCredential -ne $null) + if($null -ne $PsDscRunAsCredential) { # Check if resource is also trying to set the value for RunAsCred # In that case we will generate error during compilation, this is merge error - if($value['PsDscRunAsCredential'] -ne $null) + if($null -ne $value['PsDscRunAsCredential']) { Update-ConfigurationErrorCount Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::PsDscRunAsCredentialMergeErrorForCompositeResources($resourceId)) @@ -3719,19 +3719,19 @@ function Test-DependsOn Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::DisabledRefreshModeNotValidForPartialConfig($resourceId)) } - if($value['ConfigurationSource'] -ne $null) + if($null -ne $value['ConfigurationSource']) { Set-NodeManager $resourceId $value['ConfigurationSource'] } - if($value['ResourceModuleSource'] -ne $null) + if($null -ne $value['ResourceModuleSource']) { Set-NodeResourceSource $resourceId $value['ResourceModuleSource'] } } - if($value['ExclusiveResources'] -ne $null) + if($null -ne $value['ExclusiveResources']) { # make sure the references are well-formed foreach ($ExclusiveResource in $value['ExclusiveResources']) { @@ -3774,7 +3774,7 @@ function Test-DependsOn # If there is and user-provided value is not in that list, write an error. if ($allowedValues) { - if(($value[$key] -eq $null) -and ($allowedValues -notcontains $value[$key])) + if(($null -eq $value[$key]) -and ($allowedValues -notcontains $value[$key])) { Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::InvalidValueForPropertyErrorRecord($key, ""$($value[$key])"", $keywordData.Keyword, ($allowedValues -join ', '))) Update-ConfigurationErrorCount @@ -3804,7 +3804,7 @@ function Test-DependsOn if($allowedRange) { $castedValue = $value[$key] -as [int] - if((($castedValue -is [int]) -and (($castedValue -lt $keywordData.Properties[$key].Range.Item1) -or ($castedValue -gt $keywordData.Properties[$key].Range.Item2))) -or ($castedValue -eq $null)) + if((($castedValue -is [int]) -and (($castedValue -lt $keywordData.Properties[$key].Range.Item1) -or ($castedValue -gt $keywordData.Properties[$key].Range.Item2))) -or ($null -eq $castedValue)) { Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache]::ValueNotInRangeErrorRecord($key, $keywordName, $value[$key], $keywordData.Properties[$key].Range.Item1, $keywordData.Properties[$key].Range.Item2)) Update-ConfigurationErrorCount @@ -3815,7 +3815,7 @@ function Test-DependsOn if ($keywordData.Properties[$key].IsKey) { - if($value[$key] -eq $null) + if($null -eq $value[$key]) { $keyValues += ""::__NULL__"" } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs index 4890ff1b8e1..0c6456d1299 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs @@ -102,7 +102,7 @@ internal static IEnumerable GetFormatData() .AddScriptBlockExpressionBinding(@"function GetParam { if(-not $_.Parameters) { return $null } - $_.Parameters.Parameter | % { + $_.Parameters.Parameter | ForEach-Object { if($_.type) { $param = ""[$($_.type.name)] `$$($_.name), "" } else { $param = ""[object] `$$($_.name), "" } $params += $param diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs index fa5db34be53..3240ef5d169 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs @@ -541,7 +541,7 @@ private static IEnumerable ViewsOf_HelpInfoShort() .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Category") - .AddScriptBlockColumn("if ($_.ModuleName -ne $null) { $_.ModuleName } else {$_.PSSnapIn}") + .AddScriptBlockColumn("if ($null -ne $_.ModuleName) { $_.ModuleName } else {$_.PSSnapIn}") .AddPropertyColumn("Synopsis") .EndRowDefinition() .EndTable()); @@ -764,15 +764,15 @@ private static IEnumerable ViewsOf_MamlCommandHelpInfo_Ful .AddNewline() .EndFrame() .AddPropertyExpressionBinding(@"terminatingErrors", selectedByScript: @" - (($_.terminatingErrors -ne $null) -and - ($_.terminatingErrors.terminatingError -ne $null)) + (($null -ne $_.terminatingErrors) -and + ($null -ne $_.terminatingErrors.terminatingError)) ", customControl: control13) .AddPropertyExpressionBinding(@"nonTerminatingErrors", selectedByScript: @" - (($_.nonTerminatingErrors -ne $null) -and - ($_.nonTerminatingErrors.nonTerminatingError -ne $null)) + (($null -ne $_.nonTerminatingErrors) -and + ($null -ne $_.nonTerminatingErrors.nonTerminatingError)) ", customControl: control14) - .AddPropertyExpressionBinding(@"alertSet", selectedByScript: "$_.alertSet -ne $null", customControl: control15) - .AddPropertyExpressionBinding(@"alertSet", enumerateCollection: true, selectedByScript: "$_.alertSet -ne $null", customControl: control16) + .AddPropertyExpressionBinding(@"alertSet", selectedByScript: "$null -ne $_.alertSet", customControl: control15) + .AddPropertyExpressionBinding(@"alertSet", enumerateCollection: true, selectedByScript: "$null -ne $_.alertSet", customControl: control16) .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Examples", customControl: sharedControls[7]) .AddNewline() diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs index c2fb419b8ff..804f95975cd 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -15,7 +15,7 @@ internal static IEnumerable GetFormatData() .StartEntry() .StartFrame(leftIndent: 4) .AddText(FileSystemProviderStrings.DirectoryDisplayGrouping) - .AddScriptBlockExpressionBinding(@"Split-Path -Parent $_.Path | %{ if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent") + .AddScriptBlockExpressionBinding(@"Split-Path -Parent $_.Path | ForEach-Object{ if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent") .AddNewline() .EndFrame() .EndEntry() @@ -612,7 +612,7 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co .AddScriptBlockColumn(@"if($_.Used -or $_.Free) { ""{0:###0.00}"" -f ($_.Used / 1GB) }", alignment: Alignment.Right) .AddScriptBlockColumn(@"if($_.Used -or $_.Free) { ""{0:###0.00}"" -f ($_.Free / 1GB) }", alignment: Alignment.Right) .AddScriptBlockColumn("$_.Provider.Name") - .AddScriptBlockColumn("if($_.DisplayRoot -ne $null) { $_.DisplayRoot } else { $_.Root }") + .AddScriptBlockColumn("if($null -ne $_.DisplayRoot) { $_.DisplayRoot } else { $_.Root }") .AddPropertyColumn("CurrentLocation", alignment: Alignment.Right) .EndRowDefinition() .EndTable()); @@ -792,7 +792,7 @@ private static IEnumerable ViewsOf_System_Management_Autom $width = $host.UI.RawUI.BufferSize.Width - $indent - 2 $errorCategoryMsg = & { Set-StrictMode -Version 1; $_.ErrorCategory_Message } - if ($errorCategoryMsg -ne $null) + if ($null -ne $errorCategoryMsg) { $indentString = ""+ CategoryInfo : "" + $_.ErrorCategory_Message } @@ -808,7 +808,7 @@ private static IEnumerable ViewsOf_System_Management_Autom foreach($line in @($indentString -split ""(.{$width})"")) { if($line) { $posmsg += ("" "" * $indent + $line) } } $originInfo = & { Set-StrictMode -Version 1; $_.OriginInfo } - if (($originInfo -ne $null) -and ($originInfo.PSComputerName -ne $null)) + if (($null -ne $originInfo) -and ($null -ne $originInfo.PSComputerName)) { $indentString = ""+ PSComputerName : "" + $originInfo.PSComputerName $posmsg += ""`n"" @@ -964,7 +964,7 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddPropertyColumn("Id") .AddPropertyColumn("Name") .AddScriptBlockColumn(@" - if ($_.ConnectionInfo -ne $null) + if ($null -ne $_.ConnectionInfo) { $_.ConnectionInfo.ComputerName } @@ -985,7 +985,7 @@ private static IEnumerable ViewsOf_System_Management_Autom ") .AddScriptBlockColumn("$_.RunspaceStateInfo.State") .AddScriptBlockColumn(@" - if (($_.Debugger -ne $null) -and ($_.Debugger.InBreakpoint)) + if (($null -ne $_.Debugger) -and ($_.Debugger.InBreakpoint)) { ""InBreakpoint"" } @@ -1193,7 +1193,7 @@ private static IEnumerable ViewsOf_ModuleInfoGrouping(Cust { yield return new FormatViewDefinition("Module", TableControl.Create() - .GroupByScriptBlock("Split-Path -Parent $_.Path | %{ if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent", customControl: sharedControls[0]) + .GroupByScriptBlock("Split-Path -Parent $_.Path | ForEach-Object{ if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent", customControl: sharedControls[0]) .AddHeader(Alignment.Left, width: 10) .AddHeader(Alignment.Left, width: 10) .AddHeader(Alignment.Left, width: 35) diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs index 1ab20dc5e77..509645844a3 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs @@ -199,7 +199,7 @@ internal static void HandleComputerNameProperties(PSObject so, List In this case we want to show + // Ex: icm $s { gps } | Select-Object pscomputername --> In this case we want to show // PSComputerName if ((null != so.Properties[RemotingConstants.ComputerNameNoteProperty]) && (!PSObjectHelper.ShouldShowComputerNameProperty(so))) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 74c3de498e1..3ff457b1516 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -1081,14 +1081,14 @@ private static List PSv2FindMatches(PowerShellExecutio { powershell.AddScript(String.Format( CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -Relative -WarningAction SilentlyContinue | %{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", + "& {{ trap {{ continue }} ; resolve-path {0} -Relative -WarningAction SilentlyContinue | ForEach-Object{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", path)); } else { powershell.AddScript(String.Format( CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -WarningAction SilentlyContinue | %{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", + "& {{ trap {{ continue }} ; resolve-path {0} -WarningAction SilentlyContinue | ForEach-Object{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", path)); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 6ce9ab17503..c08b71a86b1 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -4794,7 +4794,7 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var public override AstVisitAction VisitCommand(CommandAst commandAst) { // MSFT: 784739 Stack overflow during tab completion of pipeline variable - // $null | % -pv p { $p -> In this case $p is pipelinevariable + // $null | ForEach-Object -pv p { $p -> In this case $p is pipelinevariable // and is used in the same command. PipelineVariables are not available // in the command they are assigned in. Hence the following code ignores // if the variable being completed is in the command extent. diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 17c71643719..8b3beb9c3c1 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -991,7 +991,7 @@ protected internal override void ProcessNewEvent(PSEventArgs newEvent, // invocation to the current runspace, we took dependency on eventing infrastructure and // this required ensuring the event and associated action be processed in the current thread // synchronously. The below while loop was added for that (win8: 530495). However, fix for - // 530495 resulted in hang for icm | % { icm } case and dynamic event/subscriptions scenarios. + // 530495 resulted in hang for icm | ForEach-Object { icm } case and dynamic event/subscriptions scenarios. // To overcome that, changed "processSynchronously" parameter to "processInCurrentThread" and added // a new parameter "waitForCompletionWhenInCurrentThread" to trigger blocking for ScriptBlock // case. diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index 0764124c19e..e9bf2d9fcd2 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -1020,7 +1020,7 @@ private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule -Recurse ` -ErrorAction SilentlyContinue - if ($previousOnRemoveScript -ne $null) + if ($null -ne $previousOnRemoveScript) { & $previousOnRemoveScript $args } @@ -1510,7 +1510,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( -Recurse ` -ErrorAction SilentlyContinue - if ($previousOnRemoveScript -ne $null) + if ($null -ne $previousOnRemoveScript) { & $previousOnRemoveScript $args } diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index be5ce9d3089..3c33d4d2449 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -899,7 +899,7 @@ private bool InitShouldLogPipelineExecutionDetail() /// /// This allows all success output to be set to a variable, where the variable is reset for each item returned by - /// the cmdlet. Semantically this is equivalent to : cmd | % { $pipelineVariable = $_; (...) } + /// the cmdlet. Semantically this is equivalent to : cmd | ForEach-Object { $pipelineVariable = $_; (...) } /// internal string PipelineVariable { get; set; } private PSVariable _pipelineVarReference = null; diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index b927bf93300..c35e946d272 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -450,7 +450,7 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD * b = T / 9 * * Some sample values (for T=90): - * t | %rem + * t | ForEach-Objectrem * ----------- * 0 | 100.0% * 5 | 66.6% diff --git a/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs b/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs index c5a3012184e..36aecab308f 100644 --- a/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs @@ -50,7 +50,7 @@ public static IEnumerable Get() td2.Members.Add("ConnectedUser", new ScriptPropertyData(@"ConnectedUser", GetScriptBlock(@"$this.UserInfo.Identity.Name"), null)); td2.Members.Add("RunAsUser", - new ScriptPropertyData(@"RunAsUser", GetScriptBlock(@"if($this.UserInfo.WindowsIdentity -ne $null) + new ScriptPropertyData(@"RunAsUser", GetScriptBlock(@"if($null -ne $this.UserInfo.WindowsIdentity) { $this.UserInfo.WindowsIdentity.Name }"), null)); diff --git a/src/System.Management.Automation/engine/Types_Ps1Xml.cs b/src/System.Management.Automation/engine/Types_Ps1Xml.cs index f90ee3f1652..c74d0d7a1f0 100644 --- a/src/System.Management.Automation/engine/Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/Types_Ps1Xml.cs @@ -151,7 +151,7 @@ public static IEnumerable Get() td17.Members.Add("DisplayName", new ScriptPropertyData(@"DisplayName", GetScriptBlock(@"if ($this.Name.IndexOf('-') -lt 0) { - if ($this.ResolvedCommand -ne $null) + if ($null -ne $this.ResolvedCommand) { $this.Name + "" -> "" + $this.ResolvedCommand.Name } @@ -232,10 +232,10 @@ public static IEnumerable Get() var td24 = new TypeData(@"System.Management.ManagementObject#root\cimv2\Win32_PingStatus", true); td24.Members.Add("IPV4Address", new ScriptPropertyData(@"IPV4Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | ?{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | select -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); td24.Members.Add("IPV6Address", new ScriptPropertyData(@"IPV6Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | ?{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | select -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); yield return td24; var td25 = new TypeData(@"System.Management.ManagementObject#root\cimv2\Win32_Process", true); @@ -1103,10 +1103,10 @@ public static IEnumerable Get() $helpObject = get-help -Name $commandName -Category ([string]($this.CommandType)) -ErrorAction SilentlyContinue # return first non-null uri (and try not to hit any strict mode things) - if ($helpObject -eq $null) { return $null } - if ($helpObject.psobject.properties['relatedLinks'] -eq $null) { return $null } - if ($helpObject.relatedLinks.psobject.properties['navigationLink'] -eq $null) { return $null } - $helpUri = [string]$( $helpObject.relatedLinks.navigationLink | %{ if ($_.psobject.properties['uri'] -ne $null) { $_.uri } } | ?{ $_ } | select -first 1 ) + if ($null -eq $helpObject) { return $null } + if ($null -eq $helpObject.psobject.properties['relatedLinks']) { return $null } + if ($null -eq $helpObject.relatedLinks.psobject.properties['navigationLink']) { return $null } + $helpUri = [string]$( $helpObject.relatedLinks.navigationLink | ForEach-Object{ if ($null -ne $_.psobject.properties['uri']) { $_.uri } } | Where-Object{ $_ } | Select-Object -first 1 ) return $helpUri } else @@ -1296,9 +1296,9 @@ public static IEnumerable Get() var td165 = new TypeData(@"System.Management.Automation.CallStackFrame", true); td165.Members.Add("Command", - new ScriptPropertyData(@"Command", GetScriptBlock(@"if ($this.InvocationInfo -eq $null) { return $this.FunctionName } + new ScriptPropertyData(@"Command", GetScriptBlock(@"if ($null -eq $this.InvocationInfo) { return $this.FunctionName } $commandInfo = $this.InvocationInfo.MyCommand - if ($commandInfo -eq $null) { return $this.InvocationInfo.InvocationName } + if ($null -eq $commandInfo) { return $this.InvocationInfo.InvocationName } if ($commandInfo.Name -ne """") { return $commandInfo.Name } return $this.FunctionName"), null)); td165.Members.Add("Location", @@ -1356,7 +1356,7 @@ public static IEnumerable Get() trap { } $private:dacls = """"; $private:first = $true - $private:sd.DiscretionaryAcl | % { + $private:sd.DiscretionaryAcl | ForEach-Object { trap { } if ($private:first) { @@ -1376,10 +1376,10 @@ public static IEnumerable Get() var td167 = new TypeData(@"Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PingStatus", true); td167.Members.Add("IPV4Address", new ScriptPropertyData(@"IPV4Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | ?{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | select -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); td167.Members.Add("IPV6Address", new ScriptPropertyData(@"IPV6Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | ?{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | select -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); yield return td167; var td168 = new TypeData(@"Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Process", true); diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index f8d7c03f1b0..56c2d6ee856 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1428,7 +1428,7 @@ internal static Encoding GetEncodingFromEnum(FileSystemCmdletProviderEncoding en return result; } // GetEncodingFromEnum - // [System.Text.Encoding]::GetEncodings() | ? { $_.GetEncoding().GetPreamble() } | + // [System.Text.Encoding]::GetEncodings() | Where-Object { $_.GetEncoding().GetPreamble() } | // Add-Member ScriptProperty Preamble { $this.GetEncoding().GetPreamble() -join "-" } -PassThru | // Format-Table -Auto internal static Dictionary encodingMap = diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index d8338324ba9..28e6632b902 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -3494,7 +3494,7 @@ private void EnableRunningWorkflowJobsForStepping() using (PowerShell ps = PowerShell.Create()) { ps.Commands.Clear(); - ps.AddScript(@"Get-Job | ? {$_.PSJobTypeName -eq 'PSWorkflowJob'}"); + ps.AddScript(@"Get-Job | Where-Object {$_.PSJobTypeName -eq 'PSWorkflowJob'}"); jobs = ps.Invoke(); } @@ -5531,7 +5531,7 @@ public static class DebuggerUtils [CmdletBinding()] param() - if ($PSWorkflowDebugger -ne $null) + if ($null -ne $PSWorkflowDebugger) { foreach ($frame in $PSWorkflowDebugger.GetCallStack()) { diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index b060fb353cf..0291ede7b1e 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -4500,7 +4500,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i try { - // IsNested is true for the icm | % { icm } scenario + // IsNested is true for the icm | ForEach-Object { icm } scenario if (!IsNested || (pool != null && pool.IsRemote)) { if (null != pool) diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 34c0828daa3..92b179492c5 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -2174,7 +2174,7 @@ private void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings // We don't postpone load assemblies, import modules from 'using' to the moment, when enclosed scriptblock is executed. // We do loading, when root of the script is compiled. // This allow us to avoid creating 10 different classes in this situation: - // 1..10 | % { class C {} } + // 1..10 | ForEach-Object { class C {} } // But it's possible that we are loading something from the codepaths that we never execute. // If Parent of rootForDefiningTypesAndUsings is not null, then we already defined all types, when Visit a parent ScriptBlock @@ -3288,7 +3288,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo // { // [cmdletbinding()] // param() - // $(gcm NoExist) > test.txt | % { $_ } ## file redirect with new temp pipe + // $(gcm NoExist) > test.txt | ForEach-Object { $_ } ## file redirect with new temp pipe // "hello" // } // before this change, running 'foo' will not write out 'hello'. diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index f8d85c16e02..d268d1beb91 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -175,7 +175,7 @@ private void VisitParameters(ReadOnlyCollection parameters) // slot in the tuple. This only matters for value types where we allow // comparisons with $null and don't try to convert the $null value to the // valuetype because the parameter has no value yet. For example: - // & { param([System.Reflection.MemberTypes]$m) ($m -eq $null) } + // & { param([System.Reflection.MemberTypes]$m) ($null -eq $m) } object unused; if (!Compiler.TryGetDefaultParameterValue(analysisDetails.Type, out unused)) { diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index da756953fea..9e572793ae0 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -5242,7 +5242,7 @@ public virtual ExpressionAst GetPureExpression() } /// - /// The ast that represents a PowerShell pipeline, e.g. gci -re . *.cs | select-string Foo or 65..90 | % { [char]$_ }. + /// The ast that represents a PowerShell pipeline, e.g. gci -re . *.cs | select-string Foo or 65..90 | ForEach-Object { [char]$_ }. /// A pipeline must have at least 1 command. The first command may be an expression or a command invocation. /// public class PipelineAst : PipelineBaseAst diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 63686740cb0..eadd383af30 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -3006,7 +3006,7 @@ private void HandleOutputReady(object sender, EventArgs eventArgs) dataObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, reader.ComputerName)); dataObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, reader.RunspaceId)); // PSShowComputerName is present for all the objects (from remoting)..this is to allow PSComputerName to be selected. - // Ex: Invoke-Command localhost,blah { gps } | select PSComputerName should work. + // Ex: Invoke-Command localhost,blah { gps } | Select-Object PSComputerName should work. if (dataObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null) { PSNoteProperty showComputerNameNP = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, !_hideComputerName); diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index a342219a854..6d60bf2b6cf 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -85,7 +85,7 @@ function Register-PSSessionConfiguration # See if it has 'Disable Network Access' $sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$sddl $disableNetworkExists = $false - $sd.DiscretionaryAcl | % {{ + $sd.DiscretionaryAcl | ForEach-Object {{ if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $networkSID) -and ($_.AccessMask -eq 268435456)) {{ $disableNetworkExists = $true @@ -170,7 +170,7 @@ function Register-PSSessionConfiguration $sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$curSDDL $haveDisableACE = $false $securityIdentifierToPurge = $null - $sd.DiscretionaryAcl | % {{ + $sd.DiscretionaryAcl | ForEach-Object {{ if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $networkSID) -and ($_.AccessMask -eq 268435456)) {{ $haveDisableACE = $true @@ -256,7 +256,7 @@ function Register-PSSessionConfiguration }} }} -if ($args[14] -eq $null) +if ($null -eq $args[14]) {{ Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] }} @@ -2466,7 +2466,7 @@ function Unregister-PSSessionConfiguration process {{ $shellsFound = 0 - Get-ChildItem 'WSMan:\localhost\Plugin\' -Force:$force | ? {{ $_.Name -like ""$filter"" }} | % {{ + Get-ChildItem 'WSMan:\localhost\Plugin\' -Force:$force | Where-Object {{ $_.Name -like ""$filter"" }} | ForEach-Object {{ $pluginFileNamePath = join-path ""$($_.pspath)"" 'FileName' if (!(test-path ""$pluginFileNamePath"")) {{ @@ -2484,9 +2484,9 @@ function Unregister-PSSessionConfiguration $shouldProcessTargetString = $targetTemplate -f $_.Name $DISCConfigFilePath = [System.IO.Path]::Combine($_.PSPath, ""InitializationParameters"") - $DISCConfigFile = get-childitem -literalpath ""$DISCConfigFilePath"" | ? {{$_.Name -like ""configFilePath""}} + $DISCConfigFile = get-childitem -literalpath ""$DISCConfigFilePath"" | Where-Object {{$_.Name -like ""configFilePath""}} - if($DISCConfigFile -ne $null) + if($null -ne $DISCConfigFile) {{ if(test-path -LiteralPath ""$($DISCConfigFile.Value)"") {{ remove-item -literalpath ""$($DISCConfigFile.Value)"" -recurse -force -confirm:$false @@ -2507,7 +2507,7 @@ function Unregister-PSSessionConfiguration }} # end of Process block }} -if ($args[7] -eq $null) +if ($null -eq $args[7]) {{ Unregister-PSSessionConfiguration -filter $args[0] -whatif:$args[1] -confirm:$args[2] -action $args[3] -targetTemplate $args[4] -shellNotErrMsgFormat $args[5] -force $args[6] }} @@ -2707,12 +2707,12 @@ function ExtractPluginProperties([string]$pluginDir, $objectToWriteTo) $serviceCore = [Reflection.Assembly]::Load(""Microsoft.Powershell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"") - if ($serviceCore -ne $null) {{ + if ($null -ne $serviceCore) {{ $ci = new-Object system.management.automation.cmdletinfo ""New-PSWorkflowExecutionOptions"", ([Microsoft.PowerShell.Commands.NewPSWorkflowExecutionOptionCommand]) $wf = [powershell]::Create(""currentrunspace"").AddCommand($ci).Invoke() - if($wf -ne $null -and $wf.Count -ne 0) {{ + if($null -ne $wf -and $wf.Count -ne 0) {{ $wf = $wf[0] foreach ($o in $wf.GetType().GetProperties()) {{ @@ -2770,7 +2770,7 @@ function ExtractPluginProperties([string]$pluginDir, $objectToWriteTo) $args[0] | foreach {{ $shellsFound = 0; $filter = $_ - Get-ChildItem 'WSMan:\localhost\Plugin\' -Force:$force | ? {{ $_.name -like ""$filter"" }} | foreach {{ + Get-ChildItem 'WSMan:\localhost\Plugin\' -Force:$force | Where-Object {{ $_.name -like ""$filter"" }} | foreach {{ $customPluginObject = new-object object $customPluginObject.pstypenames.Insert(0, '{0}') ExtractPluginProperties ""$($_.PSPath)"" $customPluginObject @@ -3056,11 +3056,11 @@ function Set-RunAsCredential{{ if ($isSddlSpecified) {{ $resourcesPath = Join-Path ""$pluginDir"" 'Resources' - Get-ChildItem -literalpath ""$resourcesPath"" | % {{ + Get-ChildItem -literalpath ""$resourcesPath"" | ForEach-Object {{ $securityPath = Join-Path ""$($_.pspath)"" 'Security' if ((@(Get-ChildItem -literalpath ""$securityPath"")).count -gt 0) {{ - Get-ChildItem -literalpath ""$securityPath"" | % {{ + Get-ChildItem -literalpath ""$securityPath"" | ForEach-Object {{ $securityIDPath = ""$($_.pspath)"" remove-item -path ""$securityIDPath"" -recurse -force }} #end of securityPath @@ -3096,11 +3096,11 @@ function Set-RunAsCredential{{ $networkSID = new-object system.security.principal.securityidentifier $evst,$null $resPath = Join-Path ""$pluginDir"" 'Resources' - Get-ChildItem -literalpath ""$resPath"" | % {{ + Get-ChildItem -literalpath ""$resPath"" | ForEach-Object {{ $securityPath = Join-Path ""$($_.pspath)"" 'Security' if ((@(Get-ChildItem -literalpath ""$securityPath"")).count -gt 0) {{ - Get-ChildItem -literalpath ""$securityPath"" | % {{ + Get-ChildItem -literalpath ""$securityPath"" | ForEach-Object {{ $sddlPath = Join-Path ""$($_.pspath)"" 'Sddl' $curSDDL = (get-item -path $sddlPath).value $sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$curSDDL @@ -3108,7 +3108,7 @@ function Set-RunAsCredential{{ $disableNetworkExists = $false $securityIdentifierToPurge = $null - $sd.DiscretionaryAcl | % {{ + $sd.DiscretionaryAcl | ForEach-Object {{ if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $networkSID) -and ($_.AccessMask -eq 268435456)) {{ $disableNetworkExists = $true @@ -4063,7 +4063,7 @@ function Test-WinRMQuickConfigNeeded }} # check if a winrm listener is present - elseif (!(Test-Path WSMan:\localhost\Listener) -or ((Get-ChildItem WSMan:\localhost\Listener) -eq $null)){{ + elseif (!(Test-Path WSMan:\localhost\Listener) -or ($null -eq (Get-ChildItem WSMan:\localhost\Listener))){{ $winrmQuickConfigNeeded = $true }} @@ -4166,7 +4166,7 @@ function Enable-PSSessionConfiguration process {{ - Get-PSSessionConfiguration $name -Force:$Force | % {{ + Get-PSSessionConfiguration $name -Force:$Force | ForEach-Object {{ if ($_.Enabled -eq $false -and ($force -or $pscmdlet.ShouldProcess($setEnabledTarget, $setEnabledAction))) {{ @@ -4190,7 +4190,7 @@ function Enable-PSSessionConfiguration $everyOneSID = new-object system.security.principal.securityidentifier $evst,$null $sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$sddlTemp - $sd.DiscretionaryAcl | % {{ + $sd.DiscretionaryAcl | ForEach-Object {{ if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $everyOneSID)) {{ $securityIdentifierToPurge = $_.securityidentifier @@ -4510,7 +4510,7 @@ function Disable-PSSessionConfiguration process {{ - Get-PSSessionConfiguration $name -Force:$Force | % {{ + Get-PSSessionConfiguration $name -Force:$Force | ForEach-Object {{ if ($_.Enabled -and ($force -or $pscmdlet.ShouldProcess($setEnabledTarget, $setEnabledAction))) {{ @@ -4808,7 +4808,7 @@ function Enable-PSRemoting }} # remove the 'network deny all' tag - Get-PSSessionConfiguration -Force:$Force | % {{ + Get-PSSessionConfiguration -Force:$Force | ForEach-Object {{ $sddl = $null if ($_.psobject.members[""SecurityDescriptorSddl""]) {{ @@ -4823,7 +4823,7 @@ function Enable-PSRemoting $securityIdentifierToPurge = $null $sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$sddl - $sd.DiscretionaryAcl | % {{ + $sd.DiscretionaryAcl | ForEach-Object {{ if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $networkSID) -and ($_.AccessMask -eq 268435456)) {{ $securityIdentifierToPurge = $_.securityidentifier @@ -5087,7 +5087,7 @@ function Disable-PSRemoting end {{ # Disable the network for all Session Configurations - Get-PSSessionConfiguration -Force:$force | % {{ + Get-PSSessionConfiguration -Force:$force | ForEach-Object {{ if ($_.Enabled) {{ @@ -5111,7 +5111,7 @@ function Disable-PSRemoting # Add disable network to the existing sddl $sd = new-object system.security.accesscontrol.commonsecuritydescriptor $false,$false,$sddl $disableNetworkExists = $false - $sd.DiscretionaryAcl | % {{ + $sd.DiscretionaryAcl | ForEach-Object {{ if (($_.acequalifier -eq ""accessdenied"") -and ($_.securityidentifier -match $networkSID) -and ($_.AccessMask -eq 268435456)) {{ $disableNetworkExists = $true diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 4850a064cce..db89756f366 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -49,7 +49,7 @@ namespace Microsoft.PowerShell.Commands /// /// Execute a command in a set of remote machines by specifying the /// command and the list of machines - /// $servers = 1..10 | %{"Server${_}"} + /// $servers = 1..10 | ForEach-Object{"Server${_}"} /// invoke-command -command {get-process} -computername $servers /// /// Create a new runspace and use it to execute a command on a remote machine @@ -65,7 +65,7 @@ namespace Microsoft.PowerShell.Commands /// Create a collection of runspaces and use it to execute a command on a set /// of remote machines /// - /// $serveruris = 1..8 | %{"http://Server${_}/"} + /// $serveruris = 1..8 | ForEach-Object{"http://Server${_}/"} /// $runspaces = New-PSSession -URI $serveruris /// invoke-command -command {get-process} -Session $runspaces /// @@ -948,7 +948,7 @@ protected override void BeginProcessing() // Win8 Bug:898011 - We are restricting remote steppable pipeline because // of this bug in Win8 where hangs can occur during data piping. // We are reverting to Win7 behavior for {icm | icm} and {proxycommand | proxycommand} - // cases. For ICM | % ICM case, we are using remote steppable pipeline. + // cases. For ICM | ForEach-Object ICM case, we are using remote steppable pipeline. if ((MyInvocation != null) && (MyInvocation.PipelinePosition == 1) && (MyInvocation.ExpectingInput == false)) { PSPrimitiveDictionary table = (object)runspaceInfo.ApplicationPrivateData[PSVersionInfo.PSVersionTableName] as PSPrimitiveDictionary; @@ -958,7 +958,7 @@ protected override void BeginProcessing() if (version != null) { - // In order to support foreach remoting properly ( icm | % { icm } ), the server must + // In order to support foreach remoting properly ( icm | ForEach-Object { icm } ), the server must // be using protocol version 2.2. Otherwise, we skip this and assume the old behavior. if (version >= RemotingConstants.ProtocolVersionWin8RTM) { diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index 94164c5015f..813d1b6a253 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -39,7 +39,7 @@ namespace Microsoft.PowerShell.Commands /// /// Create a set of Runspaces using the Secure Socket Layer by specifying the URI form. /// This assumes that an shell by the name of E12 exists on the remote server. - /// $serverURIs = 1..8 | %{ "SSL://server${_}:443/E12" } + /// $serverURIs = 1..8 | ForEach-Object{ "SSL://server${_}:443/E12" } /// $rs = New-PSSession -URI $serverURIs /// /// Create a runspace by connecting to port 8081 on servers s1, s2 and s3 diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 56fe7c46194..063f7690435 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -1276,9 +1276,9 @@ internal void SendDataToClient(RemoteDataObject data, bool flush, bool rep // icm . { // $a = new-object psobject // $a.pstypenames.Insert(0, "Microsoft.PowerShell.Test.Bug491001") - // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName name -Value {( 1..50kb | % { get-random -min 97 -max 122 | % { [char]$psitem } }) -join ""} + // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName name -Value {( 1..50kb | ForEach-Object { get-random -min 97 -max 122 | ForEach-Object { [char]$psitem } }) -join ""} // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName Verbose -Value {write-progress "blah" -Completed; "Some verbose data"} - // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName zname -Value {( 1..10kb | % { get-random -min 97 -max 122 | % { [char]$psitem } }) -join ""} + // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName zname -Value {( 1..10kb | ForEach-Object { get-random -min 97 -max 122 | ForEach-Object { [char]$psitem } }) -join ""} // $a // } // 1. The value of "name" property is huge 50kb and cannot fit in one fragment (with fragment size 32kb) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 9ee81b6e390..80e2effc1a6 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -2170,7 +2170,7 @@ internal static string[] GetNamespacesForTypeResolutionState(IEnumerableThe '{0}' command in the {2}' module was imported, but because its name does not include an approved verb, it might be difficult to find. The suggested alternative verbs are "{1}". - Some imported command names contain one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + Some imported command names contain one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | Where-Object @ ` * % + = ~ - The command name '{0}' from the module '{1}' contains one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + The command name '{0}' from the module '{1}' contains one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | Where-Object @ ` * % + = ~ Creating the "{0}" module manifest file. diff --git a/test/docker/networktest/DockerRemoting.Tests.ps1 b/test/docker/networktest/DockerRemoting.Tests.ps1 index 69348bd7991..a79316b3c8d 100644 --- a/test/docker/networktest/DockerRemoting.Tests.ps1 +++ b/test/docker/networktest/DockerRemoting.Tests.ps1 @@ -66,22 +66,22 @@ Describe "Basic remoting test with docker" -tags @("Scenario","Slow"){ } It "Full powershell can get correct remote powershell core version" -pending:$pending { - $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | %{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $coreVersion } It "Full powershell can get correct remote powershell full version" -pending:$pending { - $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | %{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $fullVersion } It "Core powershell can get correct remote powershell core version" -pending:$pending { - $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | %{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $coreVersion } It "Core powershell can get correct remote powershell full version" -pending:$pending { - $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | %{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $fullVersion } } diff --git a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 index 8d5f7c7776f..352fc196012 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 @@ -566,7 +566,7 @@ Describe 'Check PS Class Assembly Test' -Tags "CI" { class C1 {} $assem = [C1].Assembly $attrs = @($assem.GetCustomAttributes($true)) - $expectedAttr = @($attrs | ? { $_ -is [System.Management.Automation.DynamicClassImplementationAssemblyAttribute] }) + $expectedAttr = @($attrs | Where-Object { $_ -is [System.Management.Automation.DynamicClassImplementationAssemblyAttribute] }) It "Expected a DynamicClassImplementationAssembly attribute" { $expectedAttr.Length | should be 1} } @@ -671,7 +671,7 @@ function test-it([EE]$ee){$ee} Describe 'Type building' -Tags "CI" { It 'should build the type only once for scriptblock' { $a = $null - 1..10 | % { + 1..10 | ForEach-Object { class C {} if ($a) { $a -eq [C] | Should Be $true @@ -682,7 +682,7 @@ Describe 'Type building' -Tags "CI" { It 'should create a new type every time scriptblock executed?' -Pending { $sb = [scriptblock]::Create('class A {static [int] $a }; [A]::new()') - 1..2 | % { + 1..2 | ForEach-Object { $a = $sb.Invoke()[0] ++$a::a | Should Be 1 ++$a::a | Should Be 2 diff --git a/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 index f3791a1bb99..3f657e78c5a 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 @@ -1,6 +1,6 @@ Describe 'PSModuleInfo.GetExportedTypeDefinitions()' -Tags "CI" { It "doesn't throw for any module" { - $discard = Get-Module -ListAvailable | % { $_.GetExportedTypeDefinitions() } + $discard = Get-Module -ListAvailable | ForEach-Object { $_.GetExportedTypeDefinitions() } $true | Should Be $true # we only verify that we didn't throw. This line contains a dummy Should to make pester happy. } } @@ -44,14 +44,14 @@ class RandomWrapper '@ It 'use different sessionStates for different modules' { - $ps = 1..2 | % { $p = [powershell]::Create().AddScript(@' + $ps = 1..2 | ForEach-Object { $p = [powershell]::Create().AddScript(@' Import-Module Random '@) $p.Invoke() > $null $p } - $res = 1..2 | % { - 0..1 | % { + $res = 1..2 | ForEach-Object { + 0..1 | ForEach-Object { $ps[$_].Commands.Clear() # The idea: instance created inside the context, in one runspace. # Method is called on instance in the different runspace, but it should know about the origin. diff --git a/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 b/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 index 4759baf7e3d..307e6b85530 100644 --- a/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 +++ b/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 @@ -18,7 +18,7 @@ Describe 'NestedModules' -Tags "CI" { } if ($NestedContents) { - $manifestParams['NestedModules'] = 1..$NestedContents.Count | % { + $manifestParams['NestedModules'] = 1..$NestedContents.Count | ForEach-Object { $null = new-item -type directory TestDrive:\$Name\Nested$_ $null = Set-Content -Path "${TestDrive}\$Name\Nested$_\Nested$_.psm1" -Value $NestedContents[$_ - 1] "Nested$_" diff --git a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 index b0ac92cec5f..a1bd1ac23c3 100644 --- a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 +++ b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 @@ -39,12 +39,12 @@ Describe "MSFT:3309783" -Tags "CI" { It "Run in another process" { # For a reliable test, we must run this in a new process because an earlier binding in this process # could mask the bug/fix. - & $powershellexe -noprofile -command "[psobject] | % FullName" | Should Be System.Management.Automation.PSObject + & $powershellexe -noprofile -command "[psobject] | ForEach-Object FullName" | Should Be System.Management.Automation.PSObject } It "Run in current process" { # For good measure, do the same thing in this process - [psobject] | % FullName | Should Be System.Management.Automation.PSObject + [psobject] | ForEach-Object FullName | Should Be System.Management.Automation.PSObject } It "Pipe objects derived from PSObject" { @@ -59,7 +59,7 @@ Describe "MSFT:3309783" -Tags "CI" { } [MyPsObj]::new("abc").psobject.ToString() | Should Be "MyObj: abc" - [MyPsObj]::new("def") | Out-String | % Trim | Should Be "MyObj: def" + [MyPsObj]::new("def") | Out-String | ForEach-Object Trim | Should Be "MyObj: def" } } diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index 58115914326..091599af880 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -114,7 +114,7 @@ $suspendErrors = $null $num=0 - $params | % { + $params | ForEach-Object { $input=@{'InputObject' = 'Test';$_='Suspend'} try { diff --git a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 index dec3cb1710d..aca3df83f59 100644 --- a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 @@ -47,9 +47,9 @@ Describe "Breakpoints set on custom FileSystem provider files should work" -Tags { popd - if ($breakpoint -ne $null) { $breakpoint | remove-psbreakpoint } + if ($null -ne $breakpoint) { $breakpoint | remove-psbreakpoint } if (Test-Path $scriptFullName) { Remove-Item $scriptFullName -Force } - if ((Get-PSDrive -Name tmpTestA1 2>$null) -ne $null) { Remove-PSDrive -Name tmpTestA1 -Force } + if ($null -ne (Get-PSDrive -Name tmpTestA1 2>$null)) { Remove-PSDrive -Name tmpTestA1 -Force } } } @@ -103,7 +103,7 @@ Describe "Tests line breakpoints on dot-sourced files" -Tags "CI" { } finally { - if ($breakpoint -ne $null) { $breakpoint | remove-psbreakpoint } + if ($null -ne $breakpoint) { $breakpoint | remove-psbreakpoint } if (Test-Path $scriptFile) { Remove-Item -Path $scriptFile -Force } } } @@ -157,8 +157,8 @@ Describe "Function calls clear debugger cache too early" -Tags "CI" { } finally { - if ($breakpoint1 -ne $null) { $breakpoint1 | remove-psbreakpoint } - if ($breakpoint2 -ne $null) { $breakpoint2 | remove-psbreakpoint } + if ($null -ne $breakpoint1) { $breakpoint1 | remove-psbreakpoint } + if ($null -ne $breakpoint2) { $breakpoint2 | remove-psbreakpoint } if (Test-Path $scriptFile) { Remove-Item $scriptFile -Force } } } @@ -204,10 +204,10 @@ Describe "Line breakpoints on commands in multi-line pipelines" -Tags "CI" { } finally { - if ($breakpoints -ne $null) { $breakpoints | remove-psbreakpoint } + if ($null -ne $breakpoints) { $breakpoints | remove-psbreakpoint } if (Test-Path $script) { - del $script -Force + Remove-Item $script -Force } } @@ -231,7 +231,7 @@ Describe "Line breakpoints on commands in multi-line pipelines" -Tags "CI" { AfterAll { if ( $IsCoreCLR ) { return } - if ($breakpoints -ne $null) { $breakpoints | Remove-PSBreakpoint } + if ($null -ne $breakpoints) { $breakpoints | Remove-PSBreakpoint } } It "Short path Breakpoint on line 1 hit count" -skip:$IsCoreCLR { @@ -257,7 +257,7 @@ Describe "Unit tests for various script breakpoints" -Tags "CI" { # param($path = $null) - if ($path -eq $null) + if ($null -eq $path) { $path = split-path $MyInvocation.InvocationName } @@ -397,14 +397,14 @@ Describe "Unit tests for various script breakpoints" -Tags "CI" { } finally { - if ($line1 -ne $null) { $line1 | Remove-PSBreakpoint } - if ($line2 -ne $null) { $line2 | Remove-PSBreakpoint } - if ($cmd1 -ne $null) { $cmd1 | Remove-PSBreakpoint } - if ($cmd2 -ne $null) { $cmd2 | Remove-PSBreakpoint } - if ($cmd3 -ne $null) { $cmd3 | Remove-PSBreakpoint } - if ($var1 -ne $null) { $var1 | Remove-PSBreakpoint } - if ($var2 -ne $null) { $var2 | Remove-PSBreakpoint } - if ($var3 -ne $null) { $var3 | Remove-PSBreakpoint } + if ($null -ne $line1) { $line1 | Remove-PSBreakpoint } + if ($null -ne $line2) { $line2 | Remove-PSBreakpoint } + if ($null -ne $cmd1) { $cmd1 | Remove-PSBreakpoint } + if ($null -ne $cmd2) { $cmd2 | Remove-PSBreakpoint } + if ($null -ne $cmd3) { $cmd3 | Remove-PSBreakpoint } + if ($null -ne $var1) { $var1 | Remove-PSBreakpoint } + if ($null -ne $var2) { $var2 | Remove-PSBreakpoint } + if ($null -ne $var3) { $var3 | Remove-PSBreakpoint } if (Test-Path $scriptFile1) { Remove-Item $scriptFile1 -Force } if (Test-Path $scriptFile2) { Remove-Item $scriptFile2 -Force } @@ -421,7 +421,7 @@ Describe "Unit tests for line breakpoints on dot-sourced files" -Tags "CI" { # param($path = $null) - if ($path -eq $null) + if ($null -eq $path) { $path = split-path $MyInvocation.InvocationName } @@ -492,9 +492,9 @@ Describe "Unit tests for line breakpoints on dot-sourced files" -Tags "CI" { } finally { - if ($breakpoint1 -ne $null) { $breakpoint1 | Remove-PSBreakpoint } - if ($breakpoint2 -ne $null) { $breakpoint2 | Remove-PSBreakpoint } - if ($breakpoint3 -ne $null) { $breakpoint3 | Remove-PSBreakpoint } + if ($null -ne $breakpoint1) { $breakpoint1 | Remove-PSBreakpoint } + if ($null -ne $breakpoint2) { $breakpoint2 | Remove-PSBreakpoint } + if ($null -ne $breakpoint3) { $breakpoint3 | Remove-PSBreakpoint } if (Test-Path $scriptFile) { Remove-Item $scriptFile -Force } } } @@ -595,10 +595,10 @@ Describe "Unit tests for line breakpoints on modules" -Tags "CI" { finally { $env:PSModulePath = $oldModulePath - if ($breakpoint1 -ne $null) { Remove-PSBreakpoint $breakpoint1 } - if ($breakpoint2 -ne $null) { Remove-PSBreakpoint $breakpoint2 } - if ($breakpoint3 -ne $null) { Remove-PSBreakpoint $breakpoint3 } - if ($breakpoint4 -ne $null) { Remove-PSBreakpoint $breakpoint4 } + if ($null -ne $breakpoint1) { Remove-PSBreakpoint $breakpoint1 } + if ($null -ne $breakpoint2) { Remove-PSBreakpoint $breakpoint2 } + if ($null -ne $breakpoint3) { Remove-PSBreakpoint $breakpoint3 } + if ($null -ne $breakpoint4) { Remove-PSBreakpoint $breakpoint4 } get-module $moduleName | remove-module if (Test-Path $moduleDirectory) { Remove-Item $moduleDirectory -r -force -ea silentlycontinue } } @@ -657,8 +657,8 @@ Describe "Sometimes line breakpoints are ignored" -Tags "CI" { } finally { - if ($bp1 -ne $null) { Remove-PSBreakpoint $bp1 } - if ($bp2 -ne $null) { Remove-PSBreakpoint $bp2 } + if ($null -ne $bp1) { Remove-PSBreakpoint $bp1 } + if ($null -ne $bp2) { Remove-PSBreakpoint $bp2 } if (Test-Path -Path $tempFileName1) { Remove-Item $tempFileName1 -force } if (Test-Path -Path $tempFileName2) { Remove-Item $tempFileName2 -force } diff --git a/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 index 4f8bc8dc275..dbadc6110f2 100644 --- a/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 @@ -1,7 +1,7 @@ $script1 = @' 'aaa'.ToString() > $null 'aa' > $null -"a" 2> $null | % { $_ } +"a" 2> $null | ForEach-Object { $_ } 'bb' > $null 'bb'.ToSTring() > $null 'bbb' @@ -15,7 +15,7 @@ $script2 = @' Describe "Breakpoints when set should be hit" -tag "CI" { BeforeAll { $path = setup -pass -f TestScript_1.ps1 -content $script1 - $bps = 1..6 | %{ set-psbreakpoint -script $path -line $_ -Action { continue } } + $bps = 1..6 | ForEach-Object{ set-psbreakpoint -script $path -line $_ -Action { continue } } } AfterAll { $bps | Remove-PSBreakPoint @@ -58,8 +58,8 @@ Describe "It should be possible to reset runspace debugging" -tag "Feature" { $rs.ResetRunspaceState() } AfterAll { - if ( $ps -ne $null ) { $ps.Dispose() } - if ( $ss -ne $null ) { $rs.Dispose() } + if ( $null -ne $ps ) { $ps.Dispose() } + if ( $null -ne $ss ) { $rs.Dispose() } } It "2 breakpoints should have been set" { $breakpoints.Count | Should be 2 diff --git a/test/powershell/Language/Scripting/Debugging/DebuggingInHost.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/DebuggingInHost.Tests.ps1 index b8b07e739b1..55301dcaf92 100644 --- a/test/powershell/Language/Scripting/Debugging/DebuggingInHost.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/DebuggingInHost.Tests.ps1 @@ -53,7 +53,7 @@ Describe "Tests Debugger GetCallStack() on runspaces when attached to a WinRM ho # Get call stack from default runspace. $script = @' $rs = Get-Runspace -Id 1 - if ($rs -eq $null) { throw 'Runspace not found' } + if ($null -eq $rs) { throw 'Runspace not found' } return $rs.Debugger.GetCallStack() '@ [powershell]$psHost = [powershell]::Create() @@ -74,9 +74,9 @@ Describe "Tests Debugger GetCallStack() on runspaces when attached to a WinRM ho # Clean up if ($host.IsRunspacePushed) { $host.PopRunspace() } - if ($psHost -ne $null) { $psHost.Dispose() } - if ($hostRS -ne $null) { $hostRS.Dispose() } - if ($ps -ne $null) { $ps.Dispose() } - if ($rs -ne $null) { $rs.Dispose() } + if ($null -ne $psHost) { $psHost.Dispose() } + if ($null -ne $hostRS) { $hostRS.Dispose() } + if ($null -ne $ps) { $ps.Dispose() } + if ($null -ne $rs) { $rs.Dispose() } } } diff --git a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 index ee3e3352bf6..52255a9c722 100644 --- a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 +++ b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 @@ -36,11 +36,11 @@ } begin { - if(($paramDictionary -ne $null) -and ($paramDictionary -is [MyTestParameter]) ) { + if(($null -ne $paramDictionary) -and ($paramDictionary -is [MyTestParameter]) ) { $paramDictionary.name } - elseif ($paramDictionary -ne $null) { - if ($paramDictionary.dp1.Value -ne $null) { + elseif ($null -ne $paramDictionaryl) { + if ($null -ne $paramDictionary.dp1.Value) { $paramDictionary.dp1.Value } else { diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 index ce4ac23fcd9..154a47151be 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 @@ -27,7 +27,7 @@ Describe "Native streams behavior with PowerShell" -Tags 'CI' { $out[0] | Should BeOfType 'System.Management.Automation.ErrorRecord' $out[0].FullyQualifiedErrorId | Should Be 'NativeCommandError' - $out | Select-Object -Skip 1 | % { + $out | Select-Object -Skip 1 | ForEach-Object { $_ | Should BeOfType 'System.Management.Automation.ErrorRecord' $_.FullyQualifiedErrorId | Should Be 'NativeCommandErrorMessage' } @@ -54,7 +54,7 @@ Describe "Native streams behavior with PowerShell" -Tags 'CI' { Describe 'piping powershell objects to finished native executable' -Tags 'CI' { It 'doesn''t throw any exceptions, when we are piping to the closed executable' { - 1..3 | % { + 1..3 | ForEach-Object { Start-Sleep -Milliseconds 100 # yeild some multi-line formatted object @{'a' = 'b'} diff --git a/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 b/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 index b4f8c1b8b32..ec21b4c00c6 100644 --- a/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 +++ b/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 @@ -54,7 +54,7 @@ It 'Test: ' -TestCases $testdata { param ( $Name, $Command, $OutVariable, $PreSet, $Expected ) - if($PreSet -ne $null) + if($null -ne $PreSet) { Set-Variable -Name $OutVariable -Value $PreSet & $Command -OutVariable +$OutVariable > $null @@ -124,7 +124,7 @@ Describe "Test ErrorVariable only" -Tags "CI" { It '' -TestCases $testdata1 { param ( $Name, $Command, $ErrorVariable, $PreSet, $Expected ) - if($PreSet -ne $null) + if($null -ne $PreSet) { Set-Variable -Name $ErrorVariable -Value $PreSet & $Command -ErrorVariable +$ErrorVariable 2> $null @@ -134,7 +134,7 @@ Describe "Test ErrorVariable only" -Tags "CI" { & $Command -ErrorVariable $ErrorVariable 2> $null } - $a = (Get-Variable -ValueOnly $ErrorVariable) | % {$_.ToString()} + $a = (Get-Variable -ValueOnly $ErrorVariable) | ForEach-Object {$_.ToString()} $a | should be $Expected } @@ -145,7 +145,7 @@ Describe "Test ErrorVariable only" -Tags "CI" { get-foo2 -errorVariable +a 2> $null $a.count | Should Be 3 - $a| % {$_.ToString()} | Should Be @('a', 'b', 'foo') + $a| ForEach-Object {$_.ToString()} | Should Be @('a', 'b', 'foo') } It 'Nested ErrorVariable' { diff --git a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 index 6f3795211f6..2fbf79f845f 100644 --- a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 @@ -506,7 +506,7 @@ } } } -'@ | % {$_.assembly} | Import-module +'@ | ForEach-Object {$_.assembly} | Import-module } Get-TestCmdlet -MyParameter @{ a = 42 } | Should Be 'hashtable' diff --git a/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 b/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 index b2919609e23..e8dfdcaba26 100644 --- a/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 +++ b/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 @@ -484,7 +484,7 @@ Describe 'get-help other tests' -Tags "CI" { } $x = get-help helpFunc11 -det - $x.Parameters.parameter | % { + $x.Parameters.parameter | ForEach-Object { It '$_.description' { $_.description[0].text | Should match "^$($_.Name)\s+help" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 index faf8773a091..483342b7033 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 @@ -154,7 +154,7 @@ Describe "Debug-job test" -tag "Feature" { # we check this via implication. # if we're debugging a job, then the debugger will have a callstack It "Debug-Job will break into debugger" -pending { - $ps.AddScript('$job = start-job { 1..300 | % { sleep 1 } }').Invoke() + $ps.AddScript('$job = start-job { 1..300 | ForEach-Object { sleep 1 } }').Invoke() $ps.Commands.Clear() $ps.Runspace.Debugger.GetCallStack() | Should BeNullOrEmpty Start-Sleep 3 diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/TestGetCommand.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/TestGetCommand.Tests.ps1 index 00058310f52..8f48d529620 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/TestGetCommand.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/TestGetCommand.Tests.ps1 @@ -137,7 +137,7 @@ break } } - if($foundParam -ne $null) + if($null -ne $foundParam) { break } diff --git a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroup.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroup.Tests.ps1 index e0b093ecd4d..33fce69b843 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroup.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroup.Tests.ps1 @@ -43,7 +43,7 @@ try { Describe "Verify Expected LocalGroup Cmdlets are present" -Tags "CI" { It "Test command presence" { - $result = Get-Command -Module Microsoft.PowerShell.LocalAccounts | % Name + $result = Get-Command -Module Microsoft.PowerShell.LocalAccounts | ForEach-Object Name $result -contains "New-LocalGroup" | Should Be $true $result -contains "Set-LocalGroup" | Should Be $true @@ -328,7 +328,7 @@ try { $result = @($outErr.Count, $outErr[0].ErrorRecord.CategoryInfo.Reason, $outOut.Name) } - if ($result -eq $null) + if ($null -eq $result) { # Force failing the test because an unexpected outcome occurred $false | Should Be $true diff --git a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 index e182a993cc5..20ccf06188b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 @@ -60,7 +60,7 @@ try { Describe "Verify Expected LocalGroupMember Cmdlets are present" -Tags "CI" { It "Test command presence" { - $result = Get-Command -Module Microsoft.PowerShell.LocalAccounts | % Name + $result = Get-Command -Module Microsoft.PowerShell.LocalAccounts | ForEach-Object Name $result -contains "Add-LocalGroupMember" | Should Be $true $result -contains "Get-LocalGroupMember" | Should Be $true @@ -430,7 +430,7 @@ try { Remove-LocalGroupMember TestGroupRemove1 -Member TestUserRemove1 $result = Get-LocalGroupMember TestGroupRemove1 - $result -eq $null | Should Be $true + $null -eq $result | Should Be $true } } @@ -520,21 +520,21 @@ try { Remove-LocalGroupMember TestGroupRemove1 -Member @("TestUserRemove1", "TestUserRemove2") $result = Get-LocalGroupMember TestGroupRemove1 - $result -eq $null | Should Be $true + $null -eq $result | Should Be $true } It "Can remove array of user SIDs from group" { Remove-LocalGroupMember TestGroupRemove1 -Member @($user1sid, $user2sid) $result = Get-LocalGroupMember TestGroupRemove1 - $result -eq $null | Should Be $true + $null -eq $result | Should Be $true } It "Can remove array of users names or SIDs from group" { Remove-LocalGroupMember TestGroupRemove1 -Member @($user1sid, "TestUserRemove2") $result = Get-LocalGroupMember TestGroupRemove1 - $result -eq $null | Should Be $true + $null -eq $result | Should Be $true } It "Can remove array of user names using pipeline" { @@ -543,7 +543,7 @@ try { @($name1, $name2) | Remove-LocalGroupMember TestGroupRemove1 $result = Get-LocalGroupMember TestGroupRemove1 - $result -eq $null | Should Be $true + $null -eq $result | Should Be $true } It "Errors on remove nonexistent user from group" { @@ -569,7 +569,7 @@ try { VerifyFailingTest $sb "PrincipalNotFound,Microsoft.PowerShell.Commands.RemoveLocalGroupMemberCommand" $result = Get-LocalGroupMember TestGroupRemove2 - $result -eq $null | Should Be $true + $null -eq $result | Should Be $true } It "Errors on remove user from nonexistent group" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 index d0bee20c426..54c43d0ecae 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 @@ -47,7 +47,7 @@ try { Describe "Verify Expected LocalUser Cmdlets are present" -Tags 'CI' { It "Test command presence" { - $result = Get-Command -Module Microsoft.PowerShell.LocalAccounts | % Name + $result = Get-Command -Module Microsoft.PowerShell.LocalAccounts | ForEach-Object Name $result -contains "New-LocalUser" | Should Be $true $result -contains "Set-LocalUser" | Should Be $true @@ -62,7 +62,7 @@ try { Describe "Verify Expected LocalUser Aliases are present" -Tags @('CI', 'RequireAdminOnWindows') { It "Test command presence" { - $result = get-alias | % { if ($_.Source -eq "Microsoft.PowerShell.LocalAccounts") {$_}} + $result = get-alias | ForEach-Object { if ($_.Source -eq "Microsoft.PowerShell.LocalAccounts") {$_}} $result.Name -contains "algm" | Should Be $true $result.Name -contains "dlu" | Should Be $true @@ -536,7 +536,7 @@ try { $localUserName = 'TestUserGetNameThatDoesntExist' $result = Get-LocalGroup $localUserName* - $result -eq $null | Should Be $true + $null -eq $result | Should Be $true } It "Returns the correct property values of a user" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 index accc23e63d4..7eecdbfa17e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 @@ -12,7 +12,7 @@ function Get-NonExistantProviderName param ( [int]$length = 8 ) do { $providerName = get-randomstring -length $length - } until ( (get-psprovider -PSProvider $providername -erroraction silentlycontinue) -eq $null ) + } until ( $null -eq (get-psprovider -PSProvider $providername -erroraction silentlycontinue) ) $providerName } @@ -22,7 +22,7 @@ function Get-NonExistantDriveName param ( [int]$length = 8 ) do { $driveName = Get-RandomString -length $length - } until ( (get-psdrive $driveName -erroraction silentlycontinue) -eq $null ) + } until ( $null -eq (get-psdrive $driveName -erroraction silentlycontinue) ) $drivename } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 index 85815393cb5..b65c3e2f624 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 @@ -15,7 +15,7 @@ Describe "Get-ChildItem" -Tags "CI" { $null = New-Item -Path $TestDrive -Name $item_c -ItemType "File" -Force $null = New-Item -Path $TestDrive -Name $item_D -ItemType "File" -Force $null = New-Item -Path $TestDrive -Name $item_E -ItemType "Directory" -Force - $null = New-Item -Path $TestDrive -Name $item_F -ItemType "File" -Force | %{$_.Attributes = "hidden"} + $null = New-Item -Path $TestDrive -Name $item_F -ItemType "File" -Force | ForEach-Object{$_.Attributes = "hidden"} } It "Should list the contents of the current folder" { @@ -76,13 +76,13 @@ Describe "Get-ChildItem" -Tags "CI" { $env:__FOOBAR = 'foo' $env:__foobar = 'bar' - $foobar = Get-Childitem env: | ? {$_.Name -eq '__foobar'} + $foobar = Get-Childitem env: | Where-Object {$_.Name -eq '__foobar'} $count = if ($IsWindows) { 1 } else { 2 } ($foobar | measure).Count | Should Be $count } catch { - Get-ChildItem env: | ? {$_.Name -eq '__foobar'} | Remove-Item -ErrorAction SilentlyContinue + Get-ChildItem env: | Where-Object {$_.Name -eq '__foobar'} | Remove-Item -ErrorAction SilentlyContinue } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 index 31bb33c4e86..4382c6095f5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ComputerInfo.Tests.ps1 @@ -15,7 +15,7 @@ function Get-ComputerInfoForTest } else { - if ( $forceRefresh -or $script:computerInfoAll -eq $null) + if ( $forceRefresh -or $null -eq $script:computerInfoAll) { $script:computerInfoAll = Get-ComputerInfo } @@ -340,7 +340,7 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild $configHash = @{} foreach ($config in $configs) { - if ($config.Index -ne $null) + if ($null -ne $config.Index) { $configHash.Add([string]$config.Index,$config) } @@ -497,7 +497,7 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild $serverLevels = @{} try { - if ($regKey -ne $null) + if ($null -ne $regKey) { $serverLevelNames = $regKey.GetValueNames() @@ -513,10 +513,10 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild } finally { - if ($regKey -ne $null) { $regKey.Dispose()} + if ($null -ne $regKey) { $regKey.Dispose()} } - if ($serverLevels -eq $null -or $serverLevels.Count -eq 0) + if ($null -eq $serverLevels -or $serverLevels.Count -eq 0) { return $null } @@ -579,7 +579,7 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild $virtualizationFirmwareEnabled = $null $vMMonitorModeExtensions = $null - if (($hypervisorPresent -ne $null) -and ($hypervisorPresent -ne $true)) + if (($null -ne $hypervisorPresent) -and ($hypervisorPresent -ne $true)) { $dataExecutionPrevention_Available = Get-CimClassPropVal Win32_OperatingSystem DataExecutionPrevention_Available @@ -610,7 +610,7 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild try { $layoutAsHex = [System.Convert]::ToUInt32($layout, 16) - if ($layoutAsHex -ne $null) + if ($null -ne $layoutAsHex) { $result = Convert-LocaleIdToLocaleName $layoutAsHex } @@ -660,11 +660,11 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild $locale = Get-CimClassPropVal Win32_OperatingSystem Locale - if ($locale -ne $null) + if ($null -ne $locale) { #$localeAsHex = $locale -as [hex] $localeAsHex = [System.Convert]::ToUInt32($locale, 16) - if ($localeAsHex -ne $null) + if ($null -ne $localeAsHex) { try @@ -679,7 +679,7 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild } } - if ($localeName -eq $null) + if ($null -eq $localeName) { try { @@ -699,7 +699,7 @@ public static extern int LCIDToLocaleName(uint localeID, System.Text.StringBuild { $osPagingFiles = @() $pageFileUsage = Get-CimClass Win32_PageFileUsage - if ($pageFileUsage -ne $null) + if ($null -ne $pageFileUsage) { foreach ($pageFileItem in $pageFileUsage) { @@ -1308,7 +1308,7 @@ try { { $instance = Get-CimInstance Win32_DeviceGuard -Namespace 'root\Microsoft\Windows\DeviceGuard' -ErrorAction Stop $ss = $instance.VirtualizationBasedSecurityStatus; - if ($ss -ne $null) + if ($null -ne $ss) { $returnValue.SmartStatus = $ss; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/PSDrive.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/PSDrive.Tests.ps1 index e51402db42e..af4180fb52a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/PSDrive.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/PSDrive.Tests.ps1 @@ -40,8 +40,8 @@ Describe "Basic Alias Provider Tests" -Tags "CI" { It "Verify 'Used' and 'Free' script properties" { $drive = Get-PSDrive -Name $psDriveName - $drive.Used -eq $null | Should Be $false - $drive.Free -eq $null | Should Be $false + $null -eq $drive.Used | Should Be $false + $null -eq $drive.Free | Should Be $false } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 index 2e8892c8745..46c1c86aead 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 @@ -18,7 +18,7 @@ Describe "Tests for -NoNewline parameter of Out-File, Add-Content and Set-Conten It "NoNewline parameter works on Add-Content" { $temp = "${TESTDRIVE}/test3.txt" $temp = New-TemporaryFile - 1..9 | %{Add-Content -Path $temp -Value $_ -Encoding 'ASCII' -NoNewline} + 1..9 | ForEach-Object{Add-Content -Path $temp -Value $_ -Encoding 'ASCII' -NoNewline} (Get-Content $temp -Encoding Byte).Count | Should Be 9 } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 index de7809a4836..58a5b7d61cd 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 @@ -12,7 +12,7 @@ Describe "Acl cmdlets are available and operate properly" -Tag CI { { $acl | Set-Acl $directory } | should not throw $newacl = get-acl $directory - $newrule = $newacl.Access | ?{ $accessrule.FileSystemRights -eq $_.FileSystemRights -and $accessrule.AccessControlType -eq $_.AccessControlType -and $accessrule.IdentityReference -eq $_.IdentityReference } + $newrule = $newacl.Access | Where-Object{ $accessrule.FileSystemRights -eq $_.FileSystemRights -and $accessrule.AccessControlType -eq $_.AccessControlType -and $accessrule.IdentityReference -eq $_.IdentityReference } $newrule |Should not benullorempty } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 index 3af66cfa394..2530da4a410 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 @@ -317,7 +317,7 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { $foundCerts = Get-ChildItem Cert:\CurrentUser -Recurse -DocumentEncryptionCert # Validate they all match the EKU - $correctMatching = $foundCerts | ? { + $correctMatching = $foundCerts | Where-Object { ($_.EnhancedKeyUsageList.Count -gt 0) -and ($_.EnhancedKeyUsageList[0].ObjectId -eq '1.3.6.1.4.1.311.80.1') } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 b/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 index 53dbb5d8ec0..e185fa18ecc 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/certificateCommon.psm1 @@ -103,8 +103,8 @@ function Install-TestCertificates $env:PSModulePath = $null $command = @" -Import-PfxCertificate $script:certLocation -CertStoreLocation cert:\CurrentUser\My | % PSPath -Import-Certificate $script:badCertLocation -CertStoreLocation Cert:\CurrentUser\My | % PSPath +Import-PfxCertificate $script:certLocation -CertStoreLocation cert:\CurrentUser\My | ForEach-Object PSPath +Import-Certificate $script:badCertLocation -CertStoreLocation Cert:\CurrentUser\My | ForEach-Object PSPath "@ $certPaths = & $fullPowerShell -NoProfile -NonInteractive -Command $command $certPaths.Count | Should Be 2 | Out-Null diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 index e323a9f9a0b..3052b04d42a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 @@ -96,7 +96,7 @@ Describe "Export-Csv DRT Unit Tests" -Tags "CI" { $results = Import-Csv $filePath $results.P2 | Should be "second" - $property = $results | Get-Member | ? { $_.MemberType -eq "NoteProperty" } | % { $_.Name } + $property = $results | Get-Member | Where-Object { $_.MemberType -eq "NoteProperty" } | ForEach-Object { $_.Name } $property | should not be P1 } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1 index 0e5e044324f..d03e9bb36bc 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1 @@ -256,9 +256,9 @@ Describe "Get-Member DRT Unit Tests" -Tags "CI" { Context "Verify Get-Member with other parameters" { It 'works with View Parameter' { $results = [xml]'some text' | Get-Member -view adapted - $results | ? Name -eq a | Should Not BeNullOrEmpty - $results | ? Name -eq CreateElement | Should Not BeNullOrEmpty - $results | ? Name -eq CreateNode | Should Not BeNullOrEmpty + $results | Where-Object Name -eq a | Should Not BeNullOrEmpty + $results | Where-Object Name -eq CreateElement | Should Not BeNullOrEmpty + $results | Where-Object Name -eq CreateNode | Should Not BeNullOrEmpty } It 'Get hidden members'{ diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 index 63ac3f1f4e2..a7aee64c39c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 @@ -26,7 +26,7 @@ # Skip the tests if we couldn't find a code sign certificate # This will happen in NanoServer and IoT - if ($cert -eq $null) + if ($null -eq $cert) { $skipTest = $true return @@ -58,9 +58,9 @@ AfterAll { if ($skipTest) { return } - if ($tempName -ne $null) { Remove-Item -Path $tempName -Force -ErrorAction SilentlyContinue } - if ($oldExecutionPolicy -ne $null) { Set-ExecutionPolicy $oldExecutionPolicy -Scope Process } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $tempName) { Remove-Item -Path $tempName -Force -ErrorAction SilentlyContinue } + if ($null -ne $oldExecutionPolicy) { Set-ExecutionPolicy $oldExecutionPolicy -Scope Process } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } # @@ -117,7 +117,7 @@ Describe "Tests Import-PSSession cmdlet works with types unavailable on the clie AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Verifies client-side unavailable enum is correctly handled" -Skip:$skipTest { @@ -129,7 +129,7 @@ Describe "Tests Import-PSSession cmdlet works with types unavailable on the clie # The enum is to-string-ed appropriately (foo -x "Value2").ToString() | Should Be "Value2" } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } } } @@ -147,7 +147,7 @@ Describe "Cmdlet help from remote session" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Verifies that get-help name for remote proxied commands matches the get-command name" -Skip:$skipTest { @@ -158,7 +158,7 @@ Describe "Cmdlet help from remote session" -tags "Feature" { $gcmOutPut | Should Be $getHelpOutPut } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } } } @@ -176,7 +176,7 @@ Describe "Import-PSSession Cmdlet error handling" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } @@ -188,7 +188,7 @@ Describe "Import-PSSession Cmdlet error handling" -tags "Feature" { $expectedError | Should Not Be NullOrEmpty $expectedError[0].ToString().Contains("BrokenAlias") | Should Be $true } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } Invoke-Command $session { Remove-Item alias:BrokenAlias } } } @@ -202,7 +202,7 @@ Describe "Import-PSSession Cmdlet error handling" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Test non-terminating error" -Skip:$skipTest { @@ -245,7 +245,7 @@ Describe "Import-PSSession Cmdlet error handling" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Verifies proxied output = proxied output 2" -Skip:$skipTest { @@ -277,7 +277,7 @@ Describe "Import-PSSession Cmdlet error handling" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Verifies WarningVariable" -Skip:$skipTest { @@ -302,13 +302,13 @@ Describe "Tests Export-PSSession" -tags "Feature" { $file = [IO.Path]::Combine([IO.Path]::GetTempPath(), [Guid]::NewGuid().ToString()) $results = Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file - $oldTimestamp = $($results | Select -First 1).LastWriteTime + $oldTimestamp = $($results | Select-Object -First 1).LastWriteTime } AfterAll { if ($skipTest) { return } - if ($file -ne $null) { Remove-Item $file -Force -Recurse -ErrorAction SilentlyContinue } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $file) { Remove-Item $file -Force -Recurse -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Verifies Export-PSSession creates a file/directory" -Skip:$skipTest { @@ -316,15 +316,15 @@ Describe "Tests Export-PSSession" -tags "Feature" { } It "Verifies Export-PSSession creates a psd1 file" -Skip:$skipTest { - ($results | ?{ $_.Name -like "*$(Split-Path -Leaf $file).psd1" }) | Should Be $true + ($results | Where-Object{ $_.Name -like "*$(Split-Path -Leaf $file).psd1" }) | Should Be $true } It "Verifies Export-PSSession creates a psm1 file" -Skip:$skipTest { - ($results | ?{ $_.Name -like "*.psm1" }) | Should Be $true + ($results | Where-Object{ $_.Name -like "*.psm1" }) | Should Be $true } It "Verifies Export-PSSession creates a ps1xml file" -Skip:$skipTest { - ($results | ?{ $_.Name -like "*.ps1xml" }) | Should Be $true + ($results | Where-Object{ $_.Name -like "*.ps1xml" }) | Should Be $true } It "Verifies that Export-PSSession fails when a module directory already exists" -Skip:$skipTest { @@ -344,7 +344,7 @@ Describe "Tests Export-PSSession" -tags "Feature" { @($newResults).Count | Should Be 4 # Verifies that Export-PSSession creates *new* files - $newResults | % { $_.LastWriteTime | Should BeGreaterThan $oldTimestamp } + $newResults | ForEach-Object { $_.LastWriteTime | Should BeGreaterThan $oldTimestamp } } Context "The module is usable when the original runspace is still around" { @@ -356,7 +356,7 @@ Describe "Tests Export-PSSession" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Verifies that proxy returns remote pid" -Skip:$skipTest { @@ -384,13 +384,13 @@ Describe "Proxy module is usable when the original runspace is no longer around" $null = Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file # Close the session to test the behavior of proxy module - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue; $session = $null } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue; $session = $null } } AfterAll { if ($skipTest) { return } - if ($file -ne $null) { Remove-Item $file -Force -Recurse -ErrorAction SilentlyContinue } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $file) { Remove-Item $file -Force -Recurse -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } ## It requires 'New-PSSession' to work with implicit credential to allow proxied command to create new session. @@ -404,7 +404,7 @@ Describe "Proxy module is usable when the original runspace is no longer around" } AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Verifies proxy should return remote pid" -Pending { @@ -417,7 +417,7 @@ Describe "Proxy module is usable when the original runspace is no longer around" It "Verifies Remove-Module removed the runspace that was automatically created" -Pending { Remove-Module $module -Force - ((Get-PSSession -InstanceId $internalSession.InstanceId -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-PSSession -InstanceId $internalSession.InstanceId -ErrorAction SilentlyContinue)) | Should Be $true } It "Verifies Runspace is closed after removing module from Export-PSSession that got initialized with an internal r-space" -Pending { @@ -434,7 +434,7 @@ Describe "Proxy module is usable when the original runspace is no longer around" } AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Verifies proxy should return remote pid" -Pending { @@ -452,7 +452,7 @@ Describe "Proxy module is usable when the original runspace is no longer around" # removing the module should remove the implicitly/magically created runspace It "Verifies Remove-Module removes automatically created runspace" -Pending { Remove-Module $module -Force - ((Get-PSSession -InstanceId $internalSession.InstanceId -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-PSSession -InstanceId $internalSession.InstanceId -ErrorAction SilentlyContinue)) | Should Be $true } It "Verifies Runspace is closed after removing module from Export-PSSession that got initialized with an internal r-space" -Pending { ($internalSession.Runspace.RunspaceStateInfo.ToString()) | Should Be "Closed" @@ -469,8 +469,8 @@ Describe "Proxy module is usable when the original runspace is no longer around" } AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } - if ($newSession -ne $null) { Remove-PSSession $newSession -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $newSession) { Remove-PSSession $newSession -ErrorAction SilentlyContinue } } It "Verifies proxy returns remote pid" -Pending { @@ -614,16 +614,16 @@ Describe "Import-PSSession with FormatAndTypes" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } - if ($formatFile -ne $null) { Remove-Item $formatFile -Force -ErrorAction SilentlyContinue } - if ($typeFile -ne $null) { Remove-Item $typeFile -Force -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $formatFile) { Remove-Item $formatFile -Force -ErrorAction SilentlyContinue } + if ($null -ne $typeFile) { Remove-Item $typeFile -Force -ErrorAction SilentlyContinue } } Context "Importing format file works" { BeforeAll { if ($skipTest) { return } - $formattingScript = { new-object System.Management.Automation.Host.Size | %{ $_.Width = 123; $_.Height = 456; $_ } | Out-String } + $formattingScript = { new-object System.Management.Automation.Host.Size | ForEach-Object{ $_.Width = 123; $_.Height = 456; $_ } | Out-String } $originalLocalFormatting = & $formattingScript # Original local and remote formatting should be equal (sanity check) @@ -641,7 +641,7 @@ Describe "Import-PSSession with FormatAndTypes" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "modified remote and imported local should be equal" -Skip:$skipTest { @@ -668,7 +668,7 @@ Describe "Import-PSSession with FormatAndTypes" -tags "Feature" { # Should get 2 deserialized S.M.A.H.Coordinates objects $results.Count | Should Be 2 # First object shouldn't have the additional ETS note property - $results[0].MyTestLabel -eq $null | Should Be $true + $null -eq $results[0].MyTestLabel | Should Be $true # Second object should have the additional ETS note property $results[1].MyTestLabel | Should Be 123 } @@ -707,7 +707,7 @@ Describe "Import-PSSession with FormatAndTypes" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Serialization works for top-level properties" -Skip:$skipTest { @@ -754,8 +754,8 @@ Describe "Import-PSSession functional tests" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Import-PSSession should return a PSModuleInfo object" -Skip:$skipTest { @@ -767,7 +767,7 @@ Describe "Import-PSSession functional tests" -tags "Feature" { } It "Helper functions should not be imported" -Skip:$skipTest { - ((Get-Item function:*PSImplicitRemoting* -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item function:*PSImplicitRemoting* -ErrorAction SilentlyContinue)) | Should Be $true } It "Calls implicit remoting proxies 'MyFunction'" -Skip:$skipTest { @@ -800,7 +800,7 @@ Describe "Import-PSSession functional tests" -tags "Feature" { # The loop below works around the fact that PSEventManager uses threadpool worker to queue event handler actions to process later. # Usage of threadpool means that it is impossible to predict when the event handler will run (this is Windows 8 Bugs: #882977). $i = 0 - while ( ($i -lt 20) -and ($null -ne (Get-Module | ? { $_.Path -eq $module.Path })) ) + while ( ($i -lt 20) -and ($null -ne (Get-Module | Where-Object { $_.Path -eq $module.Path })) ) { $i++ Start-Sleep -Milliseconds 50 @@ -808,11 +808,11 @@ Describe "Import-PSSession functional tests" -tags "Feature" { } It "Temporary module should be automatically removed after runspace is closed" -Skip:$skipTest { - ((Get-Module | ? { $_.Path -eq $module.Path }) -eq $null) | Should Be $true + ($null -eq (Get-Module | Where-Object { $_.Path -eq $module.Path })) | Should Be $true } It "Temporary psm1 file should be automatically removed after runspace is closed" -Skip:$skipTest { - ((Get-Item $module.Path -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item $module.Path -ErrorAction SilentlyContinue)) | Should Be $true } It "Event should be unregistered when the runspace is closed" -Skip:$skipTest { @@ -843,7 +843,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Binding of ValueFromPipeline should work" -Skip:$skipTest { @@ -886,7 +886,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Pipeline binding works even if it relies on type constraints" -Skip:$skipTest { @@ -927,7 +927,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Pipeline binding works even if it relies on type constraints and parameter set is ambiguous" -Skip:$skipTest { @@ -970,7 +970,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Pipeline binding works even when also binding by name" -Skip:$skipTest { @@ -1020,7 +1020,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Pipeline binding works by property name" -Skip:$skipTest { @@ -1065,7 +1065,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Positional binding works" -Skip:$skipTest { @@ -1109,7 +1109,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Positional binding works when binding an array value" -Skip:$skipTest { @@ -1167,7 +1167,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Value from remaining arguments works" -Skip:$skipTest { @@ -1232,7 +1232,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Non cmdlet-based binding works." -Skip:$skipTest { @@ -1299,7 +1299,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Initializer run on the remote server" -Skip:$skipTest { @@ -1320,7 +1320,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Importing by name/type should work" -Skip:$skipTest { @@ -1359,7 +1359,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Test warnings present with '-WarningAction Continue'" -Skip:$skipTest { @@ -1399,7 +1399,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Implicit remoting: OutVariable is not intercepted for non-cmdlet-bound functions" -Skip:$skipTest { @@ -1416,7 +1416,7 @@ Describe "Implicit remoting parameter binding" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Switch parameters work fine" -Skip:$skipTest { @@ -1504,9 +1504,9 @@ Describe "Implicit remoting on restricted ISS" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } - if ($myConfiguration -ne $null) { Unregister-PSSessionConfiguration -Name ($myConfiguration.Name) -Force -ErrorAction SilentlyContinue } - if ($sessionConfigurationDll -ne $null) { Remove-Item $sessionConfigurationDll -Force -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $myConfiguration) { Unregister-PSSessionConfiguration -Name ($myConfiguration.Name) -Force -ErrorAction SilentlyContinue } + if ($null -ne $sessionConfigurationDll) { Remove-Item $sessionConfigurationDll -Force -ErrorAction SilentlyContinue } } Context "restrictions works" { @@ -1525,7 +1525,7 @@ Describe "Implicit remoting on restricted ISS" -tags "Feature" { } AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "Import-PSSession works against the ISS-restricted runspace (Out-String)" -Skip:$skipTest { @@ -1564,7 +1564,7 @@ Describe "Implicit remoting tests" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } Context "Get-Command and work (Windows 7: #334112)" { @@ -1574,7 +1574,7 @@ Describe "Implicit remoting tests" -tags "Feature" { } AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } It "PSModuleInfo.Name shouldn't contain a psd1 extension" -Skip:$skipTest { @@ -1613,11 +1613,11 @@ Describe "Implicit remoting tests" -tags "Feature" { AfterAll { if ($skipTest) { return } $powerShell.Dispose() - if ($file -ne $null) { Remove-Item $file -Recurse -Force -ErrorAction SilentlyContinue } + if ($null -ne $file) { Remove-Item $file -Recurse -Force -ErrorAction SilentlyContinue } } It "'Completed' progress record should be present" -Skip:$skipTest { - ($powerShell.Streams.Progress | select -last 1).RecordType.ToString() | Should Be "Completed" + ($powerShell.Streams.Progress | Select-Object -last 1).RecordType.ToString() | Should Be "Completed" } } @@ -1644,7 +1644,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $result = Write-Output 123 | Write-Output $result | Should Be 123 } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } } @@ -1654,7 +1654,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $module = Import-PSSession -Session $session -CommandName attack -ErrorAction SilentlyContinue -ErrorVariable expectedError -AllowClobber $expectedError | Should Not Be NullOrEmpty } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } } @@ -1669,7 +1669,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $msg = [string]($expectedError[0]) $msg.Contains("blah") | Should Be $true } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } Invoke-Command $session { ${function:Get-Command} = $oldGetCommand } } } @@ -1685,7 +1685,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $msg = [string]($expectedError[0]) $msg.Contains("notRequested") | Should Be $true } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } Invoke-Command $session { ${function:Get-Command} = $oldGetCommand } } } @@ -1701,7 +1701,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $msg = [string]($_) $msg.Contains("Get-Command") | Should Be $true } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } Invoke-Command $session { ${function:Get-Command} = $oldGetCommand } } } @@ -1726,7 +1726,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $expectedResult | Should Be $actualResult } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } Invoke-Command $session { param($x) $env:PATH = $x; Remove-Item Alias:\myOrder, Function:\myOrder, Function:\helper -Force -ErrorAction SilentlyContinue } -ArgumentList $oldPath Remove-Item $tempDir -Force -Recurse -ErrorAction SilentlyContinue } @@ -1737,10 +1737,10 @@ Describe "Implicit remoting tests" -tags "Feature" { $module = Import-PSSession -Session $session -Name Get-Variable -Type cmdlet -Prefix My -AllowClobber (Get-MyVariable -Name pid).Value | Should Not Be $PID } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } - ((Get-Item function:Get-MyVariable -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item function:Get-MyVariable -ErrorAction SilentlyContinue)) | Should Be $true } Context "BadVerbs of functions should trigger a warning" { @@ -1761,7 +1761,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $ps.Streams.Error.Count | Should Be 0 $ps.Streams.Warning.Count | Should Not Be 0 } finally { - if ($module -ne $null) { + if ($null -ne $module) { $ps.Commands.Clear() $ps.AddCommand("Remove-Module").AddParameter("ModuleInfo", $module).AddParameter("Force", $true) > $null $ps.Invoke() > $null @@ -1779,17 +1779,17 @@ Describe "Implicit remoting tests" -tags "Feature" { $getVariablePid | Should Be $remotePid ## Get-Variable function should not be exported when importing a BadVerb-Variable function - ((Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue)) | Should Be $true ## BadVerb-Variable should be a function, not an alias (1) - ((Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue) -ne $null) | Should Be $true + ($null -ne (Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true ## BadVerb-Variable should be a function, not an alias (2) - ((Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true (BadVerb-Variable -Name pid).Value | Should Be $remotePid } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } } @@ -1801,7 +1801,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $ps.Streams.Error.Count | Should Be 0 $ps.Streams.Warning.Count | Should Be 0 } finally { - if ($module -ne $null) { + if ($null -ne $module) { $ps.Commands.Clear() $ps.AddCommand("Remove-Module").AddParameter("ModuleInfo", $module).AddParameter("Force", $true) > $null $ps.Invoke() > $null @@ -1819,17 +1819,17 @@ Describe "Implicit remoting tests" -tags "Feature" { $getVariablePid | Should Be $remotePid ## Get-Variable function should not be exported when importing a BadVerb-Variable function - ((Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue)) | Should Be $true ## BadVerb-Variable should be a function, not an alias (1) - ((Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue) -ne $null) | Should Be $true + ($null -ne (Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true ## BadVerb-Variable should be a function, not an alias (2) - ((Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true (BadVerb-Variable -Name pid).Value | Should Be $remotePid } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } } } @@ -1852,7 +1852,7 @@ Describe "Implicit remoting tests" -tags "Feature" { $ps.Streams.Error.Count | Should Be 0 $ps.Streams.Warning.Count | Should Be 0 } finally { - if ($module -ne $null) { + if ($null -ne $module) { $ps.Commands.Clear() $ps.AddCommand("Remove-Module").AddParameter("ModuleInfo", $module).AddParameter("Force", $true) > $null $ps.Invoke() > $null @@ -1870,14 +1870,14 @@ Describe "Implicit remoting tests" -tags "Feature" { $getVariablePid | Should Be $remotePid ## BadVerb-Variable should be an alias, not a function (1) - ((Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue) -eq $null) | Should Be $true + ($null -eq (Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true ## BadVerb-Variable should be an alias, not a function (2) - ((Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue) -ne $null) | Should Be $true + ($null -ne (Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true (BadVerb-Variable -Name pid).Value | Should Be $remotePid } finally { - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } } } } @@ -1918,8 +1918,8 @@ Describe "Export-PSSession function" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } - if ($tempdir -ne $null) { Remove-Item $tempdir -Force -Recurse -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $tempdir) { Remove-Item $tempdir -Force -Recurse -ErrorAction SilentlyContinue } } It "Test the module created by Export-PSSession" -Skip:$skipTest { @@ -1932,11 +1932,11 @@ Describe "Export-PSSession function" -tags "Feature" { $result = $ps.AddScript(" & $tempdir\TestBug450687.ps1").Invoke() ## The module created by Export-PSSession is imported successfully - ($result -ne $null -and $result.Count -eq 1 -and $result[0].Name -eq "Diag") | Should Be $true + ($null -ne $result -and $result.Count -eq 1 -and $result[0].Name -eq "Diag") | Should Be $true ## The command Add-BitsFile is imported successfully $c = $result[0].ExportedCommands["New-Guid"] - ($c -ne $null -and $c.CommandType -eq "Function") | Should Be $true + ($null -ne $c -and $c.CommandType -eq "Function") | Should Be $true } finally { $ps.Dispose() } @@ -1957,8 +1957,8 @@ Describe "Implicit remoting with disconnected session" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Remote session PID should be different" -Skip:$skipTest { @@ -2004,12 +2004,12 @@ Describe "Select-Object with implicit remoting" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($module -ne $null) { Remove-Module $module -Force -ErrorAction SilentlyContinue } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Select -First should work with implicit remoting" -Skip:$skipTest { - $bar = foo | select -First 2 + $bar = foo | Select-Object -First 2 $bar | Should Not Be NullOrEmpty $bar.Count | Should Be 2 $bar[0] | Should Be "a" @@ -2038,7 +2038,7 @@ Describe "Get-FormatData used in Export-PSSession should work on DL targets" -ta AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } Unregister-PSSessionConfiguration -Name $configName -Force -ErrorAction SilentlyContinue } @@ -2067,7 +2067,7 @@ Describe "GetCommand locally and remotely" -tags "Feature" { AfterAll { if ($skipTest) { return } - if ($session -ne $null) { Remove-PSSession $session -ErrorAction SilentlyContinue } + if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } } It "Verifies that the number of local cmdlet command count is the same as remote cmdlet command count." -Skip:$skipTest { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Pester.Commands.Cmdlets.Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Pester.Commands.Cmdlets.Json.Tests.ps1 index 666f5463d1f..66718e248ce 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Pester.Commands.Cmdlets.Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Pester.Commands.Cmdlets.Json.Tests.ps1 @@ -69,7 +69,7 @@ Describe "Json Tests" -Tags "Feature" { It "Convertto-Json should handle Enum based on Int64" { # Test follow-up for bug Win8: 378368 Convertto-Json problems with Enum based on Int64. - if ( ("JsonEnumTest" -as "Type") -eq $null ) { + if ( $null -eq ("JsonEnumTest" -as "Type")) { $enum1 = "TestEnum" + (get-random) $enum2 = "TestEnum" + (get-random) $enum3 = "TestEnum" + (get-random) @@ -1458,9 +1458,9 @@ Describe "Json Bug fixes" -Tags "Feature" { It "ConvertFrom-Json deserializes an array of PSObjects (in multiple lines) as a single string." { # Create an array of PSCustomObjects, and serialize it - $array = [pscustomobject]@{ objectName = "object1Name"; objectValue = "object1Value" }, - [pscustomobject]@{ objectName = "object2Name"; objectValue = "object2Value" } - + $array = [pscustomobject]@{ objectName = "object1Name"; objectValue = "object1Value" }, + [pscustomobject]@{ objectName = "object2Name"; objectValue = "object2Value" } + # Serialize the array to a text file $filePath = Join-Path $TESTDRIVE test.json $array | ConvertTo-Json | Out-File $filePath -Encoding utf8 @@ -1472,7 +1472,7 @@ Describe "Json Bug fixes" -Tags "Feature" { It "ConvertFrom-Json deserializes an array of strings (in multiple lines) as a single string." { - $result = "[1,","2,","3]" | ConvertFrom-Json + $result = "[1,","2,","3]" | ConvertFrom-Json $result.Count | Should be 3 } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 index 6ac264157a1..509f6670acd 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 @@ -34,8 +34,8 @@ Describe "Get-Runspace cmdlet tests" -Tag "CI" { It "Get-Runspace should return the new runspaces" { $result = get-runspace # if the ids don't match, we'll get null passed to should - $result.id | ?{$_ -eq $r1.id } | should be $r1.id - $result.id | ?{$_ -eq $r2.id } | should be $r2.id + $result.id | Where-Object{$_ -eq $r1.id } | should be $r1.id + $result.id | Where-Object{$_ -eq $r2.id } | should be $r2.id } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 index 7c7709eee04..70da8c0d794 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 @@ -18,7 +18,7 @@ Describe "Select-Object" -Tags "CI" { } It "Should be able to use the alias" { - { $dirObject | select } | Should Not Throw + { $dirObject | Select-Object} | Should Not Throw } It "Should have same result when using alias" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Send-MailMessage.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Send-MailMessage.Tests.ps1 index 46cf77d26d5..d6ce401f2a8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Send-MailMessage.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Send-MailMessage.Tests.ps1 @@ -48,7 +48,7 @@ Describe "Basic Send-MailMessage tests" -Tags CI { } elseif ($line.StartsWith("To: ")) { - if ($rv.To -eq $null) + if ($null -eq $rv.To) { $rv.To = @() } @@ -72,7 +72,7 @@ Describe "Basic Send-MailMessage tests" -Tags CI { continue } - if ($rv.Body -eq $null) + if ($null -eq $rv.Body) { $rv.Body = @() } @@ -116,7 +116,7 @@ Describe "Basic Send-MailMessage tests" -Tags CI { $mailStore = "/var/mail" $mailBox = Join-Path $mailStore $user $mailBoxFile = Get-Item $mailBox -ErrorAction SilentlyContinue - if ($mailBoxFile -ne $null -and $mailBoxFile.Length -gt 2) + if ($null -ne $mailBoxFile -and $mailBoxFile.Length -gt 2) { $PesterArgs["Pending"] = $true $PesterArgs["Name"] += " (pending: mailbox not empty)" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Trace-Command.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Trace-Command.Tests.ps1 index d8a0b5388d0..aa4a24790ed 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Trace-Command.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Trace-Command.Tests.ps1 @@ -61,7 +61,7 @@ Describe "Trace-Command" -tags "CI" { $log = Get-Content $logfile | Where-Object {$_ -like "*ThreadID=*"} $results = $log | ForEach-Object {$_.Split("=")[1]} - $results | % { $_ | Should Be ([threading.thread]::CurrentThread.ManagedThreadId) } + $results | ForEach-Object { $_ | Should Be ([threading.thread]::CurrentThread.ManagedThreadId) } } It "Timestamp creates logs in ascending order" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 92108dc31d2..d84f4e404a9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -1257,7 +1257,7 @@ Describe "Web cmdlets tests using the cmdlet's aliases" -Tags "CI" { } # If neither www.bing.com nor www.google.com are online, then skip the tests. - $skipTests = ($endPointToUse -eq $null) + $skipTests = ($null -eq $endPointToUse) $finalUri = $endPointToUse + "?q=how+many+feet+in+a+mile" It "Execute Invoke-WebRequest --> 'iwr -URI $finalUri'" -Skip:$skipTests { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/alias.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/alias.tests.ps1 index 5d54b7739c5..562a0c50156 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/alias.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/alias.tests.ps1 @@ -32,7 +32,7 @@ $testCases += [TestData]::new("Non filesystem provider", 'env:\alias.ps1', "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportAliasCommand") } - $testCases | % { + $testCases | ForEach-Object { It "for $($_.testName)" { @@ -46,7 +46,7 @@ $exportAliasError = $_ } - if($test.expectedError -eq $null) + if($null -eq $test.expectedError) { Test-Path -LiteralPath $test.testFile | Should Be $true } @@ -119,7 +119,7 @@ $testCases += [TestData]::new("Non filesystem provider", 'env:\alias.ps1', "NotSupported,Microsoft.PowerShell.Commands.ImportAliasCommand") } - $testCases | % { + $testCases | ForEach-Object { It "for $($_.testName)" { $test = $_ diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 index 3093780b64b..1af7b4fc41c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 @@ -51,7 +51,7 @@ Remove-Item $filePath -Force -ErrorAction SilentlyContinue } - $testData | % { + $testData | ForEach-Object { It "$($_.testName)" { $test = $_ @@ -135,7 +135,7 @@ $testData += [TestData]::new("with path as non filesystem provider", "env:\", $null, "ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ImportClixmlCommand") } - $testData | % { + $testData | ForEach-Object { It "$($_.testName)" { $test = $_ diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/command.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/command.tests.ps1 index 9f10e18eaea..912a8a552b6 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/command.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/command.tests.ps1 @@ -58,7 +58,7 @@ $log = Get-Content $logfile | Where-Object {$_ -like "*ThreadID=*"} $results = $log | ForEach-Object {$_.Split("=")[1]} - $results | % { $_ | Should Be ([threading.thread]::CurrentThread.ManagedThreadId) } + $results | ForEach-Object { $_ | Should Be ([threading.thread]::CurrentThread.ManagedThreadId) } } It "Timestamp creates logs in ascending order" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 index 5a292c276ec..70a1e16e6c3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 @@ -89,7 +89,7 @@ Describe "Object cmdlets" -Tags "CI" { It 'should return correct error for non-numeric input' { $gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ea silentlycontinue - $err | % { $_.FullyQualifiedErrorId | Should Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' } + $err | ForEach-Object { $_.FullyQualifiedErrorId | Should Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' } } It 'should have the correct count' { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/xml.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/xml.tests.ps1 index 8555ae47270..9185c3ef1b8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/xml.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/xml.tests.ps1 @@ -44,7 +44,7 @@ Pop-Location } - $testcases | % { + $testcases | ForEach-Object { $params = $_.parameters diff --git a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 index 39dbd9f04a8..9b56407e748 100644 --- a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 @@ -38,7 +38,7 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { } } } finally { - if ($ps -ne $null) { + if ($null -ne $ps) { $ps.Dispose() } } @@ -116,7 +116,7 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { $ps.addscript('Write-Host "After Dispose"').Invoke() $ps.addscript("Stop-Transcript").Invoke() } finally { - if ($ps -ne $null) { + if ($null -ne $ps) { $ps.Dispose() } } diff --git a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 index 85471e23d17..d8c6c37dd45 100644 --- a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 +++ b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 @@ -32,9 +32,9 @@ Describe "PackageManagement Acceptance Test" -Tags "Feature" { $gpp = Get-PackageProvider - $gpp | ?{ $_.name -eq "NuGet" } | should not BeNullOrEmpty + $gpp | Where-Object{ $_.name -eq "NuGet" } | should not BeNullOrEmpty - $gpp | ?{ $_.name -eq "PowerShellGet" } | should not BeNullOrEmpty + $gpp | Where-Object{ $_.name -eq "PowerShellGet" } | should not BeNullOrEmpty } diff --git a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 index a2918086490..439df6c2300 100644 --- a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 @@ -29,7 +29,7 @@ foreach ($cmdlet in $cmdletList) { # If the cmdlet is not preset in CoreCLR, skip it. - $skipTest = (Get-Command $cmdlet.TopicTitle -ea SilentlyContinue) -eq $null + $skipTest = $null -eq (Get-Command $cmdlet.TopicTitle -ea SilentlyContinue) # TopicTitle - is the cmdlet name in the csv file # HelpURI - is the expected help URI in the csv file diff --git a/test/powershell/engine/InitialSessionState.Tests.ps1 b/test/powershell/engine/InitialSessionState.Tests.ps1 index 547bbddbcfb..608bb16f3ec 100644 --- a/test/powershell/engine/InitialSessionState.Tests.ps1 +++ b/test/powershell/engine/InitialSessionState.Tests.ps1 @@ -83,8 +83,8 @@ Describe "TypeTable duplicate types in reused runspace InitialSessionState TypeT AfterAll { - if ($rs1 -ne $null) { $rs1.Dispose() } - if ($rs2 -ne $null) { $rs2.Dispose() } + if ($null -ne $rs1) { $rs1.Dispose() } + if ($null -ne $rs2) { $rs2.Dispose() } } It "Verifies that a reused InitialSessionState object created from a TypeTable object does not have duplicate types" { @@ -107,7 +107,7 @@ Describe "TypeTable duplicate types in reused runspace InitialSessionState TypeT AfterAll { - if ($rs -ne $null) { $rs.Dispose() } + if ($null -ne $rs) { $rs.Dispose() } } It "Verifies that shared TypeTable is not allowed in ISS" { diff --git a/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 b/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 index ccc5eac4452..242cdf0f665 100644 --- a/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 +++ b/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 @@ -177,7 +177,7 @@ Describe "Tests for circular references in required modules" -tags "CI" { Push-Location $moduleRootPath $moduleCount = 6 # this depth was enough to find a bug in cyclic reference detection product code; greater depth will slow tests down - $ModuleNames = 1..$moduleCount|%{"TestModule$_"} + $ModuleNames = 1..$moduleCount| ForEach-Object {"TestModule$_"} CreateTestModules $moduleRootPath $ModuleNames $AddVersion $AddGuid $AddCircularReference diff --git a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 index 7b927d2b886..75bab8a4c3b 100644 --- a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 +++ b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 @@ -233,7 +233,7 @@ Process { $result = "" - if($Parameter1 -ne $null) + if($null -ne $Parameter1) { $result += " P1" foreach ($object in $Parameter1) @@ -241,7 +241,7 @@ $result = $result + ":" + $object.GetType().Name + "," + $object } } - if($Parameter2 -ne $null) + if($null -ne $Parameter2) { $result += " P2" foreach ($object in $Parameter2) diff --git a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 index 9d5d7d8b659..7e664c937b1 100644 --- a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 +++ b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 @@ -157,12 +157,12 @@ Describe "Invoke-Command remote debugging tests" -Tags 'Feature' { } else { - if ($testDebugger -ne $null) { $testDebugger.Release() } - if ($ps -ne $null) { $ps.Dispose() } - if ($ps2 -ne $null) { $ps2.Dispose() } - if ($rs -ne $null) { $rs.Dispose() } - if ($rs2 -ne $null) { $rs2.Dispose() } - if ($remoteSession -ne $null) { Remove-PSSession $remoteSession -ErrorAction SilentlyContinue } + if ($null -ne $testDebugger) { $testDebugger.Release() } + if ($null -ne $psl) { $ps.Dispose() } + if ($null -ne $ps2) { $ps2.Dispose() } + if ($null -ne $rs) { $rs.Dispose() } + if ($null -ne $rs2) { $rs2.Dispose() } + if ($null -ne $remoteSession) { Remove-PSSession $remoteSession -ErrorAction SilentlyContinue } } } diff --git a/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 b/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 index 8ced5d266c4..d516803d6c9 100644 --- a/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 +++ b/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 @@ -49,7 +49,7 @@ Describe "Remote session configuration RoleDefintion RoleCapabilityFiles key tes catch { $psioe = [System.Management.Automation.PSInvalidOperationException] ($_.Exception).InnerException - if ($psioe -ne $null) + if ($null -ne $psioe) { $fullyQualifiedErrorId = $psioe.ErrorRecord.FullyQualifiedErrorId } @@ -72,7 +72,7 @@ Describe "Remote session configuration RoleDefintion RoleCapabilityFiles key tes catch { $psioe = [System.Management.Automation.PSInvalidOperationException] ($_.Exception).InnerException - if ($psioe -ne $null) + if ($null -ne $psioe) { $fullyQualifiedErrorId = $psioe.ErrorRecord.FullyQualifiedErrorId } @@ -99,7 +99,7 @@ Describe "Remote session configuration RoleDefintion RoleCapabilityFiles key tes } catch { - if ($_.Exception.InnerException -ne $null) + if ($null -ne $_.Exception.InnerException) { $exceptionTypeName = $_.Exception.InnerException.GetType().FullName } diff --git a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 index d3a489ae431..22e7af6107f 100644 --- a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 @@ -3,7 +3,7 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { Context "SSHConnectionInfo Class Tests" { AfterEach { - if ($rs -ne $null) { + if ($null -ne $rs) { $rs.Dispose() } } @@ -55,7 +55,7 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { catch { $expectedArgumentException = $_.Exception - if ($_.Exception.InnerException -ne $null) + if ($null -ne $_.Exception.InnerException) { $expectedArgumentException = $_.Exception.InnerException } diff --git a/test/powershell/engine/SemanticVersion.Tests.ps1 b/test/powershell/engine/SemanticVersion.Tests.ps1 index bbfcb37b7fb..75069841942 100644 --- a/test/powershell/engine/SemanticVersion.Tests.ps1 +++ b/test/powershell/engine/SemanticVersion.Tests.ps1 @@ -117,9 +117,9 @@ Describe "SemanticVersion api tests" -Tags 'CI' { $operand -eq $operand | Should Be $true $operand -ne $operand | Should Be $false $null -eq $operand | Should Be $false - $operand -eq $null | Should Be $false + $null -eq $operand | Should Be $false + $null -ne $operand | Should Be $true $null -ne $operand | Should Be $true - $operand -ne $null | Should Be $true } It "comparisons with null" { diff --git a/test/tools/CodeCoverageAutomation/Start-CodeCoverageRun.ps1 b/test/tools/CodeCoverageAutomation/Start-CodeCoverageRun.ps1 index 9c3f24722f1..7e36ddb64a6 100644 --- a/test/tools/CodeCoverageAutomation/Start-CodeCoverageRun.ps1 +++ b/test/tools/CodeCoverageAutomation/Start-CodeCoverageRun.ps1 @@ -59,7 +59,7 @@ function ConvertTo-CodeCovJson $previousFileCoverage = $totalCoverage.coverage.${fileName} ##Update the values for the lines in the file. - if($previousFileCoverage -ne $null) + if($null -ne $previousFileCoverage) { foreach($lineNumber in $fileCoverage.Keys) { diff --git a/test/tools/Modules/HelpersLanguage/HelpersLanguage.psm1 b/test/tools/Modules/HelpersLanguage/HelpersLanguage.psm1 index 814df79fe7d..5ca0ce9a480 100644 --- a/test/tools/Modules/HelpersLanguage/HelpersLanguage.psm1 +++ b/test/tools/Modules/HelpersLanguage/HelpersLanguage.psm1 @@ -131,8 +131,8 @@ function Flatten-Ast param([System.Management.Automation.Language.Ast] $ast) $ast - $ast | gm -type property | ? { ($prop = $_.Name) -ne 'Parent' } | % { - $ast.$prop | ? { $_ -is [System.Management.Automation.Language.Ast] } | % { Flatten-Ast $_ } + $ast | gm -type property | Where-Object { ($prop = $_.Name) -ne 'Parent' } | ForEach-Object { + $ast.$prop | Where-Object { $_ -is [System.Management.Automation.Language.Ast] } | ForEach-Object { Flatten-Ast $_ } } } diff --git a/test/tools/Modules/HttpListener/HttpListener.psm1 b/test/tools/Modules/HttpListener/HttpListener.psm1 index e38afff1385..0dcf17aa9b0 100644 --- a/test/tools/Modules/HttpListener/HttpListener.psm1 +++ b/test/tools/Modules/HttpListener/HttpListener.psm1 @@ -61,7 +61,7 @@ Function Start-HTTPListener { Write-Verbose "Parsing: $url" $uri = [uri]$url $queryItems = @{} - if ($uri.Query -ne $null) + if ($null -ne $uri.Query) { foreach ($segment in $uri.Query.Split("&")) { @@ -69,7 +69,7 @@ Function Start-HTTPListener { { $name = $matches["name"] $value = $matches["value"] - if ($value -ne $null) + if ($null -ne $value) { $value = [System.Web.HttpUtility]::UrlDecode($value) } @@ -158,7 +158,7 @@ Function Start-HTTPListener { $redirectType = $queryItems["type"] $multiredirect = $queryItems["multiredirect"] - if ($redirectType -eq $null) + if ($null -eq $redirectType) { # End of redirection $redirectType = 'Ok' @@ -178,7 +178,7 @@ Function Start-HTTPListener { Write-Verbose -Message "No redirection" $output = $request | ConvertTo-Json -Depth 6 } - elseif ($multiredirect -eq $null) + elseif ($null -eq $multiredirect) { Write-Verbose -Message "Standard redirection" $redirectedUrl = "${Url}?test=redirect&type=Ok" @@ -207,7 +207,7 @@ Function Start-HTTPListener { "linkheader" { $maxLinks = $queryItems["maxlinks"] - if ($maxlinks -eq $null) + if ($null -eq $maxlinks) { $maxLinks = 3 } @@ -270,7 +270,7 @@ Function Start-HTTPListener { Write-Verbose -Message "Setting ContentType to $contentType" } - if ($statusCode -ne $null) + if ($null -ne $statusCode) { $response.StatusCode = $statusCode } @@ -280,7 +280,7 @@ Function Start-HTTPListener { $response.Headers.Add($header, $outputHeader[$header]) } - if ($output -ne $null) + if ($null -ne $outputl) { $buffer = [System.Text.Encoding]::UTF8.GetBytes($output) $response.ContentLength64 = $buffer.Length diff --git a/test/tools/OpenCover/OpenCover.psm1 b/test/tools/OpenCover/OpenCover.psm1 index a19aa33b18a..470d8a99b50 100644 --- a/test/tools/OpenCover/OpenCover.psm1 +++ b/test/tools/OpenCover/OpenCover.psm1 @@ -1,7 +1,7 @@ #region privateFunctions $script:psRepoPath = [string]::Empty -if ((Get-Command -Name 'git' -ErrorAction Ignore) -ne $Null) { +if ($null -ne (Get-Command -Name 'git' -ErrorAction Ignore)) { $script:psRepoPath = git rev-parse --show-toplevel } @@ -47,8 +47,8 @@ function Get-CodeCoverageChange($r1, $r2, [string[]]$ClassName) if ( $ClassName ) { foreach ( $Class in $ClassName ) { - $c1 = $r1.Assembly.ClassCoverage | ?{$_.ClassName -eq $Class } - $c2 = $r2.Assembly.ClassCoverage | ?{$_.ClassName -eq $Class } + $c1 = $r1.Assembly.ClassCoverage | Where-Object{$_.ClassName -eq $Class } + $c2 = $r2.Assembly.ClassCoverage | Where-Object{$_.ClassName -eq $Class } $ClassCoverageChange = [pscustomobject]@{ ClassName = $Class Branch = $c2.Branch @@ -97,11 +97,11 @@ function Get-CodeCoverageChange($r1, $r2, [string[]]$ClassName) function Get-AssemblyCoverageChange($r1, $r2) { - if($r1 -eq $null -and $r2 -ne $null) + if($null -eq $r1 -and $null -ne $r2) { $r1 = @{ AssemblyName = $r2.AssemblyName ; Branch = 0 ; Sequence = 0 } } - elseif($r2 -eq $null -and $r1 -ne $null) + elseif($null -eq $r2 -and $null -ne $r1) { $r2 = @{ AssemblyName = $r1.AssemblyName ; Branch = 0 ; Sequence = 0 } } @@ -122,7 +122,7 @@ function Get-AssemblyCoverageChange($r1, $r2) function Get-CoverageData($xmlPath) { [xml]$CoverageXml = get-content -readcount 0 $xmlPath - if ( $CoverageXml.CoverageSession -eq $null ) { throw "CoverageSession data not found" } + if ( $null -eq $CoverageXml.CoverageSession ) { throw "CoverageSession data not found" } $assemblies = New-Object System.Collections.ArrayList @@ -136,7 +136,7 @@ function Get-CoverageData($xmlPath) Assembly = $assemblies } $CoverageData.PSTypeNames.Insert(0,"OpenCover.CoverageData") - Add-Member -InputObject $CoverageData -MemberType ScriptMethod -Name GetClassCoverage -Value { param ( $name ) $this.assembly.classcoverage | ?{$_.classname -match $name } } + Add-Member -InputObject $CoverageData -MemberType ScriptMethod -Name GetClassCoverage -Value { param ( $name ) $this.assembly.classcoverage | Where-Object{$_.classname -match $name } } $null = $CoverageXml ## Adding explicit garbage collection as the $CoverageXml object tends to be very large, in order of 1 GB. @@ -402,7 +402,7 @@ function Install-OpenCover ## We add ErrorAction as we do not have this module on PS v4 and below. Calling import-module will throw an error otherwise. import-module Microsoft.PowerShell.Archive -ErrorAction SilentlyContinue - if ((Get-Command Expand-Archive -ErrorAction Ignore) -ne $null) { + if ($null -ne (Get-Command Expand-Archive -ErrorAction Ignore)) { Expand-Archive -Path $tempPath -DestinationPath "$TargetDirectory/OpenCover" } else { Expand-ZipArchive -Path $tempPath -DestinationPath "$TargetDirectory/OpenCover" @@ -451,7 +451,7 @@ function Invoke-OpenCover { # see if it's somewhere else in the path $openCoverBin = (Get-Command -Name 'opencover.console' -ErrorAction Ignore).Source - if ($openCoverBin -eq $null) { + if ($null -eq $openCoverBin) { throw "$OpenCoverBin does not exist, use Install-OpenCover" } } diff --git a/tools/appveyor.psm1 b/tools/appveyor.psm1 index 852c219b7f7..dced28cc42b 100644 --- a/tools/appveyor.psm1 +++ b/tools/appveyor.psm1 @@ -342,7 +342,7 @@ function Invoke-AppVeyorTest $testResultsNonAdminFile, $testResultsAdminFile <# $testResultsFileFullCLR # Disable FullCLR Build #> - ) | % { + ) | ForEach-Object { Test-PSPesterResults -TestResultsFile $_ } @@ -363,7 +363,7 @@ function Invoke-AppVeyorAfterTest $codeCoverageArtifacts = Compress-CoverageArtifacts -CodeCoverageOutput $codeCoverageOutput Write-Host -ForegroundColor Green 'Upload CodeCoverage artifacts' - $codeCoverageArtifacts | % { Push-AppveyorArtifact $_ } + $codeCoverageArtifacts | ForEach-Object { Push-AppveyorArtifact $_ } } } From b8e0ac914b95074db54cfb0f62d1a353334e5a47 Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Sun, 9 Jul 2017 22:32:54 +0100 Subject: [PATCH 2/4] Fixed a problem in ParameterBinding.Tests.ps1 test because the null comparison is now correct and also removed unnecessary initialisation that was not needed for the test but made it difficult to know what was going. Enhanced the test. Fixed one typo in Dynamicparameters.Tests.ps1 that got introduced during the last refactoring and made 2 tests fail. --- .../Language/Scripting/Dynamicparameters.Tests.ps1 | 2 +- .../engine/ParameterBinding/ParameterBinding.Tests.ps1 | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 index 52255a9c722..7f487ee718f 100644 --- a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 +++ b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 @@ -39,7 +39,7 @@ if(($null -ne $paramDictionary) -and ($paramDictionary -is [MyTestParameter]) ) { $paramDictionary.name } - elseif ($null -ne $paramDictionaryl) { + elseif ($null -ne $paramDictionary) { if ($null -ne $paramDictionary.dp1.Value) { $paramDictionary.dp1.Value } diff --git a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 index 75bab8a4c3b..53440baa18a 100644 --- a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 +++ b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 @@ -227,8 +227,8 @@ function test-collectionbinding1 { [CmdletBinding()] param ( - [array]$Parameter1 = "", - [int[]]$Parameter2 = "" + [array]$Parameter1, + [int[]]$Parameter2 ) Process { @@ -253,8 +253,8 @@ } } - $result = test-collectionbinding1 -Parameter1 1 - $result | Should Be "P1:Int32,1" + $result = test-collectionbinding1 -Parameter1 1 -Parameter2 2 + $result | Should Be "P1:Int32,1 P2:Int32,2" } It "Verify that a dynamic parameter and an alias can't have the same name" { From f1f846bdfabe7b28ba4dfa86a5bfc15c209f61c0 Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Mon, 10 Jul 2017 07:39:07 +0100 Subject: [PATCH 3/4] Refactoring fixes as suggested at the pull request review. Mainly includes spaces after Where-Object/Select-Object, 4 lines being reverted due to accidental changes and minor test refactoring. The test refactoring idea was basically to change '$null -eq $something | Should Be $true' to '$something | Should BeNullOrEmpty' --- build.psm1 | 2 +- demos/Azure/Azure-Demo.ps1 | 2 +- .../WorkflowCore/ImportWorkflowCommand.cs | 2 +- .../Microsoft.PowerShell.ODataV4Adapter.ps1 | 2 +- .../PowerShellCore_format_ps1xml.cs | 4 +-- .../CommandCompletion/CommandCompletion.cs | 4 +-- .../engine/ProgressRecord.cs | 2 +- .../engine/Types_Ps1Xml.cs | 10 +++---- .../remoting/commands/InvokeCommandCommand.cs | 4 +-- .../remoting/commands/newrunspacecommand.cs | 2 +- .../remoting/fanin/BaseTransportManager.cs | 4 +-- .../resources/Modules.resx | 4 +-- .../networktest/DockerRemoting.Tests.ps1 | 8 +++--- .../Scripting/Debugging/Debugging.Tests.ps1 | 2 +- ...s.LocalAccounts.LocalGroupMember.Tests.ps1 | 12 ++++----- ....Cmdlets.LocalAccounts.LocalUser.Tests.ps1 | 2 +- .../Get-ChildItem.Tests.ps1 | 2 +- ...mands.Cmdlets.NoNewlineParameter.Tests.ps1 | 2 +- .../AclCmdlets.Tests.ps1 | 2 +- .../Get-Alias.Tests.ps1 | 4 +-- .../Implicit.Remoting.Tests.ps1 | 26 +++++++++---------- .../RunspaceCmdlets.Tests.ps1 | 4 +-- .../Select-Object.Tests.ps1 | 2 +- .../PackageManagement.Tests.ps1 | 4 +-- .../engine/Help/UpdatableHelpSystem.Tests.ps1 | 2 +- test/tools/OpenCover/OpenCover.psm1 | 6 ++--- 26 files changed, 60 insertions(+), 60 deletions(-) diff --git a/build.psm1 b/build.psm1 index 9f7cd59152c..c700bffe0da 100644 --- a/build.psm1 +++ b/build.psm1 @@ -880,7 +880,7 @@ function Start-PSPester { $count = ($lines | measure-object).Count if ($count -eq 0) { - Start-Sleep 1 + Start-Sleep -Seconds 1 } else { diff --git a/demos/Azure/Azure-Demo.ps1 b/demos/Azure/Azure-Demo.ps1 index fff69b2bc0d..c80c14bdb51 100644 --- a/demos/Azure/Azure-Demo.ps1 +++ b/demos/Azure/Azure-Demo.ps1 @@ -10,7 +10,7 @@ ### ### Install-Package -Name AzureRM.NetCore.Preview -Source https://www.powershellgallery.com/api/v2 -ProviderName NuGet -ExcludeVersion -Destination ### -### Ensure $env:PSMODULEPATH is updated with the location you used to install. +### Ensure $env:PSModulePath is updated with the location you used to install. Import-Module AzureRM.NetCore.Preview ### Supply your Azure Credentials diff --git a/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs b/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs index 928c358f8ff..463de1ad87b 100644 --- a/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs +++ b/src/Microsoft.PowerShell.Workflow.ServiceCore/ServiceCore/WorkflowCore/ImportWorkflowCommand.cs @@ -1843,7 +1843,7 @@ internal static string AddCommonWfParameters(bool innerfunction, string workflow throw (New-Object System.Management.Automation.ErrorRecord $newException, StartWorkflow.InvalidArgument, InvalidArgument, $finalParameterCollection) }} - if ($null -ne -not $AsJob -and $job) + if (-not $AsJob -and $null -ne $job) {{ try {{ diff --git a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 index b90f7f8aaf4..7dbfca82cbe 100644 --- a/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 +++ b/src/Modules/Windows-Full/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataV4Adapter.ps1 @@ -1495,7 +1495,7 @@ function SaveCDXMLSingletonCmdlets { $xmlWriter = SaveCDXMLHeader $xmlWriter $Uri $singletonName $singletonName $CmdletAdapter - if ($null -eq $associatedEntityType.BaseTyp -and $null -ne $associatedEntityType.BaseTypeStr -and $associatedEntityType.BaseTypeStr -ne '') + if ($null -eq $associatedEntityType.BaseType -and $null -ne $associatedEntityType.BaseTypeStr -and $associatedEntityType.BaseTypeStr -ne '') { $associatedEntitybaseType = GetBaseTypeByName $associatedEntityType.BaseTypeStr $GlobalMetadata diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 804f95975cd..67a6197549d 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -15,7 +15,7 @@ internal static IEnumerable GetFormatData() .StartEntry() .StartFrame(leftIndent: 4) .AddText(FileSystemProviderStrings.DirectoryDisplayGrouping) - .AddScriptBlockExpressionBinding(@"Split-Path -Parent $_.Path | ForEach-Object{ if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent") + .AddScriptBlockExpressionBinding(@"Split-Path -Parent $_.Path | ForEach-Object { if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent") .AddNewline() .EndFrame() .EndEntry() @@ -1193,7 +1193,7 @@ private static IEnumerable ViewsOf_ModuleInfoGrouping(Cust { yield return new FormatViewDefinition("Module", TableControl.Create() - .GroupByScriptBlock("Split-Path -Parent $_.Path | ForEach-Object{ if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent", customControl: sharedControls[0]) + .GroupByScriptBlock("Split-Path -Parent $_.Path | ForEach-Object { if([Version]::TryParse((Split-Path $_ -Leaf), [ref]$null)) { Split-Path -Parent $_} else {$_} } | Split-Path -Parent", customControl: sharedControls[0]) .AddHeader(Alignment.Left, width: 10) .AddHeader(Alignment.Left, width: 10) .AddHeader(Alignment.Left, width: 35) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 3ff457b1516..c9381bc6fc2 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -1081,14 +1081,14 @@ private static List PSv2FindMatches(PowerShellExecutio { powershell.AddScript(String.Format( CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -Relative -WarningAction SilentlyContinue | ForEach-Object{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", + "& {{ trap {{ continue }} ; resolve-path {0} -Relative -WarningAction SilentlyContinue | ForEach-Object {{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", path)); } else { powershell.AddScript(String.Format( CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -WarningAction SilentlyContinue | ForEach-Object{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", + "& {{ trap {{ continue }} ; resolve-path {0} -WarningAction SilentlyContinue | ForEach-Object {{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", path)); } diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index c35e946d272..b927bf93300 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -450,7 +450,7 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD * b = T / 9 * * Some sample values (for T=90): - * t | ForEach-Objectrem + * t | %rem * ----------- * 0 | 100.0% * 5 | 66.6% diff --git a/src/System.Management.Automation/engine/Types_Ps1Xml.cs b/src/System.Management.Automation/engine/Types_Ps1Xml.cs index c74d0d7a1f0..5bfa8d18b1b 100644 --- a/src/System.Management.Automation/engine/Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/Types_Ps1Xml.cs @@ -232,10 +232,10 @@ public static IEnumerable Get() var td24 = new TypeData(@"System.Management.ManagementObject#root\cimv2\Win32_PingStatus", true); td24.Members.Add("IPV4Address", new ScriptPropertyData(@"IPV4Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); td24.Members.Add("IPV6Address", new ScriptPropertyData(@"IPV6Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); yield return td24; var td25 = new TypeData(@"System.Management.ManagementObject#root\cimv2\Win32_Process", true); @@ -1106,7 +1106,7 @@ public static IEnumerable Get() if ($null -eq $helpObject) { return $null } if ($null -eq $helpObject.psobject.properties['relatedLinks']) { return $null } if ($null -eq $helpObject.relatedLinks.psobject.properties['navigationLink']) { return $null } - $helpUri = [string]$( $helpObject.relatedLinks.navigationLink | ForEach-Object{ if ($null -ne $_.psobject.properties['uri']) { $_.uri } } | Where-Object{ $_ } | Select-Object -first 1 ) + $helpUri = [string]$( $helpObject.relatedLinks.navigationLink | ForEach-Object { if ($null -ne $_.psobject.properties['uri']) { $_.uri } } | Where-Object{ $_ } | Select-Object -first 1 ) return $helpUri } else @@ -1376,10 +1376,10 @@ public static IEnumerable Get() var td167 = new TypeData(@"Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PingStatus", true); td167.Members.Add("IPV4Address", new ScriptPropertyData(@"IPV4Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); td167.Members.Add("IPV6Address", new ScriptPropertyData(@"IPV6Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); yield return td167; var td168 = new TypeData(@"Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Process", true); diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index db89756f366..6baec94c529 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -49,7 +49,7 @@ namespace Microsoft.PowerShell.Commands /// /// Execute a command in a set of remote machines by specifying the /// command and the list of machines - /// $servers = 1..10 | ForEach-Object{"Server${_}"} + /// $servers = 1..10 | ForEach-Object {"Server${_}"} /// invoke-command -command {get-process} -computername $servers /// /// Create a new runspace and use it to execute a command on a remote machine @@ -65,7 +65,7 @@ namespace Microsoft.PowerShell.Commands /// Create a collection of runspaces and use it to execute a command on a set /// of remote machines /// - /// $serveruris = 1..8 | ForEach-Object{"http://Server${_}/"} + /// $serveruris = 1..8 | ForEach-Object {"http://Server${_}/"} /// $runspaces = New-PSSession -URI $serveruris /// invoke-command -command {get-process} -Session $runspaces /// diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index 813d1b6a253..2fb8b96c0ff 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -39,7 +39,7 @@ namespace Microsoft.PowerShell.Commands /// /// Create a set of Runspaces using the Secure Socket Layer by specifying the URI form. /// This assumes that an shell by the name of E12 exists on the remote server. - /// $serverURIs = 1..8 | ForEach-Object{ "SSL://server${_}:443/E12" } + /// $serverURIs = 1..8 | ForEach-Object { "SSL://server${_}:443/E12" } /// $rs = New-PSSession -URI $serverURIs /// /// Create a runspace by connecting to port 8081 on servers s1, s2 and s3 diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 063f7690435..5b3d85ce2b1 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -1276,9 +1276,9 @@ internal void SendDataToClient(RemoteDataObject data, bool flush, bool rep // icm . { // $a = new-object psobject // $a.pstypenames.Insert(0, "Microsoft.PowerShell.Test.Bug491001") - // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName name -Value {( 1..50kb | ForEach-Object { get-random -min 97 -max 122 | ForEach-Object { [char]$psitem } }) -join ""} + // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName name -Value {( 1..50kb | ForEach-Object { get-random -min 97 -max 122 | ForEach-Object { [char]$psitem } }) -join ""} // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName Verbose -Value {write-progress "blah" -Completed; "Some verbose data"} - // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName zname -Value {( 1..10kb | ForEach-Object { get-random -min 97 -max 122 | ForEach-Object { [char]$psitem } }) -join ""} + // Update-TypeData -TypeName Microsoft.PowerShell.Test.Bug491001 -MemberType ScriptProperty -MemberName zname -Value {( 1..10kb | ForEach-Object { get-random -min 97 -max 122 | ForEach-Object { [char]$psitem } }) -join ""} // $a // } // 1. The value of "name" property is huge 50kb and cannot fit in one fragment (with fragment size 32kb) diff --git a/src/System.Management.Automation/resources/Modules.resx b/src/System.Management.Automation/resources/Modules.resx index 96105fe97fd..04cd9689e64 100644 --- a/src/System.Management.Automation/resources/Modules.resx +++ b/src/System.Management.Automation/resources/Modules.resx @@ -328,10 +328,10 @@ The '{0}' command in the {2}' module was imported, but because its name does not include an approved verb, it might be difficult to find. The suggested alternative verbs are "{1}". - Some imported command names contain one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | Where-Object @ ` * % + = ~ + Some imported command names contain one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ - The command name '{0}' from the module '{1}' contains one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | Where-Object @ ` * % + = ~ + The command name '{0}' from the module '{1}' contains one or more of the following restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ Creating the "{0}" module manifest file. diff --git a/test/docker/networktest/DockerRemoting.Tests.ps1 b/test/docker/networktest/DockerRemoting.Tests.ps1 index a79316b3c8d..8c8184d843b 100644 --- a/test/docker/networktest/DockerRemoting.Tests.ps1 +++ b/test/docker/networktest/DockerRemoting.Tests.ps1 @@ -66,22 +66,22 @@ Describe "Basic remoting test with docker" -tags @("Scenario","Slow"){ } It "Full powershell can get correct remote powershell core version" -pending:$pending { - $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $coreVersion } It "Full powershell can get correct remote powershell full version" -pending:$pending { - $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $fullVersion } It "Core powershell can get correct remote powershell core version" -pending:$pending { - $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $coreVersion } It "Core powershell can get correct remote powershell full version" -pending:$pending { - $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object{ `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" + $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$psversiontable.psversion.tostring() }" $result | should be $fullVersion } } diff --git a/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 index dbadc6110f2..5d883b85483 100644 --- a/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/Debugging.Tests.ps1 @@ -15,7 +15,7 @@ $script2 = @' Describe "Breakpoints when set should be hit" -tag "CI" { BeforeAll { $path = setup -pass -f TestScript_1.ps1 -content $script1 - $bps = 1..6 | ForEach-Object{ set-psbreakpoint -script $path -line $_ -Action { continue } } + $bps = 1..6 | ForEach-Object { set-psbreakpoint -script $path -line $_ -Action { continue } } } AfterAll { $bps | Remove-PSBreakPoint diff --git a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 index 20ccf06188b..a029df1fcdf 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalGroupMember.Tests.ps1 @@ -430,7 +430,7 @@ try { Remove-LocalGroupMember TestGroupRemove1 -Member TestUserRemove1 $result = Get-LocalGroupMember TestGroupRemove1 - $null -eq $result | Should Be $true + $result | Should BeNullOrEmpty } } @@ -520,21 +520,21 @@ try { Remove-LocalGroupMember TestGroupRemove1 -Member @("TestUserRemove1", "TestUserRemove2") $result = Get-LocalGroupMember TestGroupRemove1 - $null -eq $result | Should Be $true + $result | Should BeNullOrEmpty } It "Can remove array of user SIDs from group" { Remove-LocalGroupMember TestGroupRemove1 -Member @($user1sid, $user2sid) $result = Get-LocalGroupMember TestGroupRemove1 - $null -eq $result | Should Be $true + $result | Should BeNullOrEmpty } It "Can remove array of users names or SIDs from group" { Remove-LocalGroupMember TestGroupRemove1 -Member @($user1sid, "TestUserRemove2") $result = Get-LocalGroupMember TestGroupRemove1 - $null -eq $result | Should Be $true + $result | Should BeNullOrEmpty } It "Can remove array of user names using pipeline" { @@ -543,7 +543,7 @@ try { @($name1, $name2) | Remove-LocalGroupMember TestGroupRemove1 $result = Get-LocalGroupMember TestGroupRemove1 - $null -eq $result | Should Be $true + $result | Should BeNullOrEmpty } It "Errors on remove nonexistent user from group" { @@ -569,7 +569,7 @@ try { VerifyFailingTest $sb "PrincipalNotFound,Microsoft.PowerShell.Commands.RemoveLocalGroupMemberCommand" $result = Get-LocalGroupMember TestGroupRemove2 - $null -eq $result | Should Be $true + $result | Should BeNullOrEmpty } It "Errors on remove user from nonexistent group" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 index 54c43d0ecae..80104505de2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.LocalAccounts/Pester.Command.Cmdlets.LocalAccounts.LocalUser.Tests.ps1 @@ -536,7 +536,7 @@ try { $localUserName = 'TestUserGetNameThatDoesntExist' $result = Get-LocalGroup $localUserName* - $null -eq $result | Should Be $true + $result | Should BeNullOrEmpty } It "Returns the correct property values of a user" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 index b65c3e2f624..043b9c4c6f9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-ChildItem.Tests.ps1 @@ -15,7 +15,7 @@ Describe "Get-ChildItem" -Tags "CI" { $null = New-Item -Path $TestDrive -Name $item_c -ItemType "File" -Force $null = New-Item -Path $TestDrive -Name $item_D -ItemType "File" -Force $null = New-Item -Path $TestDrive -Name $item_E -ItemType "Directory" -Force - $null = New-Item -Path $TestDrive -Name $item_F -ItemType "File" -Force | ForEach-Object{$_.Attributes = "hidden"} + $null = New-Item -Path $TestDrive -Name $item_F -ItemType "File" -Force | ForEach-Object {$_.Attributes = "hidden"} } It "Should list the contents of the current folder" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 index 46c1c86aead..fc3231b2445 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Pester.Commands.Cmdlets.NoNewlineParameter.Tests.ps1 @@ -18,7 +18,7 @@ Describe "Tests for -NoNewline parameter of Out-File, Add-Content and Set-Conten It "NoNewline parameter works on Add-Content" { $temp = "${TESTDRIVE}/test3.txt" $temp = New-TemporaryFile - 1..9 | ForEach-Object{Add-Content -Path $temp -Value $_ -Encoding 'ASCII' -NoNewline} + 1..9 | ForEach-Object {Add-Content -Path $temp -Value $_ -Encoding 'ASCII' -NoNewline} (Get-Content $temp -Encoding Byte).Count | Should Be 9 } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 index 58a5b7d61cd..453eb0fa18d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 @@ -12,7 +12,7 @@ Describe "Acl cmdlets are available and operate properly" -Tag CI { { $acl | Set-Acl $directory } | should not throw $newacl = get-acl $directory - $newrule = $newacl.Access | Where-Object{ $accessrule.FileSystemRights -eq $_.FileSystemRights -and $accessrule.AccessControlType -eq $_.AccessControlType -and $accessrule.IdentityReference -eq $_.IdentityReference } + $newrule = $newacl.Access | Where-Object{ $accessrule.FileSystemRights -eq $_.FileSystemRights -and $accessrule.AccessControlType -eq $_.AccessControlType -and $accessrule.IdentityReference -eq $_.IdentityReference } $newrule |Should not benullorempty } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Alias.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Alias.Tests.ps1 index 0076ce50e94..87435a1badb 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Alias.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Alias.Tests.ps1 @@ -182,7 +182,7 @@ Describe "Get-Alias" -Tags "CI" { $val1 | Should Not BeNullOrEmpty $val2 | Should Not BeNullOrEmpty - $val1 | ForEach-Object{ $i++}; + $val1 | ForEach-Object { $i++}; if($i -lt 2) { $val1 | Should BeOfType "System.Management.Automation.CommandInfo" } @@ -191,7 +191,7 @@ Describe "Get-Alias" -Tags "CI" { ,$val1 | Should BeOfType "System.Array" } - $val2 | ForEach-Object{ $i++}; + $val2 | ForEach-Object { $i++}; if($i -lt 2) { $val2 | Should BeOfType "System.Management.Automation.CommandInfo" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 index a7aee64c39c..bdedc7f6d27 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 @@ -316,15 +316,15 @@ Describe "Tests Export-PSSession" -tags "Feature" { } It "Verifies Export-PSSession creates a psd1 file" -Skip:$skipTest { - ($results | Where-Object{ $_.Name -like "*$(Split-Path -Leaf $file).psd1" }) | Should Be $true + ($results | Where-Object { $_.Name -like "*$(Split-Path -Leaf $file).psd1" }) | Should Be $true } It "Verifies Export-PSSession creates a psm1 file" -Skip:$skipTest { - ($results | Where-Object{ $_.Name -like "*.psm1" }) | Should Be $true + ($results | Where-Object { $_.Name -like "*.psm1" }) | Should Be $true } It "Verifies Export-PSSession creates a ps1xml file" -Skip:$skipTest { - ($results | Where-Object{ $_.Name -like "*.ps1xml" }) | Should Be $true + ($results | Where-Object { $_.Name -like "*.ps1xml" }) | Should Be $true } It "Verifies that Export-PSSession fails when a module directory already exists" -Skip:$skipTest { @@ -623,7 +623,7 @@ Describe "Import-PSSession with FormatAndTypes" -tags "Feature" { BeforeAll { if ($skipTest) { return } - $formattingScript = { new-object System.Management.Automation.Host.Size | ForEach-Object{ $_.Width = 123; $_.Height = 456; $_ } | Out-String } + $formattingScript = { new-object System.Management.Automation.Host.Size | ForEach-Object { $_.Width = 123; $_.Height = 456; $_ } | Out-String } $originalLocalFormatting = & $formattingScript # Original local and remote formatting should be equal (sanity check) @@ -808,7 +808,7 @@ Describe "Import-PSSession functional tests" -tags "Feature" { } It "Temporary module should be automatically removed after runspace is closed" -Skip:$skipTest { - ($null -eq (Get-Module | Where-Object { $_.Path -eq $module.Path })) | Should Be $true + (Get-Module | Where-Object { $_.Path -eq $module.Path }) | Should BeNullOrEmpty } It "Temporary psm1 file should be automatically removed after runspace is closed" -Skip:$skipTest { @@ -1779,13 +1779,13 @@ Describe "Implicit remoting tests" -tags "Feature" { $getVariablePid | Should Be $remotePid ## Get-Variable function should not be exported when importing a BadVerb-Variable function - ($null -eq (Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty ## BadVerb-Variable should be a function, not an alias (1) - ($null -ne (Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty ## BadVerb-Variable should be a function, not an alias (2) - ($null -eq (Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty (BadVerb-Variable -Name pid).Value | Should Be $remotePid } finally { @@ -1819,13 +1819,13 @@ Describe "Implicit remoting tests" -tags "Feature" { $getVariablePid | Should Be $remotePid ## Get-Variable function should not be exported when importing a BadVerb-Variable function - ($null -eq (Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Function:\Get-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty ## BadVerb-Variable should be a function, not an alias (1) - ($null -ne (Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty ## BadVerb-Variable should be a function, not an alias (2) - ($null -eq (Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty (BadVerb-Variable -Name pid).Value | Should Be $remotePid } finally { @@ -1870,10 +1870,10 @@ Describe "Implicit remoting tests" -tags "Feature" { $getVariablePid | Should Be $remotePid ## BadVerb-Variable should be an alias, not a function (1) - ($null -eq (Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Function:\BadVerb-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty ## BadVerb-Variable should be an alias, not a function (2) - ($null -ne (Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue)) | Should Be $true + Get-Item Alias:\BadVerb-Variable -ErrorAction SilentlyContinue | Should BeNullOrEmpty (BadVerb-Variable -Name pid).Value | Should Be $remotePid } finally { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 index 509f6670acd..bca3ec7b76e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 @@ -34,8 +34,8 @@ Describe "Get-Runspace cmdlet tests" -Tag "CI" { It "Get-Runspace should return the new runspaces" { $result = get-runspace # if the ids don't match, we'll get null passed to should - $result.id | Where-Object{$_ -eq $r1.id } | should be $r1.id - $result.id | Where-Object{$_ -eq $r2.id } | should be $r2.id + $result.id | Where-Object{ $_ -eq $r1.id } | should be $r1.id + $result.id | Where-Object{ $_ -eq $r2.id } | should be $r2.id } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 index 70da8c0d794..7c7709eee04 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 @@ -18,7 +18,7 @@ Describe "Select-Object" -Tags "CI" { } It "Should be able to use the alias" { - { $dirObject | Select-Object} | Should Not Throw + { $dirObject | select } | Should Not Throw } It "Should have same result when using alias" { diff --git a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 index d8c6c37dd45..d59136423fb 100644 --- a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 +++ b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 @@ -32,9 +32,9 @@ Describe "PackageManagement Acceptance Test" -Tags "Feature" { $gpp = Get-PackageProvider - $gpp | Where-Object{ $_.name -eq "NuGet" } | should not BeNullOrEmpty + $gpp | Where-Object{ $_.name -eq "NuGet" } | should not BeNullOrEmpty - $gpp | Where-Object{ $_.name -eq "PowerShellGet" } | should not BeNullOrEmpty + $gpp | Where-Object{ $_.name -eq "PowerShellGet" } | should not BeNullOrEmpty } diff --git a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 index 6911d7b7bc1..d6a355a8cd6 100644 --- a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 @@ -131,7 +131,7 @@ $testCases = @{ # These are the inbox modules. $modulesInBox = @("Microsoft.PowerShell.Core" - Get-Module -ListAvailable | ForEach-Object{$_.Name} + Get-Module -ListAvailable | ForEach-Object {$_.Name} ) function GetFiles diff --git a/test/tools/OpenCover/OpenCover.psm1 b/test/tools/OpenCover/OpenCover.psm1 index 470d8a99b50..5f73b5e4c28 100644 --- a/test/tools/OpenCover/OpenCover.psm1 +++ b/test/tools/OpenCover/OpenCover.psm1 @@ -47,8 +47,8 @@ function Get-CodeCoverageChange($r1, $r2, [string[]]$ClassName) if ( $ClassName ) { foreach ( $Class in $ClassName ) { - $c1 = $r1.Assembly.ClassCoverage | Where-Object{$_.ClassName -eq $Class } - $c2 = $r2.Assembly.ClassCoverage | Where-Object{$_.ClassName -eq $Class } + $c1 = $r1.Assembly.ClassCoverage | Where-Object{ $_.ClassName -eq $Class } + $c2 = $r2.Assembly.ClassCoverage | Where-Object{ $_.ClassName -eq $Class } $ClassCoverageChange = [pscustomobject]@{ ClassName = $Class Branch = $c2.Branch @@ -136,7 +136,7 @@ function Get-CoverageData($xmlPath) Assembly = $assemblies } $CoverageData.PSTypeNames.Insert(0,"OpenCover.CoverageData") - Add-Member -InputObject $CoverageData -MemberType ScriptMethod -Name GetClassCoverage -Value { param ( $name ) $this.assembly.classcoverage | Where-Object{$_.classname -match $name } } + Add-Member -InputObject $CoverageData -MemberType ScriptMethod -Name GetClassCoverage -Value { param ( $name ) $this.assembly.classcoverage | Where-Object{ $_.classname -match $name } } $null = $CoverageXml ## Adding explicit garbage collection as the $CoverageXml object tends to be very large, in order of 1 GB. From 6001d1a09f27924634cf027e9b075b87e211331c Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Mon, 10 Jul 2017 18:51:46 +0100 Subject: [PATCH 4/4] Fix spacing around Where-Object and indentation as requested in the second pull request review --- .../engine/Types_Ps1Xml.cs | 10 +++++----- .../Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 | 2 +- .../Implicit.Remoting.Tests.ps1 | 2 +- .../RunspaceCmdlets.Tests.ps1 | 4 ++-- .../PackageManagement/PackageManagement.Tests.ps1 | 4 ++-- test/tools/OpenCover/OpenCover.psm1 | 6 +++--- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/System.Management.Automation/engine/Types_Ps1Xml.cs b/src/System.Management.Automation/engine/Types_Ps1Xml.cs index 5bfa8d18b1b..a81f019701f 100644 --- a/src/System.Management.Automation/engine/Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/Types_Ps1Xml.cs @@ -232,10 +232,10 @@ public static IEnumerable Get() var td24 = new TypeData(@"System.Management.ManagementObject#root\cimv2\Win32_PingStatus", true); td24.Members.Add("IPV4Address", new ScriptPropertyData(@"IPV4Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object { $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); td24.Members.Add("IPV6Address", new ScriptPropertyData(@"IPV6Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object { $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); yield return td24; var td25 = new TypeData(@"System.Management.ManagementObject#root\cimv2\Win32_Process", true); @@ -1106,7 +1106,7 @@ public static IEnumerable Get() if ($null -eq $helpObject) { return $null } if ($null -eq $helpObject.psobject.properties['relatedLinks']) { return $null } if ($null -eq $helpObject.relatedLinks.psobject.properties['navigationLink']) { return $null } - $helpUri = [string]$( $helpObject.relatedLinks.navigationLink | ForEach-Object { if ($null -ne $_.psobject.properties['uri']) { $_.uri } } | Where-Object{ $_ } | Select-Object -first 1 ) + $helpUri = [string]$( $helpObject.relatedLinks.navigationLink | ForEach-Object { if ($null -ne $_.psobject.properties['uri']) { $_.uri } } | Where-Object { $_ } | Select-Object -first 1 ) return $helpUri } else @@ -1376,10 +1376,10 @@ public static IEnumerable Get() var td167 = new TypeData(@"Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PingStatus", true); td167.Members.Add("IPV4Address", new ScriptPropertyData(@"IPV4Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object { $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -first 1"), null)); td167.Members.Add("IPV6Address", new ScriptPropertyData(@"IPV6Address", GetScriptBlock(@"$iphost = [System.Net.Dns]::GetHostEntry($this.address) - $iphost.AddressList | Where-Object{ $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); + $iphost.AddressList | Where-Object { $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6 } | Select-Object -first 1"), null)); yield return td167; var td168 = new TypeData(@"Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Process", true); diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 index 453eb0fa18d..eb7c5430558 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/AclCmdlets.Tests.ps1 @@ -12,7 +12,7 @@ Describe "Acl cmdlets are available and operate properly" -Tag CI { { $acl | Set-Acl $directory } | should not throw $newacl = get-acl $directory - $newrule = $newacl.Access | Where-Object{ $accessrule.FileSystemRights -eq $_.FileSystemRights -and $accessrule.AccessControlType -eq $_.AccessControlType -and $accessrule.IdentityReference -eq $_.IdentityReference } + $newrule = $newacl.Access | Where-Object { $accessrule.FileSystemRights -eq $_.FileSystemRights -and $accessrule.AccessControlType -eq $_.AccessControlType -and $accessrule.IdentityReference -eq $_.IdentityReference } $newrule |Should not benullorempty } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 index bdedc7f6d27..0111899b361 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 @@ -808,7 +808,7 @@ Describe "Import-PSSession functional tests" -tags "Feature" { } It "Temporary module should be automatically removed after runspace is closed" -Skip:$skipTest { - (Get-Module | Where-Object { $_.Path -eq $module.Path }) | Should BeNullOrEmpty + (Get-Module | Where-Object { $_.Path -eq $module.Path }) | Should BeNullOrEmpty } It "Temporary psm1 file should be automatically removed after runspace is closed" -Skip:$skipTest { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 index bca3ec7b76e..f2e7e10e2e1 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceCmdlets.Tests.ps1 @@ -34,8 +34,8 @@ Describe "Get-Runspace cmdlet tests" -Tag "CI" { It "Get-Runspace should return the new runspaces" { $result = get-runspace # if the ids don't match, we'll get null passed to should - $result.id | Where-Object{ $_ -eq $r1.id } | should be $r1.id - $result.id | Where-Object{ $_ -eq $r2.id } | should be $r2.id + $result.id | Where-Object { $_ -eq $r1.id } | should be $r1.id + $result.id | Where-Object { $_ -eq $r2.id } | should be $r2.id } } } diff --git a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 index d59136423fb..d6338dcd45b 100644 --- a/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 +++ b/test/powershell/Modules/PackageManagement/PackageManagement.Tests.ps1 @@ -32,9 +32,9 @@ Describe "PackageManagement Acceptance Test" -Tags "Feature" { $gpp = Get-PackageProvider - $gpp | Where-Object{ $_.name -eq "NuGet" } | should not BeNullOrEmpty + $gpp | Where-Object { $_.name -eq "NuGet" } | should not BeNullOrEmpty - $gpp | Where-Object{ $_.name -eq "PowerShellGet" } | should not BeNullOrEmpty + $gpp | Where-Object { $_.name -eq "PowerShellGet" } | should not BeNullOrEmpty } diff --git a/test/tools/OpenCover/OpenCover.psm1 b/test/tools/OpenCover/OpenCover.psm1 index 5f73b5e4c28..3b0e265f68e 100644 --- a/test/tools/OpenCover/OpenCover.psm1 +++ b/test/tools/OpenCover/OpenCover.psm1 @@ -47,8 +47,8 @@ function Get-CodeCoverageChange($r1, $r2, [string[]]$ClassName) if ( $ClassName ) { foreach ( $Class in $ClassName ) { - $c1 = $r1.Assembly.ClassCoverage | Where-Object{ $_.ClassName -eq $Class } - $c2 = $r2.Assembly.ClassCoverage | Where-Object{ $_.ClassName -eq $Class } + $c1 = $r1.Assembly.ClassCoverage | Where-Object { $_.ClassName -eq $Class } + $c2 = $r2.Assembly.ClassCoverage | Where-Object { $_.ClassName -eq $Class } $ClassCoverageChange = [pscustomobject]@{ ClassName = $Class Branch = $c2.Branch @@ -136,7 +136,7 @@ function Get-CoverageData($xmlPath) Assembly = $assemblies } $CoverageData.PSTypeNames.Insert(0,"OpenCover.CoverageData") - Add-Member -InputObject $CoverageData -MemberType ScriptMethod -Name GetClassCoverage -Value { param ( $name ) $this.assembly.classcoverage | Where-Object{ $_.classname -match $name } } + Add-Member -InputObject $CoverageData -MemberType ScriptMethod -Name GetClassCoverage -Value { param ( $name ) $this.assembly.classcoverage | Where-Object { $_.classname -match $name } } $null = $CoverageXml ## Adding explicit garbage collection as the $CoverageXml object tends to be very large, in order of 1 GB.