简体   繁体   中英

How to get PS script to access folders that need admin access

I'm a desktop support tech for my company, and we often have a good bit of repetitive troubleshooting we perform such as clearing temp files and cache from C\\windows\\temp, local appdata temp folder, as well as google and IE cache/cookies. I was writing a powershell script to do this all in one go, and it does what it is supposed to. The only problem is that when I am on a user's computer, I have to actually access the windows temp and local appdata folders first and then run the script for it to work. I believe this is because those two folders require admin access to get into. Since I'm an admin I can put my creds in to access the folders just fine, but I'm having trouble finding some code to insert in order to allow the powershell script to gain access to those folders. Note: I do have a command at the beginning of the script that launches powershell as admin, but that seems to not be enough. My code is below, any insight on this would be terrific. (Looks like my comment hashtags in the code turned the comments bold, apologies)

# Runs the below script with PowerShell in Admin mode
Start-Process "$psHome\powershell.exe" -verb runas -ArgumentList "-file fullpathofthescript"

# Clears google chrome cache
Remove-Item -Path "C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Cache\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue

# Clears IE cookies
Remove-Item -Path "C:\Users\*\AppData\Roaming\Microsoft\Windows\Cookies\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue

# Clears the "windows\temp" folder
Remove-Item -Path "C:\Windows\Temp\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue

# Clears the user's local temp folder
Remove-Item -Path "C:\Users\*\AppData\Local\Temp\*" -verb runas -Recurse -Force -ErrorAction SilentlyContinue"

You can use the -Credential parameter to prompt for the local admin credentials which should allow you to delete in the C:\\Windows\\* location, assuming ACLs have not be messed with.

Remove-Item -Path "C:\Windows\Temp\*" -Credential (Get-Credential) -Recurse -Force -ErrorAction SilentlyContinue

Putting in the ErrorAction is stopping you from seeing the below error as well.

Remove-Item : A positional parameter cannot be found that accepts argument 'runas'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM