每次在Powershell 5.0中运行函数时,递增一个数字
我只是想寻找一种方法,在每次运行下面的脚本时增加变量$Num。因此,脚本开始使用168,运行,然后增加到169,再次运行,等等,直到999。谢谢每次在Powershell 5.0中运行函数时,递增一个数字,powershell,loops,increment,auto-increment,Powershell,Loops,Increment,Auto Increment,我只是想寻找一种方法,在每次运行下面的脚本时增加变量$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){
$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"
}
这就是for循环的本质
$Path = "H:\ClientFiles\CHS\Processed\"
for($Num = 168; $Num -le 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
}
我不确定你想走这条路。您可以有一个维护脚本变量的模块:
# file.psm1
$script:num = 1
function myfunc {
$script:num
$script:num++
}
我正在回答这篇文章的标题。您的模块如下所示,但powershell提示符必须始终处于打开状态
$num = $script:Num = 168
function myfunc {
$Path = ".\"
$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"
}
$script:num++
}
如果每次都在同一台机器上运行,为什么不将$num值存储在注册表中,然后检查它是否大于999,并在每次脚本运行时更新它您不能在代码中执行此操作,因为脚本无法更改自己的代码您必须创建运行脚本的脚本,然后更改脚本文件。每次运行它时,变量初始化都会开始,并且在开始时总是168。但您可以将其存储在文件中并从文件中读取。是要在每次运行脚本时递增,还是在每次发现错误时仅递增一次file@Scepticalist我希望它在每次运行脚本时递增。这是因为在我的例子中只有两种结果,要么目录有文件要压缩,要么它没有,因此出现else语句。由于某种原因,这个循环不起作用。当我输入单个值时,进程按预期运行。但是有了这个for循环,脚本运行并说complete而不做任何事情,但这不会生成循环。我知道你是从哪里来的,但我不知道如何将其有效地融入我的脚本中
$num = $script:Num = 168
function myfunc {
$Path = ".\"
$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"
}
$script:num++
}