Austin T French
Austin T French

Reputation: 5140

Powershell Reverse Escape Character

I need to know if there is a way to expand a PowerShell variable, and simultaneously not remove the next character.

What I have is the command:

"iCacls $Destination /GRANT domain\$userN:(OI)(CI)(M) /t" | Invoke-NativeExpression

Where the function Invoke-NativeExpression looks like:

    function Invoke-NativeExpression
{
    param (
   [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)]
   [string]$Expression
    )

    process
    {
        $executable,$arguments = $expression -split ' '
        $arguments = $arguments | foreach {"'$_'"}
        $arguments = $arguments -join ' '
        $command = $executable + ' ' + $arguments

      if ($command)
        {
            Write-Verbose "Invoking '$command'"
            Invoke-Expression -command $command
        }
    }
}

This method works great for non variable groups, for example domain\Admins:perms is fine.

Is there a way to allow PowerShell to accept $UserN: without seeing :(OI)(CI) as part of the variable name? A sort of reverse reverse escape character?

Upvotes: 0

Views: 348

Answers (3)

Austin T French
Austin T French

Reputation: 5140

I had an idea to hack it, and worked right after I posted this. Figures!

What I did was:

$uUserN = ":(OI)(CI)(M) /t"
"iCacls $Destination /GRANT domain\$userN$uUserN" | Invoke-NativeExpression

Is it especially pretty or readible, probably not. It did work though!

Upvotes: 0

mjolinor
mjolinor

Reputation: 68321

A couple of different ways to solve this:

Subexpressions:

"iCacls $Destination /GRANT domain\$($userN):(OI)(CI)(M) /t" 

Format string:

'iCacls $Destination /GRANT domain\{0}:(OI)(CI)(M) /t' -f $UserN 

Upvotes: 2

Keith Hill
Keith Hill

Reputation: 201852

Use {} around the name like so:

"${UserN}:(OI)(CI)(M)"

Upvotes: 3

Related Questions