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

Hi All I'm trying to mass important a csv list of users to a shared mailbox with the following script.

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn;
Import-Csv c:\temp\add.csv | foreach {
Add-MailboxPermission $_.mailbox -User $_.Name -AccessRights:FullAccess -confirm: $false
Add-ADPermission -Identity $_.mailbox -User $_.Name -AccessRights ExtendedRight -ExtendedRights "send as"

Open in new window

The add-mailbox portion works fine but, am getting this error for the second part

<mailbox> wasn't found. Please make sure you typed it correctly.

Format of csv file is like so

name | mailbox being added to
username | mailbox being added to

where "mailbox being added to" represents the target mailbox for each corresponding user in the csv file.
Any idea what I'm doing wrong here?
Become a Microsoft Certified Solutions Expert
LVL 12
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Hello Powershell Experts,

I think I have asked a similar question in the past, but I can't find it.  I have been tasked with finding all of the distribution groups in our domain and then getting a list of all the user in each group.  The following Powershell code gets the results I want and displays them to the screen in the format that I want:

$DistributionGroups = get-adgroup -filter 'GroupCategory -eq "distribution"' | sort samaccountname

foreach ($DistributionGroup in $DistributionGroups)
        Write-host $DistributionGroup.name
    Write-Host "---------------------------------------"
    Get-ADGroupMember -Identity $DistributionGroup.SamAccountName | select name | sort name
    Write-Host ""

My question is how can I get this information into a text or CSV file?
I am attempting to search all mailboxes using powershell in exchange 2013 for a attachment or subject would probably work also. I can seem to get it to run
Get-Mailbox | Search-Mailbox -SearchQuery 'subject or attachment name' -TargetMailbox "Discovery Search Mailbox" -TargetFolder "AllMailboxes-Election" -LogLevel Full

It breaks on "discovery search mailbox" I have tried it like this also "DiscoverySearchMailbox"

Is there a powershell script for downloading the latest security update for an OS. We have windows 2012 R2, windows 2008 R2, depending on the OS type and architecture, I want to download the latest security update, I already have a script for installing the updates by copying the patch on the server then install using psexec.

Thank you in advance,


When I run an export from active directory via powershell, it doesn't bring in the é letters or anything, how can I force it to do that rather than the  Eléctrico that it's giving me. Essentially it should be Eléctricos


We have the below script in place that's reminds staff to complete their timesheets. This is run from scheduled tasks on each machine. Does anyone know how we can do the following.

1. Stop the blue powershell console from flashing up before the message box appears.  I've tried -windowstyle hidden but that doesn't appear to work.
2. Change the options in the message box that appears. It would be good if the Yes button text could be changed to Complete (or Review) and the No button to Ignore

Code below, thanks

$currentUser = [System.Environment]::UserName
$IE = New-Object -ComObject internetexplorer.application

$strFilter = $("(&(objectCategory=user)(SAMAccountName={0}))" -f $currentUser)

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1
    $objSearcher.SearchScope = "SubTree"
    $objSearcher.Filter = $strFilter

$colResults = $objSearcher.FindOne() 

if ($colResults.Length -eq 1)

    $employeeID = $null
    [int32]::TryParse($colResults[0].Properties["EmployeeID"], [ref]$employeeID) | Out-Null

    if ($employeeID -gt 0)

        $svc = New-WebServiceProxy -Uri "http://pods.intranet.company.com/timesheets.asmx?wsdl"

        $hasOutstanding = $svc.hasOutstandingTS($employeeID)
        $hasToApprove = $svc.hasToApproveTS($employeeID)

        if ($hasOutstanding -or $hasToApprove)

Open in new window

In Exchange 2013, I am trying to set room resources so that all staff can view/review. Using powershell I enter:

Get-Mailbox | where{$_.RecipientTypeDetails -eq "RoomMailbox"}  | Add-MailboxPermission -User "Outlook Resource Administrators" -Accessright Fullaccess

I get the following error:

Get-Mailbox : The term 'Get-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-Mailbox | where{$_.RecipientTypeDetails -eq "RoomMailbox"}  | Add-MailboxPer ...
+ ~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-Mailbox:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
                                                           Get-Mailbox | where{$_.RecipientTypeDetails -eq "RoomMailbox"}  | Add-MailboxPermission -User "Outlook Resource Administra

Is there some type of library add-in that I need to get for power shell?

I want to have access to a Windows share with Powershell Core on a Ubuntu system.

So I tried this :
$cred = Get-Credential -UserName 'domain\user'
remove-item -path // -Credential $cred

Open in new window

I have an error :
Remove-Item : Cannot retrieve the dynamic parameters for the cmdlet. The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without specifying credentials.

Open in new window

Anyone can help me please ?

Thank you
I would like to change this part of a Powershell script so that it looks into the current folder of where it is being run from to pull the text.txt file and the attachment...

      # Invokes the Send-MailMessage function to send notification email
      $splat = @{
            From =                  'email1@mail.com'
            To =                  Get-Content -Path 'text.txt'
            SmtpServer =      'mail.smpt.com'
            Subject =            $subject
            body =                  $MessageBody
            BodyAsHtml =      $true
            Attachment =      'Attachment.pdf'
      Send-MailMessage @splat
Python 3 Fundamentals
LVL 12
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Hi ,

i have working script..
i want to put additional checks in the script to check for files and proceed further.
it should check for files after it checks for source folder.
if all three files available then proceed further to run remaining lines of checking backupfolder.
if even one file is missing or all missing it should write log the missing files and exit

Files names to check-

$logdate=Get-Date -Format ddMMMyyyy_HHmmss
$Logfile = "E:\Logs\FileProcessing_$logdate.txt"

function LogWrite ([string]$logstring)
   Add-content $Logfile -value $logstring

#Zip Files

#check if source exists
if(!(Test-Path $sourcefolder)){
    $msj="The source folder ""$($sourcefolder)"" doesn't exists. Exiting..."
    LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) ERROR:`t$msj"
    LogWrite -ForegroundColor Red $msj
    exit -1

#check the target folder or create it
if(!(Test-Path $backupFolder)){
    $msj="The target folder ""$($backupFolder)"" was created"
    LogWrite "$( Get-Date -Format "yyyy-MM-dd HH:mm:ss" ) EXECUTE:`t$msj"
    LogWrite -ForegroundColor Magenta $msj
    New-Item -ItemType Directory -Path $backupFolder | Out-Null
foreach($file in (Get-ChildItem -File $sourcefolder -Filter "*.xml" -Recurse)){
    $date = Get-date -Format "ddMMyyyy_HHmmss"
    $destinationFile = "$($FILE.Directory.FullName)\$($file.Name).zip"
    $MoveFile = …
I was helped by an Expert on the script below .. I didn't plan on it but my CSV has blanks on some of the attributes... can someone
assist modifying this so if there is a blank in one of the fields?

so lets say a user only needs 3 of the 4 values below updated , the script below does not work .. it only works if all four fields have values to update.

Import-CSV -Path "$env:SystemDrive\Test\temp.csv" | % {
  Set-ADUser $_.Username -replace @{'msExchExtensionAttribute24' = $_.msExchExtensionAttribute24; 'msExchExtensionAttribute25' = $_.msExchExtensionAttribute25; 'msExchExtensionAttribute26' = $_.msExchExtensionAttribute26; 'msExchExtensionAttribute27' = $_.msExchExtensionAttribute27; }

Open in new window


Im trying to develop a script that will strip the msexchangeguid attribute from a particular OU only, once a week as a scheduled task.
Im almost there.

The first part of the script successfully identifies all users in that OU that has a non-NULL msExchangeGUID
Get-ADUser -SearchBase "OU=Disabled-Objects,dc=my,dc=domain,dc=com" -filter * -Properties * | ? {$_.msExchMailboxGuid -ne $null}

Open in new window

The next part of the linked script will just give me the SAMAccountNames of those users with a non-Null msExchangeGUID from the above command
Select-Object SamAccountName

Open in new window

Put the final part of setting the attribute to be Null (0000) doesnt take the SamAccountNames for action
Set-RemoteMailbox  -ExchangeGUID 00000000-0000-0000-0000-00000000000

Open in new window

Here it is in one non-functioning line.

Get-ADUser -SearchBase "OU=Disabled-Objects,dc=my,dc=domain,dc=com" -filter * -Properties * | ? {$_.msExchMailboxGuid -ne $null} | Select-Object SamAccountName | Set-RemoteMailbox  -ExchangeGUID 00000000-0000-0000-0000-000000000000

Open in new window

I also thought about i could put the output of the first two lines into a text file, that I think use as a variable
Get-ADUser -SearchBase "OU=Disabled-Objects,dc=my,dc=domain,dc=com" -filter * -Properties * | ? {$_.msExchMailboxGuid -ne $null} | Select-Object SamAccountName > users.txt

Open in new window

$users=Get-content users.txt
Foreach($user in $users){
get-aduser $user| set-aduser -clear msExchMailboxGuid

Open in new window

But the users.txt has trailing whitespaces after the username so the  
get-aduser $user| set-aduser -clear msExchMailboxGuid

Open in new window

looks like
get-aduser "USERNAME        "| set-aduser -clear msExchMailboxGuid

Open in new window

when it runs. It fails on the excess whitespaces.

Any help from Powershell gurus out there?
Powershell one-liner or script that can find the latest changed file recursively in a folder, per folder 1 deep.  
That might not make sense, I have shared folder "Shared", in that folder are 200 more folders, many of which may not have been used for a very long time. I'd like a list of the latest changed file (anywhere in that folder, or its own subfolders) in each of the 200 folders with the date. I hope that makes sense.
I want to create a standard menu of options as it were, so that by clicking on a specific area, number, phrase on the menu, that it will trigger a .bat or powershell script to run.
I was hoping for something simple I could copy and paste on any computer, with the expectation that the paths to run the .bat or powershell scripts will have standard locations.
Perhaps and html file (like a web page file), where I could run each script would work, where I could manually add any new scripts etc..
I would like to change this script, so that instead of hard coding in the destination email addresses, it will look into a flat txt file and use the email addresses listed in that specific file instead.

#-------DO NOT MODIFY-------#
    #Yesterdays Date
        $date = ((Get-Date).AddDays(-2)).ToString("MMM/dd/yyyy")

#-------MODIFY AS NEEDED-------#
    #Mail Subject
        $Subject = "Report: "+$date+" REVISED "
    #Body of Email
        $MessageBody = "REVISED - Report for $date. Thank you."

      # Invokes the Send-MailMessage function to send notification email
Send-MailMessage -From 'email1@mail.com' -To 'email2@mail.com', 'email3@mail.com', 'email4@mail.com' `
  -SmtpServer 'smtp.mail.com' `
  -Subject  $subject `
  -body $MessageBody `
  -BodyAsHtml `
  -Attachment 'C:\Attachment\Attachment.pdf'

Thanks in advance for your assistance
I am, at best, a novice user when it comes to writing Powershell scripts, so any simplified explanation to this question would be appreciated.
I am accessing one of our vendors API services. In order to access it, I need to generate an authentication token. I have the url to send the request to, and I have the username and password. What I am not sure of, is how to write the script to retrieve the token. Is there a "generic" method to do this?

Again, feel free to break it down to the most basic of terms. I won't be offended. :)

Thank you in advance.
The new team technician did not realize that IIS was out (and needed to be restarted) and resolved to delete the Powershell virtual directory (do not ask me why, it just did). Now when I open the Console or the Shell I can not connect to Exchange 2010. When I tried to add this virtual directory again through normal Powershell, with the imported Exchange snap, I get the error below:

IIS without Powershell VDir:
Error recreating Powershell VDir:
With IIS Metabase Explorer no more Powershell VDir configs:
Some way to reinstall this Virtual Directory?
Export Exchange Calendar to PST
Export Calendar to PST From Exchange 2016, 2013, 2010 to Move Specific Appointment and meeting details with Date Range Command to extract details only from Live Exchange Environment. Also, Export Exchange Calendar to PST using Powershell Command and Exchange Admin Center.
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!

Dear expert.

I need help with this code:
$time = ((Get-Date).Adddays(-100))
$pathlog =  "\\server\log_*"
$Pattern = "^01","^03"
$results = Get-ChildItem $pathlog -Recurse | where-object {$_.LastWriteTime -ge $time} |
	Select-String -Pattern $Pattern | 
	Group-Object Path |
	% { #Foreach-object alias
		$_.Group | Select-Object Line
if ($results) {
$results | Out-File D:\wei_test\resulttest.txt
$text = Get-Content -Path D:\wei_test\resulttest.txt
$text.Substring(148, 182)
$results = 1

Open in new window

Now I would like to grab the Out-File result text line position  148 to 182 in each lines and show it in the powershell window.
I got a error:
Exception calling "Substring" with "2" argument(s): "startIndex cannot be larger than length of string.
Parameter name: startIndex"
At line:37 char:1
+ $text.Substring(148, 182)

Kinda stuck with this. thx for the help.
My Exchange URL needs to be updated in a live environment to the new domain URL's.  I want to know if there is draw backs or no-no's doing this.  
Also do any of the IIS Applications need to be restarted?

I plan to use powershell to quickly loop through and change all the URL's I need to match my new SSL cert.  
I am using a SAN Cert issued by GoDaddy that includes 4 of the new addresses plus one old URL.

looking for power shell Script to Compare Disk Space ,Patches and service status before and after reboot  of windows servers
or if there is any other better solution to do pre-post checks during ms patching
Please help to share power shell  script To check last reboot for windows servers (mentioned in server list ) with user id used for reboot

In Exchange O365 GUI, in Contacts  I see contact type: mailcontact and mail user. What is the difference?
What is the difference between contact and mailcontact in  Exchange?






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.