进入PSSession设置远程文件夹权限失败:无法识别E盘驱动求助
问题分析&修复方案
兄弟,你这是踩了PowerShell远程会话的一个典型坑——**错误使用Enter-PSSession**了!这个命令是给你手动操作远程机器用的交互式会话,在脚本里跑完它之后,后面的Set-Location、Get-ACL这些命令根本没跑到远程的StudFS01上,还是在你本地机器执行呢!你本地没有E盘,可不就报找不到驱动器的错嘛。
修正后的完整脚本
# 获取AD管理员凭据 $Cred = Get-Credential # 创建目标文件夹 $Name = Read-Host "What is the name of the folder?" $Location = Read-Host "What is the folder path? i.e B:\Collaboration\" New-Item -Path $Location -Name $Name -ItemType "directory" # 创建AD安全组 $Groupname = Read-Host "What is the group name? i.e. SS COLLABORATION BEN" New-ADGroup -path "OU=StorSimple Centralisation Groups,OU=Groups,OU=Northgate PLC,DC=northgatevehiclehire,DC=net" ` -Name $Groupname -GroupCategory Security -GroupScope Global ` -DisplayName $Groupname -Description "Access to $Location" -Credential $cred # 配置远程服务器StudFS01的文件夹权限 $Folderpath = Read-Host "What is the path of the folder in StudFS e drive? i.e. Vehicle Sales\TOM Information" $remoteFullPath = "E:\CentralisedData\Data\$folderpath" # 用Invoke-Command把权限配置逻辑发送到远程执行 Invoke-Command -ComputerName Studfs01 -Credential $Cred -ScriptBlock { param($targetPath, $adGroupName) # 逐个创建权限规则 $domainAdminRule = New-Object System.Security.AccessControl.FileSystemAccessRule ( "northgatevehiclehire.net\Domain Admins", "FullControl", "Allow" ) $adminGroupRule = New-Object System.Security.AccessControl.FileSystemAccessRule ( "northgatevehiclehire.net\StorSimple Centralisation Administrators", "FullControl", "Allow" ) $collabGroupRule = New-Object System.Security.AccessControl.FileSystemAccessRule ( "$adGroupName", "Modify", "Allow" ) # 获取文件夹ACL并更新规则 $acl = Get-ACL -Path $targetPath $acl.SetAccessRule($domainAdminRule) $acl.SetAccessRule($adminGroupRule) $acl.SetAccessRule($collabGroupRule) Set-ACL -Path $targetPath -AclObject $acl } -ArgumentList $remoteFullPath, $Groupname
几个关键修复点解释:
- 用
Invoke-Command替代Enter-PSSession:这是核心!Invoke-Command能直接把脚本块推送到远程服务器执行,完全适配脚本的非交互式场景,不会像Enter-PSSession那样只开个会话却不执行后续命令。 - 传递参数到远程脚本块:远程会话看不到你本地的变量,所以得用
-ArgumentList把$remoteFullPath和$Groupname传过去,在脚本块里用param接收。 - 拆分
SetAccessRule调用:你原来写的$acl.SetAccessRule($rule,$rule2,$rule3)是错的,这个方法一次只能加一条规则,得拆成三次调用。 - 删掉没用的
Start-Sleep:远程执行不需要等10秒,纯纯浪费时间~
最后提前给你个小检查建议:执行脚本前先确认远程服务器的WinRM服务正常,能通PowerShell远程:
Test-WSMan Studfs01
内容的提问来源于stack exchange,提问作者NorthgateITGuy
相关产品推荐
相关产品推荐

