简体   繁体   中英

Powershell code runs ok in Window, but not from .ps1 file

This code below runs when pasted into PowerShell window that is running as Administrator:

$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 

However, when trying to run the above code inside a .ps1 file (no other code), I get permissions error or directory location error. The .ps1 file is in the same place as the .ps1 file that runs it.

Here is what doesn't work:

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

I am trying to give a folder Full Control that I was created earlier on in the process.

EDIT: I just ran the script again and I get no errors, but no permissions are changed. It just breezes through that part of the code.

I finally got .ps1 file to run .ps1 file:

$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}

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