[英]Retrieve data from scheduled task
We're trying to collect the mapped drives of a user that is logged on to a Windows 7 client. 我们正在尝试收集已登录Windows 7客户端的用户的映射驱动器。 To do this we need to create a scheduled task and have it run as that user. 为此,我们需要创建一个计划任务,并以该用户身份运行它。 This works fine but the problem is on retrieving the data from the scheduled task. 这可以正常工作,但问题在于从计划任务中检索数据。
Code 码
Invoke-Command -ScriptBlock {
$User = 'John'
$Script = 'C:\Users\' + $User + '\AppData\Local\Temp' + '\Script.ps1'
$File = 'C:\Users\' + $User + '\AppData\Local\Temp' + '\Data.txt'
$Code = {
$User = 'John'
$File = 'C:\Users\' + $User + '\AppData\Local\Temp' + '\Data.txt'
Get-WmiObject -Class win32_mappedlogicaldisk | Select-Object Name, ProviderName |
Export-Csv $File -Encoding UTF8 -NoTypeInformation
}
$Code | Set-Content $Script -Encoding utf8
schtasks /create /RL HIGHEST /SC ONCE /ST 23:00 /TN "Test" /TR "powershell.exe -ExecutionPolicy Bypass -File '$Script'" /RU "$env:USERDNSDOMAIN\$User"
schtasks /run /TN "Test"
schtasks /delete /F /TN "Test"
for ($i = 0; $i -le 5; $i++) {
if (Test-Path $File) {
Import-Csv $File
Break
}
else {
Start-Sleep -Seconds 1
}
}
} -ComputerName $Computer
The problem seems to be retrieving the Data.txt
from the users $ENV:Temp
folder. 问题似乎是从用户$ENV:Temp
文件夹中检索Data.txt
。 It seems like a bit of a repetitive thing, is there not a cleaner way of doing this? 似乎有点重复,难道没有更干净的方法吗?
Thank you for your help. 谢谢您的帮助。
As it is a non interactive script, I'd use the same approach, just with a shortened version of the wait loop: 由于它是一个非交互式脚本,因此我将使用相同的方法,只是将等待循环的版本缩短:
while (!(Test-Path $File)) { Start-Sleep 1 }
Import-Csv $File
A bit more elegant, but essentially the same. 稍微优雅一点,但基本相同。
I would go for something like the below as a Login Script . 我会像下面这样作为登录脚本 。
$File = "\\server\share\$($env:username).csv"
if (!(Test-Path $File)) {
Get-WmiObject -Class win32_mappedlogicaldisk | Select-Object Name, ProviderName | Export-Csv $File -Encoding UTF8 -NoTypeInformation
}
As it's a login script it will run in the users context (and get only their mapped drives) and will write files to a central share rather than their local drive so it will be much easier for you to get the data. 由于它是一个登录脚本,它将在用户上下文中运行(并且仅获取其映射的驱动器),并将文件写入中央共享而不是本地驱动器,因此您可以更轻松地获取数据。
If you want another sample you can move/delete the files as appropriate, or remove the Test-Path
check and add -Append
to Export-Csv
and it'll keep logging drives to the file at every logon. 如果您想要另一个示例,则可以适当地移动/删除文件,或者删除Test-Path
检查并在-Append
Export-Csv
添加-Append
,它将在每次登录时将驱动器记录到文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.