Powershell代码在Window中运行正常,但不在.ps1文件中运行

时间:2017-02-23 23:31:34

标签: powershell

以下代码在粘贴到以管理员身份运行的PowerShell窗口时运行:

$directory = "C:\Program Files (x86)\CAREWare"
$domainName = "DHS"
$group = 'Domain Users'
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
$acl = (Get-Item $directory).GetAccessControl("Access")
$user = "{0}\{1}" -f "$domainName", $group
$user.trim()
$access = "FullControl"
$accessType = "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule -ArgumentList @("$user","$access", "$inherit", "$propagation", "$accessType")
$acl.SetAccessRule($accessRule)
set-acl $directory $acl 

但是,当尝试在.ps1文件(没有其他代码)中运行上面的代码时,我得到权限错误或目录位置错误。 .ps1文件与运行它的.ps1文件位于同一位置。

以下是没有用的:

$script4 = "D:\PowerShell\AllUsersTotalControlCAREWareFolder.ps1"
Start-Process powershell  -WorkingDirectory (Split-Path $script4)  -Credential dhs\jdavis_desktop -ArgumentList '-noprofile', '-command', "start-process '$script4' -verb runas"

我正在尝试提供一个文件夹“完全控制”,我之前在此过程中创建了该文件夹。

编辑: 我刚刚再次运行脚本,没有错误,但没有更改权限。 它只是吹过代码的那一部分。

1 个答案:

答案 0 :(得分:0)

我终于得到.ps1文件来运行.ps1文件:

$script4 = "D:\PowerShell\AllUsersTotalControlCAREWareFolder.ps1"
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$script4`"" -Verb RunAs}