We help IT Professionals succeed at work.

get-adgroupmember powershell multiple lines of code

pma111 asked
Hi, somebody kindly provided a powershell script for listing all groups in AD, as shown below:

$Groups = get-adgroup -filter *
foreach ($Group in $Groups) {
Get-ADGroupMember -Identity $Group | select $group, name | out-file "c:\groupmembers.csv" -append

Open in new window

However, as I am not from a powershell/scripting background, I dont really get how you run this. Some of the other scripts I have seen are "one-liners", i.e. get-aduser, where I can just copy and paste them onto the powershell console and run then, but for cipts with a few lines of code, do you have to save it as a specific file, and then "run the file"? If I add all the above to a single line of text and try executing that i get errors.
Watch Question

Exchange Experts

Please copy the above content into notepad save the file as Name.ps1 (extenstion should be ps1)

Then Open Exchange Managment Shell from There you can run the above .ps1 script

To Execute
[PS] C:\Path of saved Ps1 Script>.\name.ps1

For Example [PS] C:\>.\backup_report.ps1

While Executing script add .\ on the starting of script.
Top Expert 2014
Even without saving it to file, you should just be able to copy the above code and paste it as is to PS console to run it (may have to press Enter a couple times after).
Will SzymkowskiSenior Solution Architect
Most Valuable Expert 2015
Top Expert 2015
If you are running this as .ps1 then you are also going to need to change the Execution Policy as well. Restricted is the default Execution Policy and you will get errors trying to run the script.

Run Get-ExecutionPolicy

If you run this and it is set to Restricted then run the below command to change it.

Get-ExecutionPolicy | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned