您不能只$count++
在脚本块中使用以直接增加序列号的原因是:
解决方法
一个务实但可能受到限制的解决方法是使用范围说明符$script:
- 即$script:count
- 来引用调用者的$count
变量:
$directory = 'C:\Temp'
[int] $count=71
gci $directory | sort -Property LastWriteTime |
rename-item -newname { '{0}_{1}' -f $script:count++, $_.Name } -whatif
这将起作用:
一个灵活的解决方案需要对父范围的可靠相对引用:
有两种选择:
- 由于必须调用 cmdlet,概念上清晰,但冗长且相对较慢:
(Get-Variable -Scope 1 count).Value++
gci $directory | sort -Property LastWriteTime |
rename-item -newname { '{0}_{1}' -f (Get-Variable -Scope 1 count).Value++, $_.Name } -whatif
- 有点晦涩,但更快更简洁:
([ref] $count).Value++
gci $directory | sort -Property LastWriteTime |
rename-item -newname { '{0}_{1}' -f ([ref] $count).Value++, $_.Name } -whatif
[ref] $count
实际上与Get-Variable -Scope 1 count
(假设$count
在父范围中设置了一个变量)相同
注意:理论上,您可以在任何$global:count
范围内使用初始化和递增全局变量,但鉴于全局变量即使在脚本执行结束后仍然存在,您还应该事先保存任何预先存在的值,然后再恢复它,这使得方法不切实际。$global:count