Archive for the 'Powershell' Category

PowerShell Script: Zip up a folder and email it

Cool method for scripting attaching a file and emailing using Powershell.  The script also displays how to zip up a destination using Out-zip.

$sender = sender@host.com
$recipient = recipient@host.com
$server = mail.host.com
$targetFolder = c:\MyFolder
$file = c:\MyZipFile.zip
if ( [System.IO.File]::Exists($file) )
{
  remove-item -force $file
}

gi $targetFolder | out-zip $file $_
$subject = “Sending a File ” + [System.DateTime]::Now
$body = “I’m sending a file!”
$msg = new-object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
$attachment = new-object System.Net.Mail.Attachment $file
$msg.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$client.Send($msg)

Mike Hodnick : PowerShell: Zip up a folder and email it

Powershell Script : Generate rdp-files from AD

NOTE:  this script requires the Quest Active Directory cmdlets

#generate-rdpfiles.ps1

$input = Get-QADComputer -ErrorAction SilentlyContinue -SizeLimit 0 | Where-Object { $_ .operatingsystem -match “Server” }

$RDPRoot = ‘C:\RDP-Files’

if ( -not ( Test-Path -Path $RDPRoot )) {

    New-Item -Path $RDPRoot -ItemType Directory | Out-Null

}

$input | ForEach-Object {

    $path = “$RDPRoot\$($_.Name).rdp”

    $rdpfile = Test-Path -Path $path

    if ( $rdpFile -eq $true ) {

        Clear-Content -Path $path

    }

    Add-Content -Path $path -Force -Value @”

screen mode id:i:1

desktopwidth:i:1152

desktopheight:i:864

session bpp:i:16

winposstr:s:0,1,0,0,1032,795

full address:s:$($_.Name)

compression:i:1

keyboardhook:i:2

audiomode:i:2

redirectprinters:i:0

redirectcomports:i:0

redirectsmartcards:i:1

redirectclipboard:i:1

redirectposdevices:i:0

drivestoredirect:s:*

displayconnectionbar:i:1

autoreconnection enabled:i:1

authentication level:i:0

prompt for credentials:i:0

negotiate security layer:i:1

remoteapplicationmode:i:0

alternate shell:s:

shell working directory:s:

disable wallpaper:i:0

disable full window drag:i:0

allow desktop composition:i:1

allow font smoothing:i:1

disable menu anims:i:0

disable themes:i:0

disable cursor setting:i:0

bitmapcachepersistenable:i:1

gatewayhostname:s:

gatewayusagemethod:i:0

gatewaycredentialssource:i:4

gatewayprofileusagemethod:i:1

“@

}

PowerGUI - Administrative Powershell Console : Generate rdp-files from AD …

PowerShell Script: Get Listed Service Packs & Hotfixes

$strComputer = "."

$colItems = get-wmiobject -class "Win32_QuickFixEngineering" -namespace "root\CIMV2" `
-computername $strComputer

foreach ($objItem in $colItems) {
      write-host "Caption: " $objItem.Caption
      write-host "CS Name: " $objItem.CSName
      write-host "Description: " $objItem.Description
      write-host "Fix Comments: " $objItem.FixComments
      write-host "HotFix ID: " $objItem.HotFixID
      write-host "InstallationDate: " $objItem.InstallDate
      write-host "Installed By: " $objItem.InstalledBy
      write-host "Installed On: " $objItem.InstalledOn
      write-host "Name: " $objItem.Name
      write-host "Service Pack In Effect: " $objItem.ServicePackInEffect
      write-host "Status: " $objItem.Status
      write-host
}

PowerShell Script: Schedule Reboot of Server

$now=get-date

$MachineName=read-host "Please Enter Machine Name you wish to reboot :"

$When=read-host "Please enter time when you wish to reboot the server Later THAN ($now) :"

$results=$now.subtract($when)

#write-host $Results Results

$time2act=$now.Subtract($results)

#Write-host $time2act is time2act

$action=$time2act.subtract($now)

$Sec2Act= $action.totalseconds

$totalsecs="{0:N0}" -f $Sec2Act

$SecINint=[int]$totalsecs

write-host $testint

if($results -le 0)
{
write-host "done"
Write-host $MachineName "will Reboot in next " $SecINint Seconds
shutdown -s -m $machineName -t $SecINint
}
else {
write-host "Time entered has already past,please enter time later than " [$now] -Background "RED"
}

PowerShell Script: Get Last Reboot Time

$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "Machine Name"
$c.Cells.Item(1,2) = "IP Address"
$c.Cells.Item(1,3) = "MAC Address"
$c.Cells.Item(1,4) = "Last Boot Time"
$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$d.EntireColumn.AutoFit()
$m = 2
$x = get-content C:\Myworkplace\Clientlist.txt
foreach ($i in $x)
{$y = get-wmiobject Win32_NetworkAdapterConfiguration -computername $i -Filter "IPenabled = ‘True’"
foreach ($j in $y)
{$c.Cells.Item($m, 1) = $j.DNSHostName
$c.Cells.Item($m, 2) = $j.IPAddress
$c.Cells.Item($m, 3) = $j.MACAddress}
$date = new-object -com WbemScripting.SWbemDateTime
$z = get-wmiobject Win32_OperatingSystem -computername $i
foreach ($k in $z)
{$date.value = $k.lastBootupTime
If ($k.Version -eq "5.2.3790" )
{$c.Cells.Item($m, 4) = $Date.GetVarDate($True)}
Else
{$c.Cells.Item($m, 4) = $Date.GetVarDate($False)}
}
$m = $m + 1
}

Windows PowerShell : Show-WmiClass

Jeffrey Snover of Microsoft posted this script to provide a simple way to show WMI Classes within PowerShell.

Here is a script that I use to show WMI classes. I think you’ll find it useful. There is an example after the script:

##############################
# Show-WmiClass - Show WMI classes
# Author: Microsoft
# Version: 1.0
# NOTE: Notice that this is uses the verb SHOW vs GET. That is because it
# combines a Getter with a format. SHOW was added as a new “official
# verb to deal with just this case.
#############################
param(
$Name = “.”,
$NameSpace = “root\cimv2″,
[Switch]$Refresh=$false
)
# Getting a list of classes can be expensive and the list changes infrequently.
# This makes it a good candidate for caching.
$CacheDir = Join-path $env:Temp “WMIClasses”
$CacheFile = Join-Path $CacheDir ($Namespace.Replace(”\”,”-”) + “.csv”)
if (!(Test-Path $CacheDir))
{
$null = New-Item -Type Directory -Force $CacheDir
}
if (!(Test-Path $CacheFile) -Or $Refresh)
{
Get-WmiObject -List -Namespace:$Namespace |
Sort -Property Name |
Select -Property Name |
Export-csv -Path $CacheFile -Force
}
Import-csv -Path $CacheFile |
where {$_.Name -match $Name} |
Format-Wide -AutoSize
###### EOF ###########

Example

PS> show-wmiclass account
MSFT_NetBadAccount Win32_Account Win32_AccountSID
Win32_SystemAccount Win32_UserAccount
PS> show-wmiclass account -namespace root\cimv2\terminalservices
Win32_TSAccount
PS> show-wmiclass -namespace root\cimv2\terminalservices
__AbsoluteTimerInstruction __ACE
__AggregateEvent __ClassCreationEvent
__ClassDeletionEvent __ClassModificationEvent
__ClassOperationEvent __ClassProviderRegistration
__ConsumerFailureEvent __Event
__EventConsumer __EventConsumerProviderRegistration
__EventDroppedEvent __EventFilter
__EventGenerator __EventProviderRegistration
__EventQueueOverflowEvent __ExtendedStatus
__ExtrinsicEvent __FilterToConsumerBinding
__IndicationRelated __InstanceCreationEvent
__InstanceDeletionEvent __InstanceModificationEvent
__InstanceOperationEvent __InstanceProviderRegistration
__IntervalTimerInstruction __MethodInvocationEvent
__MethodProviderRegistration __NAMESPACE
__NamespaceCreationEvent __NamespaceDeletionEvent
__NamespaceModificationEvent __NamespaceOperationEvent
__NotifyStatus __NTLMUser9X
__ObjectProviderRegistration __PARAMETERS
__PropertyProviderRegistration __Provider
__ProviderRegistration __QOSFailureEvent
__SecurityDescriptor __SecurityRelatedClass
__SystemClass __SystemEvent
__SystemSecurity __thisNAMESPACE
__TimerEvent __TimerInstruction
__TimerNextFiring __Trustee
__Win32Provider CIM_ElementSetting
CIM_LogicalElement CIM_ManagedSystemElement
CIM_Setting Win32_Terminal
Win32_TerminalError Win32_TerminalServiceSetting
Win32_TerminalServiceSettingError Win32_TerminalServiceToSetting
Win32_TerminalSetting Win32_TerminalTerminalSetting
Win32_TSAccount Win32_TSClientSetting
Win32_TSEnvironmentSetting Win32_TSGeneralSetting
Win32_TSLogonSetting Win32_TSNetworkAdapterListSetting
Win32_TSNetworkAdapterSetting Win32_TSPermissionsSetting
Win32_TSRemoteControlSetting Win32_TSSessionDirectory
Win32_TSSessionDirectorySetting Win32_TSSessionSetting
PS>

Windows PowerShell : Show-WmiClass

PowerShell Toolbox

Adam Bell has a detailed, growing list of PowerShell tools that are currently available.  Bookmark the page as new tools are added when available.

Here is a sample:

/N Software NetCmdlets
- a broad range of network management and messaging capabilities. The current release contains more than 30 Cmdlets providing access to network and host protocols such as SNMP, LDAP, DNS, Syslog, HTTP, WebDav, FTP, SMTP, POP, IMAP, Rexec/RShell, Telnet, and more. This is a commercial product.

Codeplex PoshConsole
- utilises WPF features to improve on the PS shell. This tool aims to be a more modern replacement for the default shell. This is an open source product.

Codeplex PowerShell Community Extensions
- working towards providing widely useful set of additional cmdlets, providers, aliases, filters, functions and scripts for PowerShell. This is an open source product.

Codeplex PSEventing
- Trap and respond to synchronous & asynchronous .NET events within your powershell scripts with an easy to use suite of cmdlets. This is an open source product.

Microsoft PowerShell SDK
- The Windows PowerShell SDK is written for command developers who require reference information about the APIs provided by Windows PowerShell. This is a free download from MSDN.

PowerGadgets
- data visualization product that creates gadgets for displaying output from your PS data in Windows. Very simple to create. This is a commercial product.

PowerLocker PowerPad
- a small editor to develop and test your function or script. This is a free product.

Quest ActiveRoles Management Shell for AD (aka Quest AD Cmdlets)
- perform administrative tasks like discovering the AD environment, changing user properties, modifying group membership, provisioning new user accounts, and performing multiple other tasks within Active Directory. This is a free product.

Quest PowerGUI
- an extensible graphical administrative console for managing systems based on Windows PowerShell. This is a free product.

SAPIEN PrimalScript 2007
- fully-customizable user interface with multiple tabs, dockable pane, IDE for use with PowerShell and other scripting languages. This is a commercial product.

You can view the entire list here

Lead, Follow, or Move » PowerShell Toolbox

Allowing scripts to be run via PowerShell

Running scripts via Powershell is disable by default.  There is a key to note that you can run commands or cmdlets from the PowerShell console, just not scripts.  To enable this feature you can do one of two things, however one trumps the other:

Via PowerShell

Modify your ExecutionPolicy via the Set-Execution cmdlet

First run Get-ExecutionPolicy to see what level you are at.  By default, this setting is set to Restricted. 

To see what settings are available for you to set, you can type

Get-Help Set-ExecutionPolicy

This output shows that we have four options:  Restricted, AllSigned, RemoteSigned, and Unrestricted.

To set your ExecutionPolicy to Unrestricted (not recommended for production) you would enter:

Set-ExecutionPolicy Unrestricted

To validate you settings after running the Set-ExecutionPolicy, run:

Get-ExecutionPolicy

From the command above, your ExecutionPolicy is now set to Unrestricted.  You can now run any scripts you like, signed or unsigned. (Bet your administrator is happy to hear that!)

Now for the other method for setting this policy

Via Group Policy

Seeing how the first method would be a nightmare to manage, Microsoft has released the ADM files for PowerShell that allow you to configure this setting via Group Policy.  Any settings made via Group Policy will overwrite those set manually via the PowerShell Console. 

powershellADM 

You can download the PowerShell ADM here

Active Directory Account Management using PowerShell

 PowerShell and the Quest Active Directory cmdlets are a dream come true for any AD Administrator.  Methods that used to take more complicated means are now simple one-liners.  

One of the nice improvements of AD cmdlets 1.0.4 is the way you can get enable, disable, and unlock AD user accounts with simple one-liners.

Here are a few oneliners demonstrating the new functionality:

#Get all disabled accounts
Get-QADUser -Disabled $true

#Get all locked accounts in the accounting department
Get-QADUser -Locked $true -Department Accounting

#Enable all the disabled accounts
Get-QADUser -Disabled $true | Enable-QADUser

#Unlock a specific user account
Unlock-QADUser DSotnikov

Dmitry’s PowerBlog: PowerShell and beyond

The little things

I once had a coach in high school that would always, and I mean always stress the little things.  “Its the little things that make the big things”; we would hear that daily.  After playing around with Powershell at home, I started laughing because I heard that voice say that phrase as I used a single line to organize all of my scattered .iso files on my 1TB external drive. 

I always wanted to re-organize the files on this drive, but using any search feature took a long time, and time is not something I have much of.  So again, the little things.

From the PowerShell console, I was wondering in what locations were all of my ISO files?  I entered:

Get-ChildItem -path E:\ -Recurse -Include *.iso > ISO.txt

This command searched for every ISO on the external drive (E:) and piped it out to a text file.  Viewing that text file, I found out what I thought…I had ISO files everywhere.  No big deal, I’ll just modify the command above to move everything to a central repository.

Get-ChildItem -path E:\ -Recurse -Include *.iso | move-item -Destination e:\ISO\

Easy peasy, command completed and now i’m going to re-run my audit of where my ISO files are and we see that they are now all located in the -Destination directory.

Clean-up made simple!