执行PowerShell脚本移动文件时遇Permission Denied错误求助
I’ve run into this exact UnauthorizedAccessException error more times than I can count when scripting file moves in PowerShell—especially with domain-hosted files like \\domain\tm1server.log. Let’s walk through the most reliable fixes, ordered by how likely they are to resolve your issue:
1. Run PowerShell as Administrator
Most of the time, this is the quick fix. Even if you’re logged into an admin account, regular PowerShell sessions run with limited privileges by default.
- Right-click the PowerShell icon and select Run as administrator
- If your script runs automatically via Task Scheduler, go to the task’s properties → Security options → Check "Run with highest privileges"
2. Check if the File is Locked by Another Process
The tm1server.log file is probably being held open by the TM1 server process itself. You can’t move a file that’s in use by another application:
- Run this command to find the locking process:
Get-Process | Where-Object {$_.Modules.FileName -match "tm1server.log"} - If you get a result, stop the process (if it’s safe to do so) and retry the move. For server logs, you might need to schedule the move during a maintenance window when the TM1 service is stopped.
3. Verify NTFS Permissions
Move-Item requires two key permissions:
- On the source file: Read + Delete permissions (since moving a file deletes it from the original location)
- On the target folder: Write permissions
To check:
- Right-click the source file/folder → Properties → Security tab
- Select your user account (or the account running the script) and confirm the required permissions are enabled
- If not, click Edit to add or modify permissions
4. Take Ownership of the File
Sometimes the file’s ownership is tied to a system account or another user, blocking your access. Use these commands to take ownership first:
# Get the file object $logFile = Get-Item "\\domain\tm1server.log" # Retrieve the current ACL $acl = Get-Acl $logFile # Set your user as the owner $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $acl.SetOwner([System.Security.Principal.NTAccount]$currentUser) # Apply the updated ACL Set-Acl $logFile $acl
After running this, retry the Move-Item command.
5. Use Robocopy Instead of Move-Item
Robocopy is a more robust file-copying tool built into Windows, and it can sometimes bypass permission restrictions that trip up Move-Item. To move the file:
robocopy "\\domain\source-path" "\\domain\target-path" "tm1server.log" /MOV
The /MOV parameter tells Robocopy to move the file (copy it to the target, then delete the source).
Quick Notes for Domain Environments
- If you’re working with domain resources, make sure the account running the script has domain-level permissions to access both the source and target locations.
- Avoid using local admin accounts for domain file operations—stick to domain accounts with the necessary rights.
内容的提问来源于stack exchange,提问作者User1493

