【问题标题】:How to use a variable to call from a position in an array? [duplicate]如何使用变量从数组中的位置调用? [复制]
【发布时间】:2021-01-22 06:59:59
【问题描述】:

学习 Powershell 并编写此脚本以供练习。该脚本的最终目标是删除本地计算机上每个用户的 %appdata%\Roaming\Microsoft\Outlook 目录中的“Outlprnt.file”文件。该文件经常损坏,需要重命名,以便 Outlook 可以生成一个新文件。我用来执行此操作的代码如下。

$alluserprofiles = Get-ChildItem -Path C:\Users\ -name
   
[int[]]$userprofiletotal = $alluserprofiles.Count

    while ($userprofiletotal -ge 0){
    
Write-Output "Removing old print file backup for user $alluserprofiles[$userprofiletotal]..."
Remove-Item -Path "C:\Users\$alluserprofiles[$userprofiletotal]\Appdata\Roaming\Microsoft\Outlook\backup\outlprnt.old" -ErrorAction SilentlyContinue

Write-Output "Backing up current print file for user $alluserprofiles[$userprofiletotal]..."
Rename-Item -Path "C:\Users\$alluserprofiles[$userprofiletotal]\Appdata\Roaming\Microsoft\Outlook\outlprnt" -NewName "outlprnt.old"
    
Write-Output "Completed successfully for user $alluserprofiles[$userprofiletotal]."
    
$userprofiletotal = $userprofiletotal - 1
    
Write-Output "Starting $alluserprofiles[$userprofiletotal] in 5 seconds..."
Start-Sleep -s 5
}

这是我遇到问题的部分:

$alluserprofiles = Get-ChildItem -Path C:\Users\ -name

[int32[]]$userprofiletotal = $alluserprofiles.Count

因为这是输出:

$alluserprofiles[Public Default (my user) 3]

目标是:

1:将 C:\Users 中的文件夹名称存储在一个数组中($alluserprofiles)

2:创建数组中值总数的变量($userprofiletotal)

3:使用包含数组中值总数的变量来获取索引的那个位置的元素($alluserprofiles[userprofiletotal]

4:将该元素放入路径中并执行删除文件的功能(C:\Users(用户文件夹名称)\etc.)

5:从变量 $userprofiletotal 中减去 1 以移动到索引中的下一个值

6:循环直到该过程针对索引中的所有值运行。

如何使用我当前使用的方法来实现这一点?如果有更有效的方法来做到这一点(我确信有),那会是什么?提前致谢。

【问题讨论】:

  • 删除所有用户配置文件中文件的最简单解决方案是:Remove-Item -Path 'C:\Users\*\AppData\Roaming\Microsoft\Outlook\Outlprnt.file'。当 Outlook 生成新的时,这应该是您所需要的。 ;-)
  • 正确^也应该申请Rename-Item部分。
  • linked post 提供了详细信息,但简而言之:在"..." 内部,如果要引用超出简单变量引用的表达式(例如,$var),则需要将其括起来它在$(...)(例如,$($var[0])

标签: powershell


【解决方案1】:

执行您所要求的最简单方法,@Olaf 在评论中发布了答案。如果您正在寻找一种更有效的方式来遍历数组,您可以使用ForEach

$alluserprofiles = Get-ChildItem -Path C:\Users\ -name

   Foreach($user in $alluserprofiles){
    
Write-Output "Removing old print file backup for user $user..."
Remove-Item -Path "C:\Users\$user\Appdata\Roaming\Microsoft\Outlook\backup\outlprnt.old" -ErrorAction SilentlyContinue

Write-Output "Backing up current print file for user $user..."
Rename-Item -Path "C:\Users\$user\Appdata\Roaming\Microsoft\Outlook\outlprnt" -NewName "outlprnt.old"
    
Write-Output "Completed successfully for user $user."
   
Write-Output "Starting $user in 5 seconds..."
Start-Sleep -s 5
}

【讨论】:

  • 建议使用foreach 语句循环内存中的数组是一个很好的提示,但请在代码中使用适当的缩进。
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 2021-12-22
  • 2021-06-14
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2014-03-29
相关资源
最近更新 更多