【发布时间】: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