Set Folder Permission with icacls - powershell

I am embarrased that I have to ask this, but as the syntax of icacls apparently has changed in powershell, I seem to be unable to assemble a working command.
What I am trying to do:
I want to remove all permissions from a specific folder and then add the "Current logged on user" and "SYSTEM" to have Full Control. But not Admins or anything else.
What I have:
icacls $MyFolder /inheritance:r /grant: $Domain\Env:Username:(OI)(CI)F /T /grant: SYSTEM:(OI)(CI)F /T
But everytime when I execute the command I get an error
(OI)(CI) /T has not been recognized as a cmdlet or command...
I have read some tricks on the internet to use different kind of quotes or backticks for the parameters, but nothing worked for me.
Can anyone please tell my what I am doing wrong here?

As you've hinted at, the issue here isn't that the syntax is icacls has changed in PowerShell but rather that PowerShell can act strangely when executing an external command (executable) that takes arguments.
There's several ways to handle arguments, one of which is to pass them as an array of strings:
$IcaclsArgs = #(
$MyFolder,
"/inheritance:r",
"/grant",
"$Domain\$($Env:Username):(OI)(CI)F",
"/T",
"/grant",
"SYSTEM:(OI)(CI)F",
"/T"
)
& icacls #IcaclsArgs

Related

ICACLS and unicode file/folder names - the tool changes characters and is unable to locate files/folders

I'm trying to fix permissions on users folders created with Folder Redirect. I need "Domain Admins" group to have full access. Everything works as long as folder name is not using unicode characters. And there a quite many folders like that :(
For example: ICACLS changes Ł to A, ł to B...
D:\Path\Path>icacls ęóąśłżźćń
icacls ↓ˇ♣[B|zD
↓ˇ♣[B: The filename, directory name, or volume label syntax is incorrect.
'zD' is not recognized as an internal or external command,
operable program or batch file.
D:\Path\Path>icacls ĘÓĄŚŁŻŹĆŃ
icacls ↑Ë♦ZA{y♠C
↑Ë♦ZA{y♠C: Successfully processed 0 files; Failed processing 1 files
The filename, directory name, or volume label syntax is incorrect.
I tried changing chcp to various values, nothing worked (by default my cmd uses 852). Tried changing fonts used by cmd, also didn't help.
Is it possible to make ICACLS understand Polish? :)
EDIT: weird thing is, when i use ICACLS as 'system', it behaves like above. When used with mu user rights, it properly reads unicode characters.
EDIT2:
where icacls ran as user
C:\Users\Administrator.CEO>where icacls
C:\Windows\System32\icacls.exe
where icacls ran as system
C:\Windows\system32>where icacls
C:\Windows\System32\icacls.exe
i try to run icacls commands from cmd window, not as .bat or .cmd files, for example
icacls "D:\FolderRedir\IT\Stanisław Smólski" /grant "Domain Admins":F
output changes ł and ó to other characters, and icacls is unable to locate the file/directory
Not sure what exactly was wrong - we had a problem with one ups today and server was forcefully restarted. After the restart (and unexpected Windows update that used the restart oportunity) i tried icacls again, and... it worked with all the Polish characters.
I guess the problem solved itself.

Why doesn't this msiexec.exe command work in powershell?

I am trying to execute the following command through powershell, in a script invoked by an Advanced Installer generated installation program. The problem is that when the script executes, it chokes on a call to MSIEXEC.exe. More specifically, it puts up a windows dialog of the msiexec help screen.
Ok so maybe it doesn't like the way advanced installer is executing it. So I take the actual line that is causing problems:
msiexec.exe /q /i 'C:\Users\ADMINI~1\AppData\Local\Temp\mongo-server-3.4-latest.msi' INSTALLLOCATION='C:\Program Files\MongoDB\Server\3.4\' ADDLOCAL='all'
And when I execute this directly in powershell, I still get the same stupid help screen. I have tried every conceivable variation of this command line:
/a and /passive instead of /i and /q
with double quotes
with single quotes
the msi unquoted
in an admin elevated shell
in a normal privilege shell
the msi located on the desktop instead of the temp folder
using /x to uninstall in case it was already installed
In all cases, I get the damnable "help" dialog. The only thing that appears to make a difference is if I leave off the INSTALLLOCATION and ADDLOCAL options. (These are apparently used as per "Unattended Installation part 2" found here: https://docs.mongodb.com/tutorials/install-mongodb-on-windows/). In that case it just exits quietly without installing anything.
I'm honestly at my wits' end having been beating my head against the wall on this all afternoon.
By the way, the reason I'm installing mongo in such an absurd way is I need a method of having a single-install system for my company's product. It depends on Mongo, and we have to have it run as a server and use authentication, so I have to have scripts to create the admin and database user and put it into authenticated mode. Since I needed to know where mongo was installed (to execute mongod.exe and mongo.exe) I need to query the user first for the location, then pass on the install location to the mongo installer. If I'm completely off the rails here please let me know that there's a better way.
Thanks
EDITED: I forgot to mention I wrote my complete powershell script and tested it before trying to execute it through advanced installer. The script worked until I tried to run it through the installer. Strange that I still can't execute the command though manually now.
It seems that in order to pass paths with embedded spaces to msiexec, you must use explicit embedded "..." quoting around them.
In your case, this means that instead of passing
INSTALLLOCATION='C:\Program Files\MongoDB\Server\3.4\', you must pass INSTALLLOCATION='"C:\Program Files\MongoDB\Server\3.4\\"'[1]
Note the embedded "..." and the extra \ at the end of the path to ensure that \" alone isn't mistaken for an escaped " by msiexec (though it may work without the extra \ too).
To put it all together:
msiexec.exe /q /i `
'C:\Users\ADMINI~1\AppData\Local\Temp\mongo-server-3.4-latest.msi' `
INSTALLLOCATION='"C:\Program Files\MongoDB\Server\3.4\\"' ADDLOCAL='all'
Caveat:
This embedded-quoting technique relies on longstanding, but broken PowerShell behavior - see this answer; should it ever get fixed, the technique will stop working; by contrast, the
--% approach shown below will continue to work.
A workaround-free, future-proof method is to use the PSv3+ ie helper function from the Native module (in PSv5+, install with Install-Module Native from the PowerShell Gallery), which internally compensates for all broken behavior and allows passing arguments as expected; that is, simply prepending ie to your original command would be enough:
# No workarounds needed with the 'ie' function from the 'Native' module.
ie msiexec.exe /q /i 'C:\Users\ADMINI~1\AppData\Local\Temp\mongo-server-3.4-latest.msi' INSTALLLOCATION='C:\Program Files\MongoDB\Server\3.4\' ADDLOCAL='all'
The alternative is to stick with the original quoting and use --%, the stop-parsing symbol, but note that this means that you cannot use PowerShell variables in all subsequent arguments:
msiexec.exe /q /i `
'C:\Users\ADMINI~1\AppData\Local\Temp\mongo-server-3.4-latest.msi' `
--% INSTALLLOCATION="C:\Program Files\MongoDB\Server\3.4\\" ADDLOCAL='all'
Note that msiexec, despite having a CLI (command-line interface), is a GUI-subsystem application, so it runs asynchronously by default; if you want to run it synchronously, use
Start-Process -Wait:
$msiArgs = '/q /i "C:\Users\ADMINI~1\AppData\Local\Temp\mongo-server-3.4-latest.msi" INSTALLLOCATION="C:\Program Files\MongoDB\Server\3.4\\" ADDLOCAL=all'
$ps = Start-Process -PassThru -Wait msiexec -ArgumentList $msiArgs
# $ps.ExitCode contains msiexec's exit code.
Note that the argument-list string, $msiArgs, is used as-is by Start-Process as part of the command line used to invoke the target program (msiexec), which means:
only (embedded) double-quoting must be used.
use "..." with embedded " escaped as `" to embed PowerShell variables and expressions in the string.
conversely, however, no workaround for partially quoted arguments is needed.
Even though Start-Process technically supports passing the arguments individually, as an array, this is best avoided due to a longstanding bug - see GitHub issue #5576.
[1] The reason that INSTALLLOCATION='C:\Program Files\MongoDB\Server\3.4\' doesn't work is that PowerShell transforms the argument by "..."-quoting it as a whole, which msiexec doesn't recognize; specifically, what is passed to msiexec in this case is:
"INSTALLLOCATION=C:\Program Files\MongoDB\Server\3.4\"

How to check who has access to folders using cmd or powershell

I wanted to ask how one would check who has access to subfolders in a certain directory on a server using either the CMD or Powershell?
For NTFS permissions I like to use the NTFSSecurity PowerShell Module as the output is similar to the windows permissions GUI.
It has simple commands for adding and removing permissions, which is an ugly process using the standard acls commands!
To see current NTFS permissions using this module:
Get-NTFSAccess -Path "\\server\share\folder"
Which would give an output like this:
You are looking for icacls. From cmd type icacls directoryname /t replacing directoryname with the actually directory name to display all of the access permissions for the directory and subdirectories. The /t flag specifies to look in subdirectories. For more info just type in icacls into cmd or look at this link: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/icacls

Powershell to EXE tool Advice

So here's the deal. Because of a number of... let's just say not PowerShell smart people who will be using an incredibly complex application that I just finished, I need the ability to package it in an exe wrapper.
This shouldn't be that hard
I was able to successfully use PS2EXE, except for some reason with AD, it throws out a whooooole bunch of AD text that I can't get rid of. Tried to fix that for a few days before getting frustrated and moving on.
Then, I discovered PowerGUI. I can't say that I like it, at all. However, its compiler was exactly what I was looking for! Except for the fact that Exchange 2010 snap-ins are not compatible with .NET 4.5 through this application.
I want to make it very clear that my script works perfectly on multiple different computers, but as soon as I use any of these tools, everything breaks.
An exe is the best thing that I can think of to simplify the interface, and keep the Technically Intellectually Stunted from breaking everything, or running to me with every little error because they somehow got into the code and typed something and saved it, and now nothing works and it's the end of the world and they have no idea what happened.
If you guys know of any tools to wrap this up into an exe, or have any other ideas on how to help, I would really appreciate anything you guys can give me.
You have never failed me in the past!
From my point of view if you really want an EXE file you should write a .NET application, it's not so hard to embed PowerShell CmdLets.
In order to avoid end user modifying your code I know two solutions :
First : set execution policy to AllSigned on the user computer and sign the scripts you deploy. You can manage to use our own certificates (not expensive at all) or public certificates (more expensive). One of the drawback of this solution is that it does not prevent users from seeing the code. Another big drawback is that a PKI and sign code infrastructure is a lot of wast time.
Second : for non interactive scripts (be carefull it's a kind of makeshift job) :
Create a new user account
Only allow access to the script file for the new account.
Set up a task in the Windows scheduler to run that script file with PowerShell under that specific account. The permissions for the scheduled tasks allow read and execute access to the user(s). Then set the task to "disabled".
Whenever the script file needs to be run, the corresponding task is manually started by the user.
Using this solution will also allow you to remote execute your script.
When I had a similar deployment problem - 1) user's didn't know powershell 2) I didn't want them to have to understand things like execution policy, 3) how to start PS, 4) etc. I wrapped it in a batch file. I also wanted to make sure that experienced PS users still had the capabilities of PS, so the batch file determined if it was running under PS or not and ran in the current PS session if applicable. I was never too worried that users would mess with the script - they were happy if it "just worked". So whether users liked Explorer, CMD.EXE, or PS, they all were accommodated.
The batch file I wrote first runs a bit of powershell code to determine if the process of the batch file is the grandchild of a powershell process. If it is then the batch file is being invoked from PS. The execution policy is also checked and if it is lenient enough then Wscript.SendKeys is used to send keystrokes to PS to get the script running in the current PS session. If it isn't then it starts a new PS session using -ExecutionPolicy parameter and passes the script as a command line argument (-Command).
This bit of powershell code communicates back to the .CMD file using a return code. Sorry it's cryptic, but the length of command line parameters is limited. Here's the code:
set scr= $mp=[diagnostics.process]::getcurrentprocess().id
set scr=%scr%; $pp=([wmi]\"win32_process.handle='$mp'\").parentprocessid
set scr=%scr%; $gp=([wmi]\"win32_process.handle='$pp'\").parentprocessid
set scr=%scr%; $ep=[int][microsoft.powershell.executionpolicy](get-executionpolicy)
set scr=%scr%; try {$pnp=1-[int](([wmi]\"win32_process.handle='$gp'\").Name -eq \"powershell.exe\")
set scr=%scr%; } catch {$pnp=1}
set scr=%scr%; $ev = (8 * $pnp + $ep) -band 0xB; %wo% pp: $pp gp: $gp ev: $ev; if ($ev -le 1) {
set scr=%scr% %wo% Launching within existing powershell session...`n;
set scr=%scr% $w=new-object -com wscript.shell;$null=$w.appactivate($gp);
set scr=%scr%; $w.sendkeys(\"^&{{}`$st =cat "%me%";`$sc=`$st -join [char]10 -split 'rem PS script';
set scr=%scr% `$script:myArgs = `\" %*`\";`$sb=[scriptblock]::create{(} `$sc[3]{)};. `$sb{}}~\")
set scr=%scr%; }
set scr=%scr%; exit $ev
powershell -noprofile -Command %scr%
%wo% is to allow debugging this "checker script". If debugging is on the %wo% is set to write-host. Otherwise it is set to define a "null" function and then invoke the null function. The null doesn't do anything so the message that is the argument to the function is not output.
Note the escaping when invoking SendKeys. ^ is the CMD.EXE escape character and SendKeys has it's own escape mechanism, as does PS.
If run from PS you end up in a PS session thanks to SendKeys. Otherwise the batch file does this:
set scr= ren function:prompt prompto
set scr=%scr%; function prompt{ 'myApp: '+(prompto)}
set scr=%scr%; $st= (cat %me%) -join \"`n\";
set scr=%scr%; $sx=($st -split 'rem PS script')
set scr=%scr%; $sc=$sx[3]
set scr=%scr%; %wo% myArgs: $myArgs script length: $sc.length
set scr=%scr%; ^&{$script:myArgs=\"%*\"; iex $sc}
title MyApp
rem Change the number of lines on the console if currently set to 25
for /f "tokens=2" %%i in ('mode con^|findstr Lines:') do if %%i LEQ 25 (mode con lines=50&color 5F)
powershell -noexit -noprofile -command "%scr%"
This "helper script" also can't be too long. So the helper script reads the original .CMD file and then splits it by using the string 'rem PS script'. That string will be in both this helper script as well as in the batch file (separating the batch file statements from PS statements). In my case the string is also in the batch file comments, so that is why the index of 3 is used.
Your PS script can define functions or a module. Your PS script can also output some introductory info to explain to users how to get started, how to get help, or whatever you want.
Rather than just using the PS command line, your PS script could create it's own interactive environment (using Read-Host for example). However I didn't want to do that because it would have prevented experienced PS users from using their knowledge about PS. For example if your script requires a username/password, an experienced PS user could use get-credential to create a credential to send to your script.

Running a cmd in powershell referencing a UNC path

I’m in the process of creating a powershell script to check OU users against users already configured for file share archiving but I’ve hit a stumbling block. I can query AD to get a list of users per OU and their home directories, dumping all of the details out to text files for logs and basing subsequent queries on. Once I have these details I try to run a dos command, (Enterprise Vault) Archivepoints.exe passing variables to it. The command would usually be :
Archivepoints.exe find \\fopserver045v\ouone_users$
When I try to run the following code I get an error.
$app="D:\Enterprise Vault\ArchivePoints.exe"
$EVArg = "find"
$VolLine = "\\fopserver045v\ouone_users_r$"
Invoke-Item "$app $EVArg $VolLine"
Invoke-Item : Cannot find path 'D:\Enterprise Vault\ArchivePoints.exe find \fopserver045v\ouone_users_r$' because it does not exist.
At first I thought it was missing the first backslash of the UNC path that was causing the issue but I'm no longer sure.
The script and command run on the EV server and the UNC bath doesn't actually go to the server, it's only a reference path within EV so it's not a credentials issue.
I need to be able to log the output to file too if possible.
What should the code look like and should I be using invoke-command or Invoke-Expression instead ?
Thanks
Don't use Invoke-Item. External commands should be run using the call operator (&). You can use splatting for the argument list.
$app="D:\Enterprise Vault\ArchivePoints.exe"
$arguments = "find", "\\fopserver045v\ouone_users_r$"
& $app #arguments