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

Dear expert

In powershell, is it possible to invoke a variable in a variable? For exemple: $flower = ($color = "Red", leaf = "4", $weight = "50g") ?

Introduction to R
LVL 13
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

I need to get some help exporting a mailbox to PST file. I tried following several articles but in those articles there is an image where export mailbox to PST is an option but when I click on that, the only option I see is to export to CSV.
Any ideas on how I can get the mailbox exported to PST?   I did also try to use the Exchange management shell and do a export mailbox powershell command but the command comes back and says it is invalid.
I need some serious powershell assistance, I actually know absolutely nothing about it and need to hopefully convert a .bat to a .ps1.  We need to extract info of a user, the computer, date and time they are logging on and write to a file.  Below is the old .bat:
commands from bat file
echo %username% logged onto %computername% on %date% at %time% Local >> \\Computer1\test\test1\%username%.txt
ping %computername% -n 1 >> \\Computer1\test\test1\%username%.txt
Is there a way to remove "Groups" from the ribbon bar in Outlook 2016 through Group policy or other means?

Here is an image, which I can manually remove:
Hi EE,

If I had the following code

$batchfiles = (gci -path .\downloads -filter "*batch*.csv").fullname
foreach ($file in $batchfiles){
  $f = gc $file -ReadCount -1
  write-host "$($($f.tochararray().where({$_ -eq ""'""}) | measure).count) apostrophes in $file"
  out-file -FilePath $file -InputObject $f.Replace("'", '''')

Open in new window

How could I add a list of series directories for this code module to execute against? Ideally, I would like to read the directories from .txt file e.g Directories.txt with each new line being treated a new directory.

Any assistance is welcome.

Thank you.
I am trying to use powershell to to get all active directory users that have a certain attribute "title:staff" and are NOT a member of a specific group "all-staff".?

Things tend to time out as there are plenty of users in the same OU, so limiting by searchbase doesn't really help, and Get-ADPrincipalGroupMembership does not work - having to expand members property into a file to get all members.

The problem is how do I get all non-members that also have that particular attribute? What would the filter look like, and would it have to be done with some sort of a "foreach" operation, so it is split into individual commands that won't time out, even if they take longer as a whole?

maybe if I get a list "A" of all people with the attribute, and then check against list B that has all existing all-staff members, and if in A and NOT in B output "name" to a specific file?

Or something completely different?
Hello experts,

I am looking for a procedure to copy the various .log files which contains at least one line that start with : 1; and finish with ;17 :

AsOfDate variable required in order to exclude files older than this date (Creation or Modified date).

Windows batch or Powershell approach are more than welcome
If you have questions, please contact me
Modify existing Powershell to delete Bak files  X number of days based on generated content  (csv log) report with function to send report after removal.

I need Powershell script to ready csv log "fullname" column and remove any bak files folder older then 5 days from remote servers (computername column).
Below i included script to generate that csv log report.  Perhaps this script can be modified to do what i need in the above description.

This is csv log report

#TYPE System.Management.Automation.PSCustomObject                        
ComputerName           Name          FullName                                Size              Created
RTDB101                  Brie.bak         \\RTDB101\E$\Brie.bak      939.40 MB      9/23/2019 15:16
RTDB101                  SFWT.bak        \\RTDB101\E$\SFWT.bak      2,729.45 MB      9/23/2019 15:16
CDB102                         RES.bak        \\CDB102\E$\RES.bak      4,343.22 MB      8/12/2018
CDB102                        DEW.bak      \\CDB102\E$\DEW.bak      1,245.87 MB      10/10/2019
RDER103             WERT.bak      \\RDER103\E$\WERT.bak      1,235.87 MB      5/23/2019 0:00
RDER103            WERTY.BAK      \\RDER103\E$\WERTY.BAK      935.40 MB      5/23/2019 0:00

This is the script to generate this report.

$ComputersPath = "C:\Audit\computers.txt"
$LogPath = "C:\Audit\"
$LogFile = Join-Path -Path $LogPath -ChildPath BakFileReport.csv
$sendMailMessageParams = @{
      Smtpserver = "xxxxx.xxxx.xxx.xxx.net"
      From =       "BackupFileChecks_noreplay@xxxx.com"
      To =         "xxxx.xxxxn@xxxx.com"
      CC =         "yyal.yyyyan@yyyyys.com"
      Subject =    "Database Backup …
Bulk rename of TXT files. What I am hoping is someone will have a bat/powershell script that will renames 000's of TXT files. For example I have the following

and so on

What I want to rename them to is

Laptop 100
Laptop 101
Laptop 102

Would someone happen to have a script that will do this from a certain folder


Hello, I am in need of a script to remotely gather a list of all scheduled tasks that are executing powershell scripts - .ps1

I have about 1000+ computers which have multiple .ps1 files and I need to collect them along with their status, lastruntime, author, description. Below is the url to a nice posh script. However, I only need to get the tasks that fire a .ps1. This one below grabs all the running tasks.

Exploring ASP.NET Core: Fundamentals
LVL 13
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

is there a way to automatically answer NO to All in a powershellscript
I made a script to automatically delete files older than 7 days and empty folders.
But sometimes I get the question "Confirm
The item at Microsoft.PowerShell.Core\FileSystem::xxxxxx has
children and the Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue?
I want to automaticaaly answer NO to ALL on this... but I can't seem to find how to do this...

the script I use is...

	$foldersfile = ".\folders.csv"
	$folderpaths = Import-CSV $foldersfile -delimiter ";"

        ForEach ($folderpath in $folderpaths){
                       Get-ChildItem -Path $Path -Filter 'thumbs.db' -Force -Recurse |   remove-Item -force
                       $dirs = gci $path -directory -recurse | Where { (gci $_.fullName).count -eq 0 } | select -expandproperty FullName
                       $dirs | Foreach-Object { Remove-Item $_ }
                       #delete the thumbs.db files
                       write-host "folder done"
                       Get-ChildItem -Path $path -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-7))} | remove-Item
                       write-host "files done"
                } while ($dirs.count -gt 0) #end doWhile
        }#end foreach

Open in new window

I have a script to create an AD user and add to its respective security groups, this script works 80% of the time without issues, but sometimes I have the problem that It can not add the user to his group because it can not find the recent create user.  If I add a delay it fixes the problem.  I want to fix it without adding the delay, any suggestions

function New-OPAdDomainStudent
   Short description
   Long description
   Example of how to use this cmdlet
   Another example of how to use this cmdlet
        $HomeFolderPath = "\\myd-fileserver.mydomain.com\students$",
        $HomeDrive = "H:",
        $OU = "DOMAIN Students"

        $EmailSuffix = "@students.mydomain.com"
        $Email = $SamAccountName + $EmailSuffix
        $HomeFolder = Join-Path -Path $HomeFolderPath -ChildPath $SamAccountName
        $OuDn = (Get-ADOrganizationalUnit -Filter {Name -eq $OU}).DistinguishedName
        if ($OuDn -eq $null) {
            log -message "Unable to find OU $OU, exiting" -level Error
        $Password = "Welcome"
        $EncryptedPassword = ConvertTo-SecureString $Password -AsPlainText -Force
        log -message "Creating account $SamAccountName" …
Having trouble with using a variable as a "-like" attribute in a filter of a PowerShell Query. It seems like it is taking the variable name  as a string, as opposed to its actual value, or I'm  I doing something else wrong?

for example, if I want to get a list of users with first name including the characters " Jo"

this works :

get-aduser -filter {givenname -like "*jo*"}

this doesnt:

$firstname = "jo"
get-aduser -filter {givenname -like "*$firstname*"}

I know I am missing something fundamental, just don't know what it is.
What is the best way to get a list of active directory users via ADSI? Typical powershell cmdlet is Get-AdUser -filter *, where it returns attributes DistinguishedName, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName by default. What is equivalent command in ADSI?
I found this one, but it is not returning anything, i'm just getting >> context in my CLI. If i save this to file i can run it as ./file.ps1 and it works. So to finalize i just need it to run in powershell without creating file and do it on remote machine.
$ACCOUNTDISABLE       = 0x000002
$PASSWORD_EXPIRED     = 0x800000

$searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person))"
$searcher.FindAll() | % {
  $user = [adsi]$_.Properties.adspath[0]
  New-Object -Type PSCustomObject -Property @{
    SamAccountName       = $user.sAMAccountName[0]
    Name                 = $user.name[0]
    Mail                 = $user.mail[0]
    PasswordLastSet      = [DateTime]::FromFileTime($_.Properties.pwdlastset[0])
    Enabled              = -not [bool]($user.userAccountControl[0] -band
    PasswordNeverExpires = [bool]($user.userAccountControl[0] -band
    PasswordExpired      = [bool]($user.userAccountControl[0] -band

Open in new window

Would anyone happen to have a powershell script to check a bunch of computers AD member of groups from a populated txt file and output to a csv?

Thanks in Advance

Don't laugh...

I have a new client.  They have four computers in the office and the owner refuses to allow them to connect to the internet.

Of course, they have email so once a day, the users can connect, check mail, reply, then get off of the internet.

My fix has been showing the users how to change the default gateway to get them on and off, but that's too many mouse clicks.

I'd like a powershell or something that'll be like an on/off switch.  Double click it, you're on, double click it again, you're off...something like maybe diable NIC or something.

I'm lazy.

Anyone help me out with that?


I have a pretty large distribution list that has 100s of users. The old IT Team did not do a good job of managing these DLs and now the DL has dozens of users that are off boarded/disabled. So any time you send an email you get the dreaded DNR from those users. Logically I am thinking that i need to first extract unto an CSV file all current users from that DL (Samaccountname). Then I can take that data and run it through another script that will isolate all disabled users. Then take that data and run another script that will strip all AD memberships off of those users that would include that distribution list. Am I thinking of this correct logically or is there an easier method to get this accomplished?
Requirement :

In CSV file I want to check three scenarios.

First : Find the Columns which have Header Empty and Data in the Column and rename the Column Header as Temporary Header
Second : Find the Columns which has Header but not the data in the Column (do nothing to these columns)
Third : Find the Columns with No Data at all and delete

Finally Convert CSV  to XLsx format and save the file name with Time stamp  like Filename_YYYY_MM_DD_HHmm (processed time)

I've got a ps1 file with a couple of functions inside. Now I'd like to run one of these functions as a job. Is that possible? (I know how to run the whole script as a job but I'd like to know if it's possible to run just one function as a job) Thanks
Rowby Goren Makes an Impact on Screen and Online
LVL 13
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

I am working on requirement.

Where the csv file has data in only one column. but i want to transpose it

Before each cell value in one column:


Expected output in each cell value in rows in csv file
XSW PERT WEr wer orld  jss

Using Pwershell script
need to click the Tick box on Managers can update member list in Active directory for groups under an OU.
Please note: All I need is, for the check box to be selected under a OU with all groups located under it.  I already have the username attached to the managedby attribute
I have a previously script created but is not working.  This script runs and throws no errors, but check box is still not selected

Import-Module ActiveDirectory
$searchBase = 'OU=Groups=domain,DC=com'
Get-ADGroup -LDAPFilter "(&(objectcategory=group)(managedBy=*))" -Property managedBy -SearchBase $searchBase | ForEach-Object {
      $manager = Get-ADUser -Identity $_.managedBy
      Write-Host "Processing $($_.Name) (managed by '$($manager.SamAccountName)')"
      $acl = Get-Acl -Path "AD:\$($_.DistinguishedName)"
      $newAce = New-Object -TypeName System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList `
      Set-Acl -Path "AD:\$($_.DistinguishedName)" -AclObject $acl

I'd like to be able to run a script against one OU at a time to find all the accounts that are:

Password Expired
Account is NOT disabled

I dont want to include accounts with the Password Never Expires
I have a powershell script that runs in two parts the first part reboots a windows server 2008 R2 box this part works great, the second part of the script logs in a domain user account with autologon.exe then runs an executable with various parameters then sends an email with the process id and true/false state of of the process id. The script works fine wrapped around a windows task scheduler entry. The issue is it runs in the background and does not display the exe window on the desktop. We have to be able to  interface with the program.  How do i make this script run interactively on the desktop? Below is the powershell script.

# Bert 7-14-18 Autologon to OSP server and run OSP web server GUI and web services

# =============================================================================================
# Autologon to Sage user account
start-process c:\script\autologon.exe -ArgumentList "test","mydomain.com","test2019","/accepteula"
# =============================================================================================

# =============================================================================================
# Set path location
set-location "c:\sage\sage 100 2018 web engine\webeng\home\"
# Start ProvideX web config GUI
.\pvxwin32.exe c:\sage\sage 100 2018 web engine\webeng\home\webcfg.ini *web/webcfg
# Start base launcher
.\pvxwin32.exe webhide.ini *web\webserv
# Start MAS90 web server instance
.\pvxwin32.exe webhide.ini *web/websport -ARG "MAS90"

Open in new window

Microsoft Windows PowerShell ISE not working.  It just sits showing the attached  screen.  How do I fix this???
I need to enable or disable account on active directory domain controller (Server 2012) through powershell wmi:
1. I tried using command: wmic useraccount where "name='myusername'" set disabled=true
It returns an error:
Updating property(s) of '\\MYDCONTROLLER\ROOT\CIMV2:Win32_UserAccount.Domain="
Description = Generic failure

Open in new window

2. I tried using command:
PS C:\Windows\system32> Get-WmiObject Win32_UserAccount -filter "LocalAccount=False"|?{$_.name -eq "userName"} |%{$_.disabled=$true;$_.passwordChangeable=$true;$passwordrequired=$true;$disabled=$true;$_.put()}
This returns error:

Exception calling "Put" with "0" argument(s): "Generic failure "
At line:1 char:174
+ ... isabled=$false;$_.put()}
+                    ~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Open in new window

I found this command in
Any ideas? I know how to use Get-aduser or other commands, but it need to be done via wmi






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.