【问题标题】:powershell auto increment by 001powershell 自动递增 001
【发布时间】:2019-11-26 05:17:54
【问题描述】:

这就是我想要实现的。 捕获屏幕并将其保存为 $username-$date-000.jpg 其中 000 需要在每次保存文件时自动递增。 (即 000,001,002)

我已尝试自动生成号码。 我该怎么办? 如何自动增加数字?

$Path = read-host "Screenshot will save to - [1] Desktop or [2] C:\" 
switch ($Path)
{
        1
        {
        $Path = "$($env:USERPROFILE)\Desktop\"
        }
        2
        {
        $Path = "C:\"
        }
}
$X = 0
$FileName = %{"$env:USERNAME-$(get-date -f MM-dd)-$(($X+1).ToString("000")).jpg"}
$File = "$Path\$FileName"

【问题讨论】:

标签: powershell auto-increment


【解决方案1】:

当让用户在路径之间进行选择时,我认为您需要更多 (3) 个变量来跟踪该路径的当前序列号。

另外,我建议使用Join-Path cmdlet 将字符串组合成路径。

这样的事情应该可以工作:

# we need three index variables: 
# one for the final file name, a second one for when the user chooses to save to desktop
# and a third one for when the user selects to save to the C:\ drive.
$index = $desktopIndex = $cdriveIndex = 0

# enter a loop to make sure no other choices than '1' or '2' get through
do {
    $choice = Read-Host "Screenshot will save to - [1] Desktop or [2] C:\"     #"# let the user choose the destination
    switch ($choice) {
        '1' { 
              $Path = Join-Path -Path $env:USERPROFILE -ChildPath 'Desktop'
              $index = $desktopIndex++  # increment the counter for files that go to the desktop
            }
        '2' { 
              $Path = "C:\"
              $index = $cdriveIndex++   # increment the counter for files that go to the C:\ drive
            }
    }
} until ($choice -eq '1' -or $choice -eq '2')

# construct the filename using the -f format operator
$fileName = '{0}-{1:MM-dd}-{2:000}' -f $env:USERNAME, (Get-Date), $index
$file     = Join-Path -Path $Path -ChildPath $FileName

希望有帮助

【讨论】:

    【解决方案2】:

    这可能不是理想的方法,但它仍然有效:

    for ($i = 0; $i -ne 200; $i = $i + 20) {
        $num = "0" * ( 3 - $i.ToString().Length) + $i.ToString()
        $FileName = "file-$num"
        $FileName
    }
    

    这里我只是将数字的长度作为字符串获取,并根据 3 - {数字的字符长度}在开头添加 x 个 0。

    因此,您需要添加基于 x 的 0 数量的计算:

    $num = "0" * ( 3 - $x.ToString().Length) + $x.ToString()
    

    你的文件名是:

    $FileName = %{"$env:USERNAME-$(get-date -f MM-dd)-$num.jpg"}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      相关资源
      最近更新 更多