首先,我想道歉。我不使用 Powershell。这对我来说是一次很棒的学习经历!如果我的代码让你畏缩,我很抱歉 :)
我与多个建筑物一起工作,有时很难判断用户在哪里,最好搜索一下用户今天登录的位置。
我在用户登录时使用批处理脚本保存到文件,以便在提交故障单时可以搜索它,但不包括计算机甚至建筑物。每天都会自动生成一个新文件。
这是绑定为 GPO 的登录批处理脚本:
echo User: , %username% , Computer: , %computername% , Date\Time: , %date% %time% >> \\path\to\my\saved\file-%date:~-4,4%%date:~-10,2%%date:~-7,2%.csv
这是我用来搜索用户的 powershell 脚本:
Set-StrictMode -Version latest
$path = '\\path\to\my\saved\'
$ext='.csv'
$file='file'
$realFile="$path$file-$(get-date -F 'yyyyMMdd')$ext"
$control = Read-Host -Prompt 'Which User are you looking for?'
$output = $path + "\output.log"
$CSV2String = Select-String -Pattern $control -Path $realFile
Function getStringMatch
{
$result = Select-String -Pattern $control -Path $realFile -Quiet
If ($result -eq $True)
{
$match = $realFile
Clear-Host
Write-Host "Success! $control found logged in today!" -Foregroundcolor "green"
ForEach ($line in $CSV2String) {
$text = $line -Split ","
ForEach($string in $text) {
Write-Host "$string"
}
}
Select-String -Pattern $control -Path $realFile | Out-File $output -Append
} ElseIf ($result -eq $False){
Clear-Host
Write-Host "Error $control not found logged in, please check the User Name and try again!" -ForegroundColor "red"
Write-Host "'$control' Not logged in!" -ForegroundColor "yellow"
}
}
getStringMatch
这似乎很好用,但是当我使用脚本时,输出对我来说很奇怪,它显示了它搜索过的文件的路径,我不希望这样。我只想要信息的输出。
Success! SearchedUser found logged in today!
\\path\to\my\saved\file-20160209.csv:1:User:
SearchedUser
Computer:
MyComputer-01
Date\Time:
Tue 02/09/2016 9:31:41.93
如何从输出中删除“\path\to\my\saved\file-20160209.csv:1:”部分?我也需要根据日期进行更改,如果可能的话,我想使用一个变量。
我玩了 -Replace 但我无法让它完成我想要的任务。
任何援助将不胜感激 :)