我們希望消除每個使用者的 appdata 資料夾中存在的已識別出的錯誤設定檔(並進行手動修復)。設定檔只存在於各處,而不存在於每個使用者中。因此,我試圖拼湊一個腳本,如果指定的文字與 config.xml 上的 get-content 匹配,腳本將傳回 true/false。我想針對每台電腦上的每個使用者設定檔執行此命令並將結果輸出到 csv。
到目前為止我遇到了一個問題。仍在學習 powershell,因此非常感謝任何幫助。
$Users = "C:\Users"
$x = "This is the text I'm looking for"
Foreach ($Username in $Users)
{
$Path = "$Users\$Username\AppData\Local\MyApp\Settings\Config.xml"
$y = Get-Content -Path $Path
If ($y -match $x)
{
"true"
}
else
{
"false"
}
}
正如您所看到的,我還沒有轉到 csv 部分,因為我無法獲得生成 get-content 的正確路徑。
而不是我希望 foreach 迴圈工作的正確路徑是:
"C:\Users\Username1\AppData\Local\MyApp\Settings\Config.xml"
"C:\Users\Username2\AppData\Local\MyApp\Settings\Config.xml"
"C:\Users\Username3\AppData\Local\MyApp\Settings\Config.xml"
相反,我收到以下錯誤:
Get-Content : Cannot find path 'C:\Users\C:\Users\AppData\Local\MyApp\Settings\Config.xml' because it does not exist.
At C:\Users\mastaxx\Desktop\test.ps1:9 char:6
+ $y = Get-Content -Path $Path
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\C:\Use...ings\Config.xml:String) [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
我在這裡看似愚蠢的假設是 $Users 是"C:\Users"
(我相信這是因為我已經定義了它)而 $Username 是"Username1"
(顯然不是)。相反,我可以看到"C:\Users"
在這種情況下,正在建置的路徑是錯誤的:
C:\Users\C:\Users\AppData\Local\MyApp\Settings\Config.xml
我希望 foreach 循環將內部的每個資料夾視為$Users
一個單獨的對象,並成為$Username
每個循環實例中的 ,允許我將其插入到設定檔中,$path
如下所示:
$Users $Username
↓ ↓
C:\Users\Username1\AppData\Local\MyApp\Settings\Config.xml
我不完全確定我做錯了什麼,但我知道我肯定在這裡做了一些愚蠢的事情。非常感謝任何具有更好 PS 技能的人幫忙指出嗎?
答案1
我設法發現我在等式中缺少 Get-Childitem 。
這是正確的方法,儘管我確信我的 PS 需要重大改進,因為我無法導出格式正確的 CSV,所以我選擇了混亂的方法,即輸出單獨的 CSV每個實例都是正確的,但至少它有效!
$computers = Get-Content -Path "C:\computers.txt"
foreach ($comp in $computers) {
$i = "\\$comp\C$\Users\"
$AppData = "\AppData\Local\MyApp\Settings\Config.xml"
$text = "Text I'm Looking For*"
Get-ChildItem -Path $i
Foreach ($folder in Get-Childitem $i)
{
$ReadConfig = Get-Content -Path "$i$folder$AppData"
If ($ReadConfig -match $text)
{
out-file "c:\results\$comp $folder.csv"
}
else
{
"false"
}
}
}