Powershell

15K

Solutions

55

Articles & Videos

7K

Contributors

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

Need help with combining these script together if it can be done, any help is appreciated.

Also want to mention, this will be for use in a large environment, 20k or so, and I plan on having as a scheduled task.  Not sure if this is an efficient script or will be too intrusive.  Input is welcome.

The first script goes through all mailboxes in ExO, and if it's a member of a group "MobileUsers", it enables activesync and owafordevices, for everything else it disables these features.

Import-Module MSOnline
$mailboxes = Get-CASMailbox -resultSize unlimited
$asusers = Get-DistributionGroupMember -Identity 'MobileUsers'

$asguids = @()
foreach ($user in $asusers) {
    $asguids += $user.GUID
}

foreach ($mailbox in $mailboxes) {
    if ($asguids -contains $mailbox.GUID ) {           
        if ($mailbox.ActiveSyncEnabled -ne $true) {     
            $mailbox | Set-CASMailbox -ActiveSyncEnabled $true –OWAforDevicesEnabled $True
        }
    }
    else {
        if ($mailbox.ActiveSyncEnabled -ne $false) {   
            $mailbox | Set-CASMailbox -ActiveSyncEnabled $false –OWAforDevicesEnabled $false
        }
    }
}

Open in new window


The second script (which can be based off of the same "MobileUsers" group, I have to set an license SKU in ExO for intune.  The header from the input file is:   "UPN","usagelocation","SKU"#

$users = import-csv .\intune.csv -delimiter “,”
foreach ($user in $users)
{
$upn=$user.UPN
$usagelocation=$user.usagelocation
$SKU=$user.SKU
Set-MsolUser -UserPrincipalName $upn -UsageLocation $usagelocation
Set-MsolUserLicense -UserPrincipalName $upn -AddLicenses $SKU
}

Open in new window

0
Problems using Powershell and Active Directory?
LVL 6
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

I use my own laptop at my customer site.  I have a network logon, but because my laptop is not a member of the domain (and I don't log on to the network) I am prompted for my credentials whenever I use some network resource (IIS, fileshares, Exchange).

At times, this becomes annoying.  The prompts for my credentials may popup behind other windows and I don't see them, etc.

Long story short, I'd like to have a PS that will map a drive (and then unmap it) for the servers with shares I most use to do this that I can schedule to run regularly from the scheduler so that the prompting is done in the background and I can just start using the shares (about a half dozen) I regularly use.

I've found commands for mapping and unmapping drives, but I don't see a syntax with a credential parameter, which won't work for this situation.  Can anyone provide an example or pointer to one that would workout?
0
Hi Experts,

Im new to powershell. I want to filter only to show Microsoft products installed in a machine and save it to a file. Below is the script Im writing. Is there anywhere i can fit where-object in it or any other suggestions.

Get-WmiObject -Class win32_Product -ComputerName $pc -Property name,vendor,version,installdate | ForEach-Object {
    '{0},{1},{2},{3},{4}' -f $env:COMPUTERNAME,$_.Name,$_.Vendor,$_.Version,$_.InstallDate
} | out-file C:\"$env:COMPUTERNAME"_SW01.txt

Open in new window

0
Hi,
I am migrating mailboxes over from Exchange 2010 to Exchange 2016.
Can someone tell me a powershell/Exchange Mgt shell command that will tell me which of my current users  have quotas over 1 GB?
I don't want to move my users from 2010-2016 and have them move into a smaller DB.

Thanks,
nacht
0
Hi,

Is there a way that I can add one EXTERNAL contact into a SHARED mailbox? In Office365 Exchange. Have a shared mailbox and want to add ONE user to the shared mailbox.

Thanks in advance

John
0
OK

I have a specific OU that I need to search users which are in 2 specific groups, I don't mind changing the group in the code and running it twice, that's not an issue at all.... What's the easiest way to achieve this because I'm at a loss....

This is the best I could come up with, any ideas?

$groupmembers = get-adgroupmember "BR-internetgroup" |

Get-ADUser -filter * -SearchBase "OU=BR,OU=HO,DC=net,DC=Comnpanyname,DC=co,DC=uk" | where-object {$groupmembers.distinguishedname -notcontains $_.distinguishedname}

Open in new window


Cheers

Alex
0
Hello Experts,

I'm in the process of disabing SMB1 server on all our environments and have only our Prod left.

I would like to be able to identify without installing Message Analyser/Wireshark if there's any SMB1 use and there's two powershell  commands which get close to what I need:

get-smbsession - shows all user sessions to the server, but not SMB version used
get-smbconnections - shows smb version/info for current user logged onto the server

Is there a way to show the SMB version for all the user sessions on the server? Possibly piping one of the above commands into the other?

many thanks,
Gareth
0
Working on a script that creates an o365 user via powershell and it's breaking when I try to append or combine text inputs to make new variables.

The following is supposed to take the inputs from the textbox input '$o365UserFirst.text', '$o365UserLast.text' and merge them into a $displayname for use later, then take the textbox input '$o365useralias.text' and add the domain at the end for use later. Then finally it uses the text inputs to make a new mailbox, but it errors out with a "Cannot bind argument ot parameter 'MicrosoftOnlineServicesID' because it is null" error. For some reason the first bits appear to be creating empty variables. This obviously isn't the entire script, but just the broken part.


             $displayname = ($O365UserFirst.text + " " + $O365UserLast.text)
            $O365UserEmail = ($O365UserAlias.text + "@domain.com")


            New-Mailbox -Alias $O365UserAlias.Text -Name $O365UserAlias.Text -FirstName $O365UserFirst.Text -LastName $O365UserLast.Text -DisplayName $displayname -MicrosoftOnlineServicesID $0365UserEmail -Password (ConvertTo-SecureString -String $O365UserPassword -AsPlainText -Force)
           
            $Results.AppendText("`r`n")
            $Results.AppendText("User Mailbox Created... Continuing Script")
0
We have windows 2016 Standard server which after installed updated got converted to a Data Center.
is there any way back to windows standard (I have Citrix VDA installed and configured on it)
without reinstalling windows from Scratch. Power Shell only allowed upgrade not a downgrade.
0
I have a exchange 2010, hybrid to exo 2013/office 365.  

I created an alternate authoritative domain in Office 365 only, not on-prem in 2010.

I'm trying to create a shared mailbox in exchange online but am not having much luck getting it to work, granting full rights.

I ran through this process to convert to a mailbox, then created and on prem object, change the exchangeGUID and did a sync.  It did not sync with Azure however, or read "Synced with Active Directory." in step 5.

Any idea's on this?  Do I need to create the domain and/or OU structure on prem for this to work?
0
Does Powershell have you tied up in knots?
LVL 6
Does Powershell have you tied up in knots?

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

Hello,

I am trying to use Get-ExchangeEnvironmentReport from this site (http://www.stevieg.org/2011/06/exchange-environment-report/). I have used this for Exchange 2010 with no issues. I am not sure if I am missing anything. When I try to use this with Exchange 2013 I get the following error. I cannot find the report anywhere. I appreciate your help!

######################################################

[PS] C:\Users\nimda\Desktop>.\Get-ExchangeEnvironmentReport.ps1

Security warning
Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your
computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning
message. Do you want to run C:\Users\nimda\Desktop\Get-ExchangeEnvironmentReport.ps1?
[D] Do not run  [R] Run once  [S] Suspend  [?] Help (default is "D"): r

cmdlet Get-ExchangeEnvironmentReport.ps1 at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
HTMLReport: .\Get-ExchangeEnvironmentReport.ps1
Exception calling "OpenRemoteBaseKey" with "2" argument(s): "The RPC server is too busy to complete this operation.
"
At C:\Users\nimda\Desktop\Get-ExchangeEnvironmentReport.ps1:361 char:3
+         $RemoteRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachi ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          :
0
can someone provide assistance with this script, we need to update this script to use an "input.csv" file  

we are trying to export all the groups for the users on the input.CSV file. this script works for a single

$Groups = (Get-ADPrincipalGroupMembership -Identity usera | Select-Object -ExpandProperty name) -join ','

get-aduser usera -properties memberof,samaccountname,givenname,surname | select samaccountname,givenname,surname, @{name="Groups";expression={$Groups}} | export-csv "c:\temp\ADUsers.csv" -Delimiter ";" -NoTypeInformation -Encoding UTF8

Open in new window

0
I need to disable VMQ

I am using command

Set-VMNetworkAdapter –ManagementOS -Name <VirtualNetworkAdapterName> -VmqWeight 0

how do I get the VirtualNetworkAdapterName
0
I found the following code to output some information from vCenter:

Get-VM |
Select Name,
@{N="Datastore";E={[string]::Join(',',(Get-Datastore -Id $_.DatastoreIdList | Select -ExpandProperty Name))}},
@{N="UsedSpaceGB";E={[math]::Round($_.UsedSpaceGB,1)}},
@{N="ProvisionedSpaceGB";E={[math]::Round($_.ProvisionedSpaceGB,1)}},
@{N="Guest";E=($_.Guest}},
@{N="PowerState";E={$_.PowerState}}, 
@{N="Notes";E={$_.Notes}} |
Export-Csv C:\Temp\report.csv -NoTypeInformation -UseCulture

Open in new window


The problem I am having is that the output of "Guest" returns output in the following format:

MyVirtualMachine:Microsoft Windows Server 2008 (32 bit)

What I would like is not to output the "MyVirtualMachine:" bit.  I've used the split command before to do something like this but I can't get it to work inside a hash table. Also I think I need to convert the "Guest" value to a string before I can use split.

I would appreciate advice on how to do this.  Thanks.
0
I cannot seem to find a way with PowerShell to distinguish between Office 365 Retention Policies and Label Policies.
NOTE: I am not speaking about Exchange Retention Policies at all for this question

Any ideas?
0
Hi,

I am trying to finish up a PowerShell script to where I am pulling a listing of groups from Active Directory and export them to a .csv file.  I need the script to also output the group-type (security, distribution).  Here is what I have so far:

Get-ADGroup -Filter {GroupCategory -eq "Security"} | ForEach-Object {
      $Group = $_
      Get-ADGroupMember -Recursive -Identity $_.DistinguishedName
} | Select-Object -Property `
            @{Name='GroupName'; Expression={$Group.Name}},
            @{Name='GroupType'; Expression={$Group.GroupScope}},
            @{Name='MemberName'; Expression={$_.Name}},
            @{Name='MemberSamAccountName'; Expression={$_.SamAccountName}} |
      Export-Csv -NoTypeInformation -Path 'C:\Group Listing.csv'

Thanks.
0
I have a text file which contains a list of userprinciplename of departed users.  Is there a PS command I could use to call this text file and remove their O365 licenses?

Thanks.
0
I'm trying to use PowerShell and robocopy to search a directory for specific files, based on extension, created within a date range, and then copy all files in that folder to a target directory. I'm looking for a way to get directory level one or two up from the folder I want to copy, so that I can pipe that to the robocopy job. Without this, I end up copying all the files from the source into a single target directory without the original folder structure.

Example of what I'm trying to get:
\\Share\Source\1\test.ext copied to \\OtherShare\Target\A\1\test.ext

What I have so far:

$srcPath = "\\Share\Source\"
$dstPath = "\\OtherShare\Target\A"

Get-ChildItem $srcPath -recurse -include *.ext | Where-Object {$_.CreationTime -ge "01/01/2017" -and $_.CreationTime -le "01/01/2018"} | ForEach-Object {robocopy $_.DirectoryName $dstPath /r:1 /w:1}
0
How to execute below script , found this in technet but due to lack of comments not sure on execution


# Initialize some variables used for counting and for output 
$From = Get-Date "20/11/2011" 
$To = $From.AddDays(1) 
 
[Int64] $intSent = $intRec = 0
[Int64] $intSentSize = $intRecSize = 0
[String] $strEmails = $null 
 
Write-Host "DayOfWeek,Date,Sent,Sent Size,Received,Received Size" -ForegroundColor Yellow 
 
Do 
{ 
    # Start building the variable that will hold the information for the day 
    $strEmails = "$($From.DayOfWeek),$($From.ToShortDateString())," 
 
    $intSent = $intRec = 0 
    (Get-TransportServer) | Get-MessageTrackingLog -ResultSize Unlimited -Start $From -End $To | ForEach { 
        # Sent E-mails 
        If ($_.EventId -eq "RECEIVE" -and $_.Source -eq "STOREDRIVER")
		{
			$intSent++
			$intSentSize += $_.TotalBytes
		}
         
        # Received E-mails 
        If ($_.EventId -eq "DELIVER")
		{
			$intRec++
			$intRecSize += $_.TotalBytes
		}
    } 
 
 	$intSentSize = [Math]::Round($intSentSize/1MB, 0)
	$intRecSize = [Math]::Round($intRecSize/1MB, 0)
 
    # Add the numbers to the $strEmails variable and print the result for the day 
    $strEmails += "$intSent,$intSentSize,$intRec,$intRecSize" 
    $strEmails 
 
    # Increment the From and To by one day 
    $From = $From.AddDays(1) 
    $To = $From.AddDays(1) 
} 
While ($To -lt (Get-Date)) 
#While ($To -lt (Get-Date "01/12/2011"))

Open in new window

0
Free Tool: Site Down Detector
LVL 8
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

does anyone know of a way, perhaps using one of the AD cmdlets, that will get the same info as a Microsoft baseline security analyser scan, in the "shares" section of the report, which gives both the share and directory ACL, but writes the results out to a CSV file so further filtering/analysis can be performed. MBSA does give what I need but the report is essentially read only, I need a way to filter the results as on some servers under review are hundreds of shares, so having it in csv would make that additional analysis a lot easier. Basically MBSA just enumerates all shares on a server and produces the share and directory ACL, in a simple:

share (name), path, share ACL, directory ACL,

so I need a command to do the same and put the results in a nice CSV file with the same columns so I can do similar analysis.
0
Hi,

I am trying to create a PowerShell script to pull some info from Active Directory into a .csv format.  I am trying to get the following attributes:

- Group
-GroupType
-GroupMember.

Here is what I have so far:

Get-ADGroup -Filter {GroupCategory -eq "Security"} | ForEach-Object {
    $Group = $_
    Get-ADGroupMember -Recursive -Identity $_.name
} | Select-Object @{
    Name="GroupName"
    Expression={$Group.name}
}, Name | Export-Csv -NoType -Path C:\Security Groups.csv

I am running server 2008 R2.

Thanks.
0
Hi people,

Can anyone here please review my Exchange Server PowerShell below to do the mailbox migration from one Exchange Server called PROD-MBX14 into PRODMBX22-VM and then send the email out for any status complete or error ?

New-MigrationBatch –Local –Name PROD-Migration CSVData ([System.IO.File]::ReadAllBytes("C:\TEMP\Group1_Migration.csv")) –TargetDatabase SVR1-DB01, SVR1-DB02, SVR1-DB03, SVR1-DB04  -Autostart -AutoComplete
Start-MigrationBatch –Identity PROD-Migration
Complete-MigrationBatch PROD-Migration

Open in new window


In the .CSV C:\TEMP\Group1_Migration.csv, there are 688 lines of unique email address per line that is running in the old mailbox server.

What I have done manually is to select all of the mailboxes DB in the new server PRODMBX22-VM called:
PRODMBX22-VM-DB01
PRODMBX22-VM-DB02
PRODMBX22-VM-DB03
PRODMBX22-VM-DB04

But how do I do it using the script above and then executing it with the scheduled task to start the migration in the batch of 10, and then move on to the next one again?

The reason I do it 10 by 10 is that the Exchange server is running out of memory if I do it more than 10.

Thanks in advance.
0
Hi all,

For some time now I've been experiencing severe issues with our Exchange 2016 Servers, which are set up in coexistence with 2010 at the moment for migration. Moving mailboxes to 2016 is no problem at the moment, but since updating to CU 4 and .NET 4.6.2 (and on some servers CU 5 as well) I am unable to run even a simple set- or enable-mailbox command on those 2016 servers. Some example commands I try to run are:

Set-Mailbox "sttetest2010" -ThrottlingPolicy "limitrecipientrate5000" (this is an Exchange 2010 hosted mailbox)
Enable-Mailbox "sttetest2016" -Database "MAILDB06" (this is an Exchange 2016 database on the same server - EX06 - I ran the command on, for an existing active directory account "sttetest2016")

The error I get when running those commands always is:

Processing data for a remote command failed with the following error message: [ClientAccessServer=EX06,BackEndServer=ex
06.ad.ua.ac.be,RequestId=79c44d8e-737c-418b-93da-7ac2d12acdd5,TimeStamp=19/06/2017 11:36:42] [FailureCategory=WSMan-Oth
ers] For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OperationStopped: (ex06.ad.ua.ac.be:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : JobFailure
    + PSComputerName        : ex06.ad.ua.ac.be

I get this sort of message on every Exchange 2016 Server I have, regardless of CU version. I've been doing some searching and digging into this, uninstalled .NET 4.6.2 and reinstalled …
0
Hi Experts,

I have an array such that :

ForEach ($item in $ServiceNameArr){ echo $item }

Output:

Apache Tomcat 8.0 gsedev
Apache Tomcat 6

two or more services in array

ForEach ($item in $ServiceNameArr){ $arrd = Invoke-Command -ComputerName vsrver1 -Credential $credentials -ArgumentList $item -ScriptBlock {Param($DisplayName);Get-WmiObject win32_service | ?{$_.DisplayName -like $DisplayName} |select PathName} }

when I echo $arrd I see only the results for "Apache Tomcat 6"


PS C:\> foreach ($items in $arrd){echo $arrd.pathname }
C:\Manager\bin\tomcat6.exe //RS//Tomcat6

I am not getting the other service values (Apache Tomcat 8.0 gsedev)


Please help me out, I would really appreciate any help. Please let me know if you have any questions on the above.
0
Hello All,

The below command helps to get me the log with all lines which consists of %, but what I am looking here is to run this command on multiple servers using a text file. Please help.

(get-content \\APHNGKL400\F$\maint.log) | Select-String "%"

Any assistance is appreciated.
0

Powershell

15K

Solutions

55

Articles & Videos

7K

Contributors

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.