'How to run Powershell script through command prompt [duplicate]

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


Solution 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1