每次在Powershell 5.0中运行一个函数就增加一个数字

问题描述 投票:0回答:2

我只是在寻找一种方法,每次运行下面的脚本时,都会增加$ Num变量。因此,脚本首先使用168开始运行,然后递增到169,然后再次运行,依此类推,直到999。谢谢!

$Path = "H:\ClientFiles\CHS\Processed\"
$Num = 168
$ZipFile = "FileGroup0000000$Num.zip"
$File = "*$Num*.83*"
$n = dir -Path $Path$File | Measure

        if($n.count -gt 0){
        Remove-Item $Path$ZipFile
        Compress-Archive -Path $Path$File -DestinationPath $Path
        Rename-Item $Path'.zip' $Path'FileGroup0000000'$Num'.zip'          
        Remove-Item $Path$File            

        }    
        else {
            Write-Output "No Files to Move for FileGroup$File"
        }
powershell loops increment auto-increment
2个回答
0
投票

这本质上是for循环的目的!

$Path = "H:\ClientFiles\CHS\Processed\"
for($Num = 168; $Num -ge 999; $Num++){
    $ZipFile = "FileGroup0000000$Num.zip"
    $File = "*$Num*.83*"
    $n = dir -Path $Path$File | Measure

    if ($n.count -gt 0) {
        Remove-Item $Path$ZipFile
        Compress-Archive -Path $Path$File -DestinationPath $Path
        Rename-Item "${Path}.zip" "${Path}FileGroup0000000${Num}.zip"
        Remove-Item $Path$File

    }
    else {
        Write-Output "No Files to Move for FileGroup$File"
    }
}

for()循环声明的分解:

for($Num = 168; $Num -le 999; $Num++){
 #       ^            ^          ^
 #       |            |          | Increase by one every time
 #       |            | Keep running as long as $num is less than or equal to 999
 #       | Start with an initial value of 168
}

0
投票

不确定您是否要走这条路。您可以使用一个模块来维护脚本变量:

# file.psm1

$script:num = 1

function myfunc {
  $script:num
  $script:num++
}
import-module .\file.psm1

myfunc
1

myfunc
2

myfunc
3

remove-module file
© www.soinside.com 2019 - 2024. All rights reserved.