Tag Archives: powershell

Uncategorized

Managing Windows Server 2012 Shares From Powershell

SMB cmdlets come in two modules. Before you can really use these in powershell you first need to import them. These are called SmbShare and SmbWitness, so to import the modules:

Import-Module SmbShare
Import-Module SmbWitness

Or for short:

Import-Module Smb*

Once the SMB modules are imported, we’ll start by looking at what shares you’ve got on your system using Get-SmbShare:

Get-SmbShare

Next, we can create a new share with the minimum two pieces of information required and adding who get’s FullAccess, which is not required:

New-SmbShare -Name BAK -Path E:\BAK -FullAccess krypted

Then we can provide a little more information if we so choose. Here, I’m going to add a description to the share I just created:

Set-SmbShare -Name BAK -Description "To be used for Windows Backup backups."

Now that we have this BAK share, we can configure who’s able to access it. To see who can access the share, use Get-SmbShareAccess along with the -Name followed by the name of each share you’re curious about:

Get-SmbShareAccess -Name BAK

Note that this -Name structure is consistent with all the smb* cmdlets.

If we want to grant another user access to our share we can go ahead and do so using the Grant-SmbShareAccess cmdlet:

Grant-SmbShareAccess -Name BAK -AccountName krypted1 -AccessRight Full

Now that I’ve given the krypted1 user access to a share, I can remove the initial user krypted since I don’t really like him any more. To do so, use the Revoke-SmbShare cmdlet, again identifying the -Name of the Share followed by the account name to remove access for:

Revoke-SmbShare -Name BAK -AccountName krypted

You can also block a user from accessing a share. If a group is granted access and the user is blocked then the user will stay blocked. To block a user, use the Block-SmbShareAccess cmdlet, identify the -Name of the share and then the users name with the -AccountName option. That krypted user is kinda’ pesky so we’ll go ahead and block him:

Block-SmbShareAccess -Name BAK -AccountName krypted

But then the krypted user ends up needing access, so we’ll unblock him using the Unblock-SmbShareAccess cmdlet with the same syntax:

Unblock-SmbShareAccess -Name -AccountName krypted

Permissions are the next most important aspect of managing access to objects. Just because a user can access a share doesn’t mean they should be able to get into that juicy morsel of a payroll directory. CACLS is the command line interface to manage permissions at the file and directory level. CACLS is not a powershell cmdlet. You can see the permissions of a file or folder using the Get-Acl cmdlet. It’s just a cmdlet that you define a location to show the permissions for. Here, we’ll check the c:\Shared\Payroll directory:

Get-Acl c:\Shared\Payroll

Then, there’s the Set-Acl command, which can alter an Acl. As you can imagine, there are a lot of different permissions that can be applied to objects, including the need for recursion and for setting the permissions for recursed objects (OK, OK – I know recursed isn’t really what you might call that, but I’ve always wanted to say it so there ya’ go!). Therefore, instead of taking you through using set-acl I’ll just say, check out the TechNet on it at http://technet.microsoft.com/en-us/library/hh849810.aspx.

Finally, many environment just want the users who can access a share to have the Acl to access the data in the shares. To aid in what should be considered a relatively simple task, you can alter an Acl by piping the output of the get-SmbShare into the Set-Acl command. This sets the Acls to be the same as the permissions set in the share itself:

(Get-SmbShare -Name Bak).PresetPathAcl | Set-Acl

cloud Microsoft Exchange Server Windows Server

Managing Office 365 Users Using PowerShell

Programmatically controlling the cloud is an important part of trying to reign in the chaos of disparate tools that the beancounters make us use these days. Of all the companies out there, Microsoft seems to understand this about as well as anyone and their fine programmers have provided us with a nice set of tools to manage Office 365 accounts, both in a browser (as with most cloud services) and in a shell (which is what we’ll talk about in this article).

This article isn’t really about scripting PowerShell. Instead we’re just looking at a workflow that could be used to script a Student Information System, HRIS solution or another tool that has thousands of users in it to communicate with Microsoft’s 365 cloud offering, providing access to Exchange, Lync, Access, Unified Messaging and of course, minesweeper. Wait, before you get carried away, I still haven’t found a way to access minesweeper through PowerShell… Sorry…

In order to manage Office 365 objects, you will first need to import the MSOnline module (e.g. of cmdlets) and then connect to an account with administrative access to an Office365 environment. To import the cmdlets, use the Import-Module cmdlet, indicating the module to import is MSOnline:

Import-Module MSOnline

The Get-Credential cmdlet informs you what account you are currently signed in as. Once you have imported the appropriate cmdlets, connect to MS Online using the Connect-MsolService cmdlet with no operators, as follows:

Connect-MsolService

You will then be prompted for a valid Live username and password. The Connect-MsolService cmdlet also supports a -Credential operator (Connect-MsolService –Credential) which allows for injecting authentication information into the command in a script. Next, setup a domain using New-MsolDomain along with the -Name operator followed by the name of the domain to use with Office 365:

New-MsolDomain -Name krypted.com

The output would appear as follows, indicating that the domain is not yet verified:

Name                  Status                       Authentication
krypted.com      Unverified              Managed

Once created, in order to complete that you are authoritative for the domain, build a text record in the DNS for the authoritative name server for the domain. To see what the text record should include, run Get-MsolDomainVerificationDns:

Get-MsolDomainVerificationDns -DomainName krypted.com -Mode dnstxtrecord

The output would appear as follows:

Label : deploymsonline.com
Text : MS=ms123456789
Ttl : 3600

Once the domain name shows as verified, you need to confirm it, done using Confirm-MsolDomain:

Confirm-MSolDomain -DomainName krypted.com

you can create a user within the domain. To see account information, use the Get-MsolUser cmdlet with no operators:

Get-MsolUser

To create an account, use the New-MsolUser cmdlet. This requires four attributes for the account being created: UserPrincipalName, DisplayName, FirstName and LastName. These are operators for the command as follows, creating an account called Charles Edge with a display name of Charles Edge and an email address of cedge@krypted.com:

New-MsolUser -UserPrincipalName "cedge@krypted.com" -DisplayName "Charles Edge" -FirstName "Charles" -LastName "Edge"

Other attributes can be included as well, or you can use a csv file to import accounts. Once created, you can use the Set-MSolUserPassword cmdlet to configure a password, identifying the principal with -userPrincipalName and the new password quoted with -NewPassword. I also elected to not make the user change their password at next login (through the web portal users have to reset their password and they’re randomly generated, so this is much more traditionally equivalent to what we’ve done in Active Directory Users and Computers):

Set-MsolUserPassword -userPrincipalName cedge@krypted.com -NewPassword "reamde" -ForceChangePassword False

We can also use Set-MsolPasswordPolicy to change the password policy, although here we’ll use Set-MsolUser for the account so that the password never expires:

Set-MsolUser -UserPrincipalName cedge@krypted.com -PasswordNeverExpires True

Also, you could use Set-MailboxPermission to configure permissions on mailboxes. I’ve also found that Get-MsolAccountSku is helpful to get information about the actual account I’m logged in as and while I’m waiting for a domain to verify that I can use Get-MsolDomain to see the status. Once the domain is accepted, Get-AcceptedDomain shows information about the domain. Set-MsolUserLicense can be used to manage who gets what license.

Finally, all of this could be strung together into a subsystem by any organization to centrally bulk import and manage delegated domains in an Office365 environment. There are going to be certain areas where human intervention is required but overall, most of the process can be automated, and once automated, monitoring the status (e.g. number of accounts, etc) can also be automated, providing a clear and easy strategy for 3rd party toolsets to be integrated with the Office 365 service that Microsoft is providing. It is a new world, this cloud thing, but it sure seems a lot like the old world where we built middleware to do the repetitive parts of our jobs… Just so happens we’re tapping into their infrastructure rather than our own…

Mass Deployment Windows Server Windows XP

Powershell Goodies From Vexasoft

There are a number of features that make mass deployment of Mac OS X pretty easy. Some of these would be great to have in Windows. These range from systemconfiguration to networksetup and the ability to look at packages that have been installed and review their bills of material. Well, the good people at Vexasoft have built a number of Powershell libraries that, while they aren’t named as such, do a number of the features that these commands do, just for Windows clients via Powershell. And the best part is, a number of them are free.

Let’s look at what some of these commands do:

  • First, there are the cmdlets used to manage the network stack (so similar to various verbs in networksetup). These include Add-NetworkAdapterDNS, Add-NetworkAdapterGateway, Add-NetworkAdapterIP, Disable-NetworkAdapter, Enable-NetworkAdapter, Get-NetworkAdapter, Remove-NetworkAdapterIP, Remove-NetworkAdapterGateway, Remove-NetworkAdapterDNS, Set-(followed by the others from the above sets) and Rename-NetworkAdapter.
  • Second, you can automate binding with Set-Domain. This is similar to dsconfigad but less awesome because it’s third party, but still more awesome than the native tools because it’s easier.
  • Third, rename the system. This is similar to scutil, hostname, sets. Just use Rename-Computer to change the name of a Windows system.
  • My favorite, having written something similar, is probably Get-RemoteDesktopConfig and Set-RemoteDesktopConfig, similar to the kickstart options in OS X.
  • And a tool similar to installer in OS X, Install-MSIProduct, which installs MSIs.
  • Sixth, there’s Set-Pagefile, because if you’re gonna’ change it, do so while imaging to save a reboot later…
  • While there are others, the final one I’d like to mention is still free: Get-RegistryKey, which gives us the ability to basically run the closest thing to defaults commands I’ve found against the Windows platform.

They install as standard Powershell modules, making them easy to drop into practically any imaging environment. Much of these can be done via WMI or Powershell already, but will require a bit more legwork to script. Having them pre-built makes it easier than ever to perform some basic tasks for other platforms en masse, on Windows.

Microsoft Exchange Server Windows Server

Mail Tips, For Loops and Powershell

Powershell gives Exchange admins a lot of nice little tricks to use. Exchange 2010 has a new feature in tool tips. You can use Powershell, to run a basic for loop, looping through a quick Get-Mailbox. Based on the output of the Get-Mailbox, you can get a list of all valid mailboxes for an organization. You can then execute a command, allowing you to run any mailbox command against every mailbox of an organization. In the following example, we’ll use the Set-MailBox to make a basic mail tip for all users:

foreach ($mailbox in (Get-Mailbox)) { Set-MailBox -Identity $mailbox -MailTip “Please send only legitimate emails” }

Mac OS X Mac OS X Server Mac Security Mass Deployment Unix Windows Server Windows XP Xsan

Lots of new stuff: Command Line Wiki Integration

The Mac Commands page and the PowerShell Commands page are both now wikis and users with accounts on this site can edit them.

Additionally I added a number of new pages worth of commands, FTP CommandsWindows Commands, Final Cut Server Commands, Amazon S3 Commands, Podcast Producer Commands and Xsan Commands; both of which are wikis as well.

Mac OS X VMware Xsan

Scripting Compellent

As with EMC, Compellent allows you to manage servers, volumes, server folders, volume folders, views, and of course mappings programatically. This provides the automation minded engineer with a full-on suite for managing their Compellent-based SAN. All of this is made possible using CompCU.jar. I keep a scripts folder and keep the jar file there, which can initially be downloaded from the Compellent site. Unlike a traditional shell script the scripts are to be placed into a text file and replayed against the SAN.

If you are using VMware or Xen then you can combine the automation in Compellent along with the automation available with the command line interface for those solutions to accomplish some pretty nifty tasks. Simply call up the CompCU.jar inside shell scripts (or powershell scripts) doing automation in VMware to automatically duplicate LUNs and therefore virtual machines. Useful in lab environments and a number of other scenarios, CompCU.jar provides a nice environment and it’s pretty straight forward to use if you understand the underlying architecture that Compellent uses. For example, the following would run the commands listed in the file called myfile in sequence:
java -jar /scripts/CompCU.jar -s /scripts/myfile

  • c: run command
  • create x:Creates a LUN of -name
  • -s replay x:Runs verb against the Compellent of x type
  • createview: Verb used to create a view based on a replays
  • force: force event to occur
  • host: define
  • last: Repeats the last replay
  • move: Moves mapped views
  • name: Names a LUN
  • password: password to be used when user option is indicated
  • purge: Delete items from your Recycle Bin
  • readcache True/False: enables or disables readcache on a LUN
  • server x: x indicates the name or address of the server you are running your verb against
  • size x: indicates the size of a LUN
  • user: user to perform action as
  • view x: name views
  • viewexpire x: x sets the expiry for your views
  • volume x: identifies the volume to use with the verb
  • writecache True/False: enables or disables writecache on a LUN

One thing I’ve been doing is automating the creation of a volume, mounting it, backing up to it, unmounting it, vaulting it and then after an expiry time, deleting the volume. Without using CompCU.jar I’m not really sure it would have been possible! Although, Compellent also has a PowerShell command set that offers up even more granularity and can help keep you from having to send data into a text file for the command to run in java while offering more functionality in less commands. I am finding it a little more complicated to use so I just haven’t played with using PowerShell with it much, but will get back once I get around to it – but if you have any good commands feel free to post in the comments…

Windows Server

Show Logical Disks in Windows with PowerShell

Quick & dirty, needed to loop through some servers to look at the logical volumes available on each. Using get-WmiObject you can query the available disks for Windows servers:

get-WmiObject win32_logicaldisk

There were a lot of servers, so then I realized I only cared about disks that were named a certain way. As with posix, you can pipe data, so I used where to constrain the output to those with names matching a certain disk name I was looking for:

get-WmiObject win32_logicaldisk | where {$_.name -match “SomeName”}

Isn’t server sprawl so much fun…

Active Directory Windows Server

List Shares in Windows w/ PowerShell

It is not uncommon to end up with a number of shares on a server, be it Windows, Mac OS X or Linux. With all of this sprawl it can be useful to see the shares in a quick and concise manner. using the Win32_Share WMI class through PowerShell you can do just that from the command line, similar to the sharing command in Mac OS X Server. The command, from PowerShell would be something similar to the following:

get-WmiObject -class Win32_Share

Assuming communication is working as intended, you can also query for the shares of other systems, by adding a -computer switch and specifying the host you’re listing shares on, as follows:

get-WmiObject -class Win32_Share -computer dc1.krypted.com

One can also list shared printers with a little trickeration in the {} side of things:
get-WmiObject -list | where {$_.name -match “Printer”}

Microsoft Exchange Server

Exchange 2007: Change Default Domain with PowerShell

Your users sick of typing in their domain name in the OWA auth screen?  Well, here’s the PowerShell command to make it where they don’t have to any more:

Set-OWAVirtualDirectory -Identity “owa (default web site)” -LogonFormat username -DefaultDomain krypted.com 

Since you’re not using krypted.com as your mail domain swap that out with your domain name of course.  And if you want to use it for the other virtual directories of OWA, such as Exadmin then run it again swapping out the owa with the VD you’re using.  Oh, you can do it through the Exchange Management Console too, but the GUI isn’t as much fun.  But if you do decide to do it that way, fire up the mmc, click on Server Configuration, click on the Client Access role, click on your server, select the site (probably OWA), then click Properties and set authentication to forms based authentication.  From here, click User Name Only and then click on Browse to set your domain name.  When you’re done hit Apply and then restart IIS and test it out.

Windows Server

Windows Server: Set Permissions Using PowerShell

 

Set-acl

Set Access Control List permissions from on a file (or object).

Syntax
      Set-Acl [-path] string[] [-aclObject] ObjectSecurity
                 [-filter string]
                    [-Include String] [-Exclude String]
                       [-passThru] [-whatIf] [-confirm] [CommonParameters]

Key
   -Path path
       Path to the item to be changed {accepts wildcards}

   -aclObject ObjectSecurity
       An ACL with the desired property values.

   -filter string
       A filter in the provider's format or language.
       The exact syntax of the filter (wildcard support etc) depends on the provider.
       Filters are more efficient than -include/-exclude, because the provider
       applies the filter when retrieving the objects, rather than having
       PowerShell filter the objects after they are retrieved.

   -include string
       Include only the specified items from the Path. e.g. "May*"
       this only works when the path includes a wildcard character.

   -exclude string
       Omit the specified items from the Path e.g. "*SS64*"
       this only works when the path includes a wildcard character.

   -passThru
       Pass the object created by Set-Acl through the pipeline.

   -whatIf
       Describe what would happen if you executed the command without
       actually executing the command.

   -confirm
       Prompt for confirmation before executing the command.

   CommonParameters:
      -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutVariable.

Examples

Copy the security settings from Dog.txt to Cat.txt

PS C:\>$DogACL = get-acl c:\dog.txt
PS C:\>set-acl -path C:\cat.txt -AclObject $DogACL

Or the same thing with a pipeline:

PS C:\>get-acl c:\dog.txt | set-acl -path C:\cat.txt

Apply the same $DogACL to all the files in C:\Temp\ and all of its subdirectories:

PS C:\>get-childitem c:\temp -recurse -force | set-acl -aclobject $DogACL -whatif