I try to use Set-Acl in my PowerShell script if just I make
$my_acl = Get-Acl "C:\"
Set-Acl D:\ $my_acl
This work in Admin
but if I try to launch script in User en elevate to Admin
$my_acl = Get-Acl "C:\"
$arg5={param($my_acl,)(Set-Acl D:\ $my_acl )}
Start-Process powershell.exe -ArgumentList "-noexit -command & {$arg5} $my_acl" -Verb RunAs
I got this error
Set-Acl : AclObject
Au caractère Ligne:1 : 19
+ & {param($my_acl)(Set-Acl D:\ $my_acl )} System.Security.AccessContro ...
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument : (System.Security...rectorySecurity:String) [Set-Acl], ArgumentExceptio
n
+ FullyQualifiedErrorId : SetAcl_AclObject,Microsoft.PowerShell.Commands.SetAclCommand
EDIT:
Thank for the solution PRASOON KARUNAN V the solution is really nice, but I just make:
Start-Process powershell -ArgumentList "Get-Acl C:\ | Set-Acl D:\" -Credential ($credentials_admin)
Start-Sleep -Seconds 3
Start-Process powershell -ArgumentList "Get-Acl C:\Users\$($my_user) | Set-Acl D:\$($my_user)" -Credential ($credentials_admin)
I just pipe out the result of Get-Acl in my Set-Acl and it's ok.
Your script have problems.
You don't need to set the scrtipblock to a variable, better to call
it directly.
There was a unwanted comma in param block.
Parenthesis are not required here (Set-Acl D:\ $my_acl )
$my_acl = Get-Acl "C:\"
Start-Process powershell.exe -ArgumentList "-noexit -command & {param(`$my_acl) Set-Acl D:\ `$my_acl} $my_acl" -Verb RunAs
Like below, we have to escape the $ sign so that the value no not invoked when those are using in double quotes.
`$My_acl
Related
Uninstalling :
The term 'C:\temp\install\Deploy-Application.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
+ CategoryInfo : ObjectNotFound: (C:\temp\install\Deploy-Application.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : WKPF26YSKX
This is the code ran:
function Install-File {
Invoke-Command `
-Session $global:session `
-ScriptBlock{
if( -not (Test-Path -Path "V:\") ) {
New-PSDrive -Name "V" -PSProvider "FileSystem" -Root "\\lounaswps01\idrive\D907ATS" -Credential (Get-Credential -Credential "slb8031a") -Scope global
}
$Global:certRequestID = $global:objTemp.CRID
# Assign server path and local path variables w/ given CR ID
$serverPath = "v:\" + $Global:certRequestID
$localPath = "C:\temp\" + $Global:certRequestID
dir $serverPath
dir $localPath
#Copy-Item -Path $serverPath -Destination $localPath -Recurse -Force | Out-Host
# Check for atsinst.bat first - run it if it exists. Else offer uninstall/install options
if(Test-Path -LiteralPath "${localPath}\install\atsinst.bat") {
Invoke-Expression -Command " ${localPath}\install\atsinst.bat -DeployMode 'Silent' | Out-Host "
}
Write-Host "`nUninstalling ${certRequestID}: "
Invoke-Expression -Command " ${localPath}install\Deploy-Application.exe -DeployMode 'Silent' -DeploymentType 'Uninstall' | Out-Host"
#Start-process -FilePath "${localPath}\install\Deploy-Application.exe" -argumentList "-DeployMode Silent -DeploymentType Uninstall" -wait -noNewWindow
Write-Host "`nInstalling ${certRequestID}: "
Invoke-Expression -Command " ${localPath}\install\Deploy-Application.exe -DeployMode 'Silent' | Out-Host "
}
# Offer to delete files from host
$prompt = Read-Host -Prompt "`nDelete ${certRequestID} from the user's temp folder? (y/n)"
if($prompt.ToLower() -eq "y") {
Write-Host "`nDeleting files..."
Remove-Item -LiteralPath $localPath -Recurse -Force
}
}
You're missing a backslash in one of the lines for uninstalling?
Invoke-Expression -Command " ${localPath}install\Deploy-Application.exe
Should Read:
Invoke-Expression -Command " ${localPath}\install\Deploy-Application.exe
Brief summary of what I'm trying to do.
I have a script in powershell that takes 2 files and reads in the embedded credentials and stores them in a variable to which then I can run administrative commands from.
This works great, however, after the files are read and the key is stored, I'm trying to delete the 2 files and I keep getting the following error:
Start-Process : Parameter set cannot be resolved using the specified
named parameters. At \mars\Client-Installs\NetSmart
Test3\Setup.ps1:137 char:15
+ Start-Process <<<< -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path
$file1 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
Start-Process : Parameter set cannot be resolved using the specified
named parameters. At \mars\Client-Installs\NetSmart
Test3\Setup.ps1:138 char:15
+ Start-Process <<<< -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path
$file2 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
The account I'm running with is part of domain admin and when I look in task manager I can see it running in Administrative mode.
I also know that the folder path where the files reside also have full share and security access to.
Here is a snippit of my code (The bottom 2 lines are the ones that don't seem to work)
function Authentication
{
#---------------------------------------------------
#Authenticate Admin Account using encrypted password
#---------------------------------------------------
$TempFolder = $env:temp
#The 2 lines underneath is if you are running the auth files from the same directory
#$global:AESKeyFilePath = $path + "\aeskey.txt"
#$global:SecurePwdFilePath = $path + "\credpassword.txt"
#Move the files to the temp folder
$global:file1 = $path + "\aeskey.txt"
$global:file2 = $path + "\credpassword.txt"
Copy-Item -Path $file1 -Destination $TempFolder -force
Copy-Item -Path $file2 -Destination $TempFolder -force
#If you choose to run it from the temp directory comment the lines above and uncomment the 2 below.
$global:AESKeyFilePath = $TempFolder + "\aeskey.txt"
$global:SecurePwdFilePath = $TempFolder + "\credpassword.txt"
$global:userUPN = "domain\user"
#use key and password to create local secure passwordtemp
$global:AESKey = Get-Content -Path $AESKeyFilePath
$global:pwdTxt = Get-Content -Path $SecurePwdFilePath
$global:securePass = $pwdTxt | ConvertTo-SecureString -Key $AESKey
#create a new psCredential object with required username and password
$global:adminCreds = New-Object System.Management.Automation.PSCredential($userUPN, $securePass)
#Remove the files below
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file1 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file2 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
}
You cannot specify -NoNewWindow and -WindowStyle together, its contradicting.
See Get-Command Start-Process -Syntax for the parameter sets.
I hope below way is what you need. Just use -WindowStyle Hidden.
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file2 -Force" -WorkingDirectory $path -PassThru
I was searching around and found a few hints but a few detail pieces are missing.
Here is what I have:
install-chrome.bat
PowerShell -NoProfile -Command "&{Start-Process PowerShell -ArgumentList '-NoProfile -File install-chrome.ps1' -Verb RunAs}"
install-chrome.ps1
$client = New-Object System.Net.WebClient;
$client.DownloadFile("https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe", ".\ChromeStandaloneSetup64.exe");
.\ChromeStandaloneSetup64.exe /silent /install ;
Two things are not working as expected:
I still get a UAC popup even though the posts I found state that the above should start PowerShell in Admin mode.
I was expecting .\ would download the .exe to the directory the .ps1 and .bat scripts are located.
Any hints on how to solve this?
EDIT:
Thanks to the reply from #TheIncorrigible1 I managed to solve the second part. Both options work more or less (it downloads it, but the installation throws an error locally) when I execute them directly in PowerShell:
< V3
$PSScriptRoot = Split-Path -Parent -Path $script:MyInvocation.MyCommand.Path
$uri = "https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe"
$path = "$PSScriptRoot\ChromeStandaloneSetup64.exe"
$client = New-Object System.Net.WebClient
$client.DownloadFile($uri, $path)
& $path /install
V3+
$uri = "https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe"
$path = "$PSScriptRoot\ChromeStandaloneSetup64.exe"
Invoke-WebRequest -Uri $uri -OutFile $path
& $path /install
But the batch still throws errors:
At line:1 char:62
+ ... tart-Process PowerShell -Verb RunAs -ArgumentList -NoProfile, -File, ...
+ ~
Missing argument in parameter list.
At line:1 char:69
+ ... ocess PowerShell -Verb RunAs -ArgumentList -NoProfile, -File, 'C:\Pro ...
+ ~
Missing argument in parameter list.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingArgument
Two things-
You don't need to wrap your batch command to powershell in a scriptblock and -ArgumentList expects an array of string arguments:
powershell.exe -NoProfile -Command "Start-Process -FilePath powershell.exe -ArgumentList #('-NoProfile', '-File', '%~dp0install-chrome.ps1') -Verb RunAs"
There's an automatic variable, $PSScriptRoot, to determine where your root directory is:
$uri = 'https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe'
if (-not $PSScriptRoot) {
$PSScriptRoot = Split-Path -Parent -Path $script:MyInvocation.MyCommand.Definition
}
$outFile = "$PSScriptRoot\ChromeStandaloneSetup64.exe"
if ($PSVersionTable.PSVersion.Major -lt 3) {
(New-Object -TypeName System.Net.WebClient).DownloadFile($uri, $outFile)
}
else {
Invoke-WebRequest -Uri $uri -OutFile $outFile
}
& $outFile /silent /install
Here you go:
$Path = $env:TEMP; $Installer = "chrome_installer.exe"; Invoke-WebRequest "http://dl.google.com/chrome/install/375.126/chrome_installer.exe" -OutFile $Path\$Installer; Start-Process -FilePath $Path\$Installer -Args "/silent /install" -Verb RunAs -Wait; Remove-Item $Path\$Installer
I get the an invalid path error with this script:
$buildZIP= 'starmatic'
echo $buildZIP
$command = ”\\XXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1 $buildZIP”
Invoke-Expression -Command $command
This is ToZipNew.ps1:
Param(
[Parameter(Position=1, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$build
)
echo "$build"
$S = "L:\Gopi_Prod_App\$build\App_Data\*"
$D = "\Gopi_Prod_App\Starmatic_UI.zip"
echo $S
echo $D
Get-ChildItem "$S" | Compress-Archive -DestinationPath "$D" -Verbose
#Compress-Archive -Path "$S" -CompressionLevel Fastest -DestinationPath "$D"
Error I am getting:
Compress-Archive : The path 'L:\Gopi_Prod_App' either does not exist or is not a
valid file system path.
At \\XXXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1:13 char:45
+ ... t-ChildItem "$S" | Compress-Archive -DestinationPath "$D" -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (L:\Gopi_Prod_App:String) [Compress-Archive], InvalidOperationException
+ FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Compress-Archive
Invoke-Expression is almost always the wrong tool for whatever job you have at hand. Also, it looks to me like you actually want to run the script on the remote host. However, your Invoke-Expression statement is reading the script from the remote share and executing it locally.
Change
$command = ”\\XXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1 $buildZIP”
Invoke-Expression -Command $command
into
Invoke-Command -Computer 'XXXXXXXXXX' -ScriptBlock {
& 'L:\Gopi_Prod_App\ToZipNew.ps1' $using:buildZIP
}
to run the script on the remote host XXXXXXXXXX.
If you do want to run the script locally connect the share \\XXXXXXXXXX\L$ as a network drive L: and call the script from that drive:
New-PSDrive -Name 'L' -PSProvider FileSystem -Root '\\XXXXXXXXXX\L$' -Persist
& 'L:\Gopi_Prod_App\ToZipNew.ps1' $buildZIP
Remove-PSDrive -Name 'L'
I wonder how to uses icacls within a PowerShell script for setting up permissions on a fileshare for a computeraccount for e.g. Domain\myServer$.
This is what I'm trying:
$ComputerAccount = "domain\myServer$"
$Folder = "\\TestServer\TestShare\folder1"
$rule = $ComputerAccount+':(M),(OI),(CI)'
$resICacls = Invoke-Expression "icacls $folder /grant $rule"
I got this error message:
Invoke-Expression : At line:1 char:83
+ ... ant Domain\myServer$:(M),(OI),(CI)
+ ~~
Variable reference is not valid. '$' was not followed by a valid variable name
character. Consider using ${} to delimit the name.
At c:\Binary\testacl.ps1:12 char:26
+ $resICacls = Invoke-Expression "icacls $folder /grant $rule"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : InvalidVariableReference,Microsoft.PowerShell.Commands.InvokeExpressionCommand
I tried different variants of escaping the $ but found no solution.
Anyone haves a hint how to do this?
Try using the call operator (&) or cmd /c instead of Invoke-Expression:
& icacls $folder /grant $rule
cmd /c icacls $folder /grant $rule
or use Get-Acl/Set-Acl for changing permissions:
$permissions = 'Modify'
$inheritance = 'ContainerInherit, ObjectInherit'
$acl = Get-Acl -Path $folder
$ace = New-Object Security.AccessControl.FileSystemAccessRule ($ComputerAccount, $permissions, $inheritance, 'InheritOnly', 'Allow')
$acl.AddAccessRule($ace)
Set-Acl -AclObject $acl -Path $folder
Invoke-Expression -Command:icacls foldername /grant groupName:"(CI)(OI)M"
This works fine. So I guess that if you will put the command into single quote (i.e. '') it will work. For example:
$ComputerAccount = "domain\myServer$"
Invoke-Expression -Command:"icacls $ComputerAccount /grant GroupName:'(CI)(OI)M'"