Why doesn't echo yes| work in my script?

5k views Asked by At

Can anyone explain to me why I can write 'ECHO Y|' in the Powershell command line but not if I implement it in a script?

These variables are taken from a .csv file. When I used the command line I did not use the variables.

ECHO Y|cacls $_."Serverdisc" /G ADMINISTRATORS:F
 cacls $_."Serverdisc" /G $_."Username":C /T /E
 cacls $_."Serverdisc" /G SYSTEM:F /T /E
3

There are 3 answers

0
Adil Hindistan On

I am guessing you are trying to pass "Y(es)" to any possible prompts? CMD shell and PowerShell are two different shells. What you are trying to do is use the CMD shell syntax for Powershell and therefore running into trouble

$_ is used when you are iterating through an array coming from pipeline, so there must be something other than what you have shared here. I will give you an example.

Assume I have 2 files in c:\temp\:

c:\temp\a.txt
c:\temp\b.txt

and I want to grant them permissions and not to be prompted.

"c:\temp\a.txt","c:\temp\b.txt" | foreach-object {
ECHO Y|cacls $_ /G ADMINISTRATORS:F
echo Y|cacls $_ /G SYSTEM:F /T /E
}

This is equivalent to the following

ECHO Y|cacls c:\temp\a.txt /G ADMINISTRATORS:F
echo Y|cacls c:\temp\a.txt /G SYSTEM:F /T /E
ECHO Y|cacls c:\temp\b.txt /G ADMINISTRATORS:F
echo Y|cacls c:\temp\b.txt /G SYSTEM:F /T /E

$_ is being replaced withing foreach-object by what is coming down from pipeline, which is pretty much imitating CMD shell command that would work.

0
HAL9256 On

I will add to Adil H.'s comments and say that using cacls is depreciated. You should instead be using icacls. icacls has a parameter /Q (Quiet) which will suppress all the confirmation messages for you, and you will not have to use ECHO Y| in your code.

(assuming you have the rest of your script in order(see Adil H.'s post)) Your script block would change to this:

icacls $_."Serverdisc" /Q /Grant ADMINISTRATORS:F
icacls $_."Serverdisc" /Q /Grant $_."Username":C /T
icacls $_."Serverdisc" /Q /Grant SYSTEM:F /T
0
Rob van Halteren On

It's probably because the pipeline function of powershell is different from the cmd prompt

If you use cmd /c echo Y| cacls .... it will work.