'Why does the definition $id = 1 need?
I try to customize my profile on Windows PowerShell.
Referring a book, I wrote the following code in Microsoft.Powershell_profile.ps1.
function Prompt
{
$id = 1
$historyItem = Get-History -Count 1
if($historyItem)
{
$id = $historyItem.Id +1
}
Write-Host -ForegroundColor DarkGray "`n[$(Get-Location)]"
Write-Host -NoNewLine "PS:$id > "
$host.UI.RawUI.WindowTitle = "$(Get-Location)"
"`b"
}
I can understand most of how the code works, but not understand the $id = 1 (line 3).
Why does it need this code? $id is defined in line 7, so $id = 1 isn't need here, is it?
So, I try to execute this code and the without $id = 1 code. To me, there's no difference.
Why is $id = 1 added to this code?
Solution 1:[1]
It isn't required. The code you posted needs it because it needlessly distinguishes between "has history" and "doesn't have history". If you removed the line $id = 1 and started a new PowerShell instance you'd have an empty $id as long as the command history remains empty.
You could get the same result as the code from your question by simply running
$id = (Get-History -Count 1).Id + 1
because (Get-History -Count 1).Id evaluates to an empty result if the history is empty, which is automatically cast to 0 for the addition operation.
Solution 2:[2]
I just want to point out that it can also be written in a more terse way like this:
$id = if($historyItem) { $historyItem.Id +1 } else { 1 }
Solution 3:[3]
try like this
- declare a final int currentIndex;
- declare a constructor for your class yourclass({ this.currentIndex = 0 }); 0 is for first page
- navigate like yourclass(currentIndex: 0));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ansgar Wiechers |
| Solution 2 | General Grievance |
| Solution 3 | Taqi Tahmid Tanzil |

