0
votes

We're trying to collect the mapped drives of a user that is logged on to a Windows 7 client. 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. It seems like a bit of a repetitive thing, is there not a cleaner way of doing this?

Thank you for your help.

2
Write the data to a share on a server? - henrycarteruk
Thx for the tip! U just thought there was a better way. Because now one needs to check when the file is present with a wait time on it. - DarkLite1
Are you going to run this on a domain joined computer? If so there are much easier ways of doing this.. - henrycarteruk
Yes, on a domain joined machine. The problem however lies in the fact to find the mapped drives of the logged on user, not the user that initiated the script from the server. - DarkLite1
For scheduling, you might want to look into PSScheduledJob. msdn.microsoft.com/en-us/powershell/reference/5.1/… - lit

2 Answers

0
votes

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.

0
votes

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.