[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More







Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.

Share tech news, updates, or what's on your mind.

Sign up to Post


I am trying to export users from about 300 groups to CSV. What is the best way and command to do this? DO I need to create a file before hand for the command to recognize the group names?
Problems using Powershell and Active Directory?
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

how to disable powershell ISE in windows 10?
i added powershell_ise.exe to the list of programs the user is not allowed to run in group policy, but it still allows them to run it.
the policy is correctly applied
In the query below, i am try to import AD dist groups(both distribution and security groups)  from a CSV, and would like to return the user name and email address and indicate whether the groups is regular distribution or a security group.  Is it possible to get these results?

Get-ADGroupMember "dist.grp" | select samaccountname | %{Get-ADUser $_.samaccountname -Properties mail} | %{write-output "$($_.samaccountname) `t`t  $($_.mail)"}

Manage Bitlocker keys for enterprise network, gather the keys and log any computers offline that resulted in not getting bitlocker key for that computer

below script is not working correctly for multiple computers to be checked for online connectivity write log, get bitlocker or else write log stating computername of machine that is offline, I don't know where I went wrong with my function for the log because all thats happening is log file shows date time stamp and nothing else and I'm not getting any other keys

function log($string){
write-host $string
$timestamp =  (get-date -format dd-mm-yyyy) + "|" + (get-date -format HHMMsstt)
$computers = get-content -path '\\computername\c$\users\admin\desktop\scripts\Laptops.txt'
if(Test-Connection -ComputerName $computer -count 1 -quiet){

log "$computer is online getting bitlocker key"
manage-bde -protectors -get c: -computername $computer > "\\computername\c$\users\admin\desktop\bitlocker\$computer.txt"
$logfile  = "\\computername\c$\users\admin\desktop\scripts\logs\devicesoffline.txt"
log "$computer is Offline"
$timestamp + " " + $string | out-file -FilePath $logfile -Append -force

This question is for a PowerShell guru!

I am trying to create an archival script to archive files on an SFTP solution.  This is a Windows 2016 system with PS 5

PS C:\Windows\system32> $PSVersionTable

Name                           Value                                                                                                          
----                           -----                                                                                                          
PSVersion                      5.1.14393.2515                                                                                                 
PSEdition                      Desktop                                                                                                        
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                        
BuildVersion                   10.0.14393.2515                                                                                                
CLRVersion                     4.0.30319.42000                                                                                                
WSManStackVersion              3.0                                                                                                            
PSRemotingProtocolVersion      2.3                                                                                                            

Open in new window

Using the below Powershell command, I am trying to change the drive but it fails with error: "drive is in used"
is there a way to force it to change as we can change in the Windows Dick Management Console
Get-Partition -DiskNumber 1 | Set-Partition -NewDriveLetter G

Open in new window

Thanks.... ;)
Looking for a powershell script that satisifies getting

Last modification date for AD accounts in an organistation

Want to use it to check AD accounts that haven't been modified in over a year

Have used lastlogon and lastlogontimestamp but looking for modification
I'm running Hyper-v in a 2012 R2 cluster.  (Note: this is NOT SCVMM)
I'm trying to get a list of all the VMs currently running on the Host I'm logged into and their respective possible owners. i.e. which cluster nodes they could potentially migrate to.  The reason is that I THEN want to set those VMs to only run on that particular host for patching purposes.  Once done I'll want to reverse it so the VMs can once again migrate when needed.  Here is the code and attendant error message.  I'm hoping someone can assist me with achieving my goal or at least point me in the right direction.

$VMs = get-vm
foreach ($vm in $vms)
	get-clusterresource -vmid "$VM.vmid" | get-clusterownernode

Open in new window

The error I am getting is:

Get-ClusterResource : Cannot bind parameter 'VMId'. Cannot convert value "Microsoft.HyperV.PowerShell.VirtualMachine.vmid" to type "System.Guid". Error: "Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."
At line:1 char:50
+ foreach ($vm in $vms) {get-clusterresource -vmid "$vm.vmid" | get-clusterownerno ...
+                                                  ~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ClusterResource], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.FailoverClusters.PowerShell.GetResourceCommand
I have a couple of systems here at my work that got the windows store and other apps (calculator) uninstalled.  I have been trying to run the powershell commands I have found in order to reinstall those but nothing seems to be working.  Other than reinstall the OS is there anything else I could try before doing something more destructive?  thanks.
What the best way to search for users with same firt name in Powershell ?

$user=john and then pull their samaccountname , givenname and sur name into a table csv file
Redefine Your Security with AI & Machine Learning
Redefine Your Security with AI & Machine Learning

The implications of AI and machine learning in cyber security are massive and constantly growing, creating both efficiencies and new challenges across the board. Check out our on-demand webinar to learn more about how AI can help your organization!

I have a script which scans all servers in AD and returns local group members. Can you help me to update script so that output format will be grouped by server with heading – Server name, Local Group Name, Members, Type?

# Define local groups to audit
$groups = "Administrators", "Remote Desktop Users";
# Add Active Directory powershell plug-in
import-module activedirectory;
# Get all servers from AD and ignore predefined list 
$adservers = get-adcomputer -filter {operatingsystem -like "*server*"} | where {$_.enabled -eq $true} | sort name;
# Loop through each server found in AD
foreach ($adserver in $adservers) {
    # Set server name from AD object
    $servername = $adserver.name;
    # Check if server is pingable
    if((test-connection -computername $servername -count 1 -quiet)) {
        # Loop through each group to audit
        foreach ($group in $groups) {
            # Define the localgroup in the correct format
            $localgroup = [ADSI]"WinNT://$servername/$group";
            # Get members of the local group
            $members = @($localgroup.Invoke("Members"));
            # Loop through each member found
            foreach ($member in $members) {
                # Define name and type of the member
                $memberName = $member.GetType().Invokemember("Name","GetProperty",$null,$member,$null);
                $memberType = $member.GetType().Invokemember("Class","GetProperty",$null,$member,$null);

Open in new window

Hi team,

Need a very basic power shell help.

I need to export a list of users from AD whose employeeType attribute has value Extranet. The Export CSV to have displayName, sAMAccountName, mail and employeeType.

Thanks, much appreciated.
I am trying to remove a hidden system directory recursively from different paths on a single server. For example:


Can I use a PowerShell or CMD one-liner to find and delete all instances of $DIRECTORY where path is dissimilar?

We have exchange 2007 and we migrated all the mailboxes to 0365 and now we are going to decomission the exchange server and there are 900 old mail boxes left on this server that is not required  .

Please let me know the easy way of deleting all the mail boxes
Is there any poweshell command to do this task.Or do i need to manually  go to Exchnage management console- Mailbox and highlight mailbox and remove?  and change the mailbox retention period?

Any help much appreciated.

I want to pin a Windows 10 application to the taskbar using Powershell.   I think syspin.exe will work to do this.   However, my problem is that the application is installed via an .appx and I can not find the location of the file to pin to the taskbar or the actual name to use as a parameter to syspin..
I have the following powershell script (see below) that gives me members of groups. Each group is exported individually to its own csv file. Knowing next to nothing about PS, how can I modify the script to have all the groups and member export into a single file?

Import-Module ActiveDirectory
$ouList = @(

$dc = "DC=$($ENV:UserDNSDomain.Replace('.', ',DC='))"
$ouList | ForEach-Object {
      Get-ADGroup -Filter * -Properties Description, DisplayName, GroupCategory, GroupScope, Member -SearchBase "$(If ($_) {$_ + ',' + $dc} Else {$dc})" -ResultSetSize $null | ForEach-Object {
            $group = $_
            $_.Member |
                  Get-ADObject -Property DisplayName, SamAccountName, UserAccountControl |
                  Where-Object {($_.ObjectClass -eq 'user') -and (($_.UserAccountControl -band $ACCOUNTDISABLE) -eq 0)} |
                  Sort-Object -Property SamAccountName |
                  Select-Object -Property `
                        @{n='Group Name'; e={$group.Name}},
                        @{n='Group Description'; e={$group.Description}},
                        @{n='Member SamAccountName'; e={$_.Name}},
                        @{n='Member DisplayName'; e={$_.DisplayName}},
                        @{n='Member UserAccountControl'; e={$_.UserAccountControl}},
                        @{n='Group DistinguishedName'; e={$group.DistinguishedName}} |
                  Export-Csv -NoTypeInformation -Path "C:\Scripts\$($group.Name).csv"
I am trying to clean up DNS and remove a ton of worthless Primary and Secondary zones on several 2012R2 servers. We have been playing with this PS but cannot get it to work properly.

$CSV = Import-Csv -Path "C:\_scripts\DNS\DelZones.csv"
foreach ($zone in $csv)
{ Remove-DnsServerZone -name $Zone -PassThru -verbose -whatif}

What we get back is when running it is:
Remove-DnsServerZone : The zone @{Zone=DummyZone.Dum} was not found on server DNS-03

So DummyZone.Dum is listed in the CSV and is hosted on DNS-03, so it seems to read the CVS, but adds @ and brackets {} which causes it to not be found. Any suggestions on how to fix this? I have used the command successfully with a single domain just not with the CSV.

Or if you have a different approach that would be great as well. Thanks in advance.
How can i run the query below against a csv file?  Or import the list from the CSV to run against the query;

Get-MailboxPermission -Identity <mailbox> | where  { ($_.AccessRights -eq "FullAccess") -and ($_.IsInherited -eq $false) -and -not
($_.User -like "NT AUTHORITY\SELF") } | ft @{Name="Identity";expression={($_.Identity -split "/")[-1]}}, User –AutoSize

Many thanks!

I'm looking for a script that will loop through thousands of directories.  If there are less than 10 subdirectories in a folder, it will move that parent folder with the subfolders to another location.

Example:  under this share, \\network_share\test, is the structure below:
\\network_share\test\folder1\test\subfolder1, subfolder2, subfolder3, subfolder4, subfolder5, subfolder6, subfolder7, subfolder8, subfolder9
\\network_share\test\folder2\test\subfolder1, subfolder2,subfolder3, subfolder4, subfolder5, subfolder6, subfolder7
\\network_share\test\folder3\test\subfolder1, subfolder2, subfolder3, subfolder4, subfolder5, subfolder6, subfolder7, subfolder8, subfolder9, subfolder10

Since folder1 and folder2 have less than 10 subfolders, folder1 and folder2 along with their subfolders will be moved to \\network_share\test2.  Note: it will need to search down two subdirectories to get the count.

Thank you
Simplify Active Directory Administration
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

Running the following cmdlet

Get-DnsServerResourceRecord -ZoneName $zonename -RRtype PTR -ComputerName $dc


Get-DnsServerResourceRecord : Invalid class
At line:4 char:12
+ $records = Get-DnsServerResourceRecord -ZoneName $zonename -RRtype PT ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (PS_DnsServerResourceRecord:root/Microsoft/...rResourceRecord) [Get-DnsServerResourceRecord], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041010,Get-DnsServerResourceRecord

Not sure why

Any help much appreciated
I am new to Automation testing, i have to write automation scripts for File Router service, this service has a source/input folder and a destination folder, based on the file name, extension the file(s) will be moved to respective destination.

This is a windows service. based on the configuration this router will move the files

What will be better technology stack for this requirement, when i run the tests , they should be able to copy, verify whether it is copied or not

I am trying to figure out the best way to do the following. I want to set the startup type of System Event Notification Service (SENS) to Automatic, then check to see if it was set correctly, display a message of either success or unsuccessful, followed by restarting the service. Currently I have:

# Set SENS Service StartupType to Automatic
    write-Host "Setting System Event Notification Service Startup Type to Automatic on $ComputerName..." -ForegroundColor 'White'
    Try {Set-Service -Name SENS -StartupType Automatic}
    Catch {$TimeStamp = (Get-Date).ToUniversalTime()
        Write-Host "Could not set System Event Notification Service Startup Type to Automatic on $ComputerName. Exception Error: $($_.Exception.Message)" -ForegroundColor 'Red'}
    #Check is SENS service is set to automatic
    $SENService = Get-Service -Name SENS
    If ($SENService.StartType -eq "Automatic") {Write-host "System Event Notification Service is set to Automatic on $ComputerName..."}
    If ($SENService.StartType -ne "Automatic"){Write-Host "System Event Notification Service is not set to Automatic on $ComputerName..."}

    # Restart SENS Service
    Write-Host "Restarting System Event Notification Service on $ComputerName..." -ForegroundColor 'White'
    Try {Restart-Service -Name SENS -Force -ErrorAction Stop}
    Catch {$TimeStamp = (Get-Date).ToUniversalTime()

Open in new window



$dls = Get-DistributionGroup -ResultSize Unlimited
foreach($dl in $dls)
 $mem = get-distributiongroupmember -identity $dl.name
 if($mem.count -eq 0)
 write-host $dl.name

how do I pipe above command to csv file
Hi, i have script for get all groups that a user is member of. Works correctly, but  i cant export it to csv file. output shows PS terminal just. any ideas what i exactly must  add to script?


Import-Module ActiveDirectory
Get-ADUser -SearchBase "OU=Users,DC=domain,DC=local" -Filter * | foreach-object {
write-host "User:" $_.Name -foreground green
    Get-ADPrincipalGroupMembership $_.SamAccountName | foreach-object {
        write-host "Member Of:" $_.name

MyText MyText2 (bvbv)(jj3)
MyTex MyTe (123qwe)(jj3)
MyTex MyTe (123qwe)

I need to test these strings.
If line include (jj3) - then return (bvbv) (1. line)
If line include (jj3) - then return (23qwe) (2. line)
Nothing returned (3. line)

Thanks in advance






Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.