1

I'm not able to get the following powershell script to run in cmd prompt. The script will list all ad groups for a USERNAME and it works great in powershell. I want to be able to do this in cmd prompt so I can eventually automate the process in VBA. But I can't seem to configre the string correctly.

this is my code in command prompt with the error:

C:\Users\USERNAME>powershell -command "(New-Object System.DirectoryServices.DirectorySearcher(""(&(objectCategory=User)(samAccountName=USERNAME))"")).FindOne().GetDirectoryEntry().memberOf | clip"
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
SQALEX101
  • 209
  • 1
  • 3
  • 16
  • Replace the QUOTATION MARKS `""` with APOSTROPHE `'`. – lit Mar 30 '22 at 21:08
  • 1
    In short: When calling PowerShell's _CLI_ (`powershell.exe` for _Windows PowerShell_, `pwsh` for _PowerShell (Core) 7+_) from the outside, using `-Command` / `-c`, you need to _escape_ `"` chars. you want passed through as part of the command: `\"` works in principle, but can break when calling from `cmd.exe`, as would happen in this case. Use `"^""` (sic) with `powershell.exe`, and `""` with `pwsh.exe`, inside overall `"..."` quoting. See the linked duplicate for details. – mklement0 Mar 30 '22 at 22:10
  • A - tricky - alternative is to stick with `\"` escaping and individually `^`-escape `cmd.exe` metacharacters such as `&`, but that requires careful analysis of which parts of the string `cmd.exe` sees as unquoted. – mklement0 Mar 30 '22 at 22:12

1 Answers1

2

In cmd.exe you'll want to use the escape sequence \" for the quote marks inside the string argument, and then escape the & with the sequence ^&:

C:\Users\USERNAME>powershell -command "(New-Object System.DirectoryServices.DirectorySearcher(\"(^&(objectCategory=User)(samAccountName=USERNAME))\")).FindOne().GetDirectoryEntry().memberOf | clip"
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206