$map = @{}
$arr | ForEach-Object $map[$_] = $true
CSV imports all values as strings. Convert to int before sorting:
$data | Select-Object *, @N="SalaryInt";E=[int]$_.Salary | Sort-Object SalaryInt -Desc
Better yet, cast during filtering:
Where-Object [int]$_.YearsOfExperience -ge 2
Master these cmdlets to solve problems in one or two pipelines:
| Cmdlet | Purpose |
|--------|---------|
| Sort-Object | Sort ascending/descending |
| Group-Object | Count occurrences |
| Where-Object | Filter elements |
| Select-Object | Pick first N, last N, or specific properties |
| ForEach-Object | Apply transformation |
| Measure-Object | Sum, average, min, max |
| Join-String (v6+ not available) → use -join operator | Combine strings |
| Split operator | Split strings |
| -match, -replace | Regex operations | powershell 3 cmdlets hackerrank solution
He tested on the sample:
[ERROR] Connection timeout
[INFO] User login
[ERROR] Disk timeout error
[WARNING] Low memory
[ERROR] timeout in module X
His command returned 3 (lines 1, 3, 5). The expected output was 3. It passed.
He used Where-Object with the -match operator: $map = @{}
$arr | ForEach-Object $map[$_] = $true
Where-Object $_ -match '^\[ERROR\]'
The ^ anchors to the start of the line, \[ escapes the bracket.
$sum = 0
$arr | ForEach-Object $sum += $_
The provided PowerShell function is well-structured and readable. It uses a switch statement to handle different cmdlets, which makes the code concise and easy to maintain.
The function also includes input validation and provides meaningful error messages. CSV imports all values as strings
However, there are a few areas that can be improved:
Creates new columns on-the-fly.
| Select-Object Department, @Name="AverageSalary"; Expression= Measure-Object Salary -Average).Average