我有几行PowerShell代码,它们在远程目录中查找
Get-ChildItem "\\box_lab001\f$\output files" -force |
Where-Object {!$_.PsIsContainer -AND $_.lastWriteTime -lt (Get-Date).AddMinutes(-5) } |
Select-Object LastWriteTime,@{n="Path";e={convert-path $_.PSPath}} |
Tee-Object "\\\box_lab001\c$\Users\john\Documents\output files_root.txt" |
Remove-Item -force
我想要做的是让它在多个框中可扩展,如果用户在box_lab01上看到问题,则通过10.然后他可以使用要求输入的开关来运行脚本。然后它会单独运行命令,每次都替换box_lab ###,可能吗?
C:\powershell.ps1 -input
what boxes are having the issue? use three digit numbers only, comma separated
答案 0 :(得分:1)
您想要添加一个以数组值作为输入的参数。然后,您可以使用它们来检查每台机器:
[CmdletBinding()]
param(
[int[]]
# The numbers of the machines whose output files should be removed.
$MachineNumbers
)
$MachineNumbers | ForEach-Object {
$machineRoot = '\\box_lab{0:d3}' -f $_
Get-ChildItem ('{0}\f$\output files' -f $machineRoot) -force |
Where-Object {!$_.PsIsContainer -AND $_.lastWriteTime -lt (Get-Date).AddMinutes(-5) } |
Select-Object LastWriteTime,@{n="Path";e={convert-path $_.PSPath}} |
Tee-Object ('{0}\c$\Users\john\Documents\output files_root.txt' -f $machineRoot) |
Remove-Item -force
代码('\\box_lab{{0:d3}}' -f $_)
将从用户传递的每个数字转换为零填充的三字符字符串(似乎是您的计算器命名方案)。然后你会像这样调用你的脚本:
Remove-OutputFiles -MachineNumbers (1..10)
Remove-OutputFiles -MachineNumbers 1,2,3,4,5
您可以为MachineNumbers
参数提供合理的默认值,这样如果没有传递任何参数,它就会命中一组默认的机器。
我也会将[CmdletBinding()]
属性添加到您的脚本中,这样您就可以将-WhatIf
传递给您的脚本,看看哪些文件会被删除而不会实际删除它们:
Remove-OutputFiles -MachineNumbers (1..3) -WhatIf
答案 1 :(得分:0)
是
您可以使用Read-Host
提示输入。您可以使用param(...)
向脚本添加参数:
param($input = $null)
if ($input) {
$foo = Read-Host -Prompt $input
}
然后,您可以使用-split
:
$numbers = $foo -split ','
循环遍历:
$numbers | ForEach-Object {
...
}
您可以在块中使用$_
来引用当前号码。