问题
I am looking for a PowerShell script which when the user clicks on from their desktop it increments a count by 1, keeps a record and when the user next clicks the script it increments from last number with formatting of 000000.
So when the user launches the script it becomes 000001, next time it'll be 000002,000010... and so on.
I have tried the below but it's not seem to be working, I am not to shell scripting. I am also not sure how to save the previous run, so next time it increments from the last number.
$counter = 0;
$counter++
回答1:
here is some example to create a file and format the numbers. Remember that leading zeros are only possible in a string. (place $counter = $counter++
at will)
$path = "D:\test\text.txt"
# Test if the file exists
if ( (Test-Path $path) ) {
# read file
$content = Get-Content $path
# convert string to int
$counter = [int]$content
}else{
$counter = 0
}
$counter++
# create a string with leading zeros
$countString = "{0:d6}" -f ($counter)
# end of your script
# save to file
$countString | Out-File $path
"{0}" -f $var
will format the variable in a stringa specific way. See here for a list how you can format the variables. Add more variables to a string like this: "{0} , {1} , {2}" -f $var1,$var2,$var3
An alternative would be to manipulate the .ps1 file itself and write the number in the scriptfile... But i wouldn't realy recommand that.
来源:https://stackoverflow.com/questions/56543348/how-to-write-a-powershell-script-which-auto-increments-a-number-by-1-every-time