full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Find sharable storage.ps1
|
Find sharable storage.ps1
|
# This function returns all datastores that can be shared amongst ESX hosts.
function Get-ShareableDatastore {
# Get all datastores.
$datastores = Get-Datastore
# Load the HostStorageSystems of all hosts.
$hosts = Get-VMHost | Get-View -property ConfigManager
$storageSystems = @()
foreach ($h in $hosts) {
$storageSystems += Get-View $h.ConfigManager.StorageSystem -Property StorageDeviceInfo
}
foreach ($dso in $datastores) {
$ds = $dso | Get-View -Property Info
# Check if this datastore is NFS.
$dsInfo = $ds.Info
if ($dsInfo -is [VMware.Vim.NasDatastoreInfo]) {
Write-Output $dso
continue
}
# Get the first extent of the datastore.
$firstExtent = $dsInfo.Vmfs.Extent[0]
# Write-Host $firstExtent
# Find a host that maps this LUN.
foreach ($hss in $storageSystems) {
$lun = $hss.StorageDeviceInfo.ScsiLun | Where { $_.CanonicalName -eq $firstExtent.DiskName }
# Write-Host $lun
if ($lun) {
# Search the adapter topology of this host, looking for the LUN.
$adapterTopology = $hss.StorageDeviceInfo.ScsiTopology.Adapter |
Where { $_.Target |
Where { $_.Lun |
Where { $_.ScsiLun -eq $lun.key }
}
} | Select -First 1
# We've found a host that has this LUN. Find how it maps to an adapter.
$adapter = $hss.StorageDeviceInfo.HostBusAdapter | Where { $_.Key -eq $adapterTopology.Adapter }
# It's shared if it's Fibre Channel or iSCSI (we checked for NFS earlier)
if ($adapter -is [VMware.Vim.HostFibreChannelHba] -or $adapter -is [VMware.Vim.HostInternetScsiHba]) {
Write-Output $dso
}
# Otherwise it's not shared and we quit walking through hosts.
break
}
}
}
}
|
PowerShellCorpus/PoshCode/OnTapSDK_Discoverability.ps1
|
OnTapSDK_Discoverability.ps1
|
# Glenn Sizemore www . Get-Admin . com
# Requires the NetApp OnTap SDK v3.5
# Get-NaAPI
# Will return a list of ZAPI Calls that the filer supports. Can be used
# as a poor man's Get-Command for the OnTap SDK.
#########################################################################
# Usage:
# Connect to the filler
# $Filer = 'TOASTER'
# $NetApp = New-Object NetApp.Manage.NaServer($filer,1,0)
# $NetApp.SetAdminUser(UserName,Password)
#
# Example
# Get-NaAPI -Server $NetApp
#
# Will retrieve every OnTap ZAPI request in the system
#
# Example
# Get-NaAPI -NaServer $NetApp -Name Volume
#
# Will return every ZAPI call that pertains to volume management.
Function Get-NaAPI {
Param(
[NetApp.Manage.NaServer]$NaServer,
[string]$Name
)
Begin {
$APIList = @()
}
Process {
$NaElement = New-Object Netapp.Manage.NaElement("system-api-list")
$apis = $NaServer.InvokeElem($naelement).GetChildByName("apis")
Foreach ($api in $apis.GetChildren()) {
$APIList += $api.getchildcontent("name")
}
}
End {
if ($Name) {
return $APIList | Where-Object {$_ -match $name}
} else {
return $APIList
}
}
}
# Get-NaAPIElements
# Given a ZAPI call return the parameters in that call.
#########################################################################
# Usage:
# Connect to the filler
# $Filer = 'TOASTER'
# $NetApp = New-Object NetApp.Manage.NaServer($filer,1,0)
# $NetApp.SetAdminUser(UserName,Password)
#
# Example
# Get-NaAPIElements -NaServer $NaServer -API "volume-list-info"
#
# returns all the elements/parameters used by the volume-list-info API.
#
# Example
# Get-NaAPIElements -NaServer $NaServer -API "volume-list-info" -output
#
# Will return any output elements volume-list-info generates.
Function Get-NaAPIElements {
Param(
[NetApp.Manage.NaServer]$NaServer,
[string[]]$API,
[switch]$Output
)
Process {
$e = New-Object NetApp.Manage.NaElement("api-list")
Foreach ($A in $API) {
$e.AddNewChild('api-list-info',$A)
}
$NaElement = New-Object NetApp.Manage.NaElement("system-api-get-elements")
$NaElement.AddChildElement($e)
$apilist = $NaServer.InvokeElem($naelement).getchildbyname("api-entries")
Foreach ($A in $apiList.getchildbyname("system-api-entry-info")) {
$Obj = "" | Select API, ElementName, ElementType, Optional, AllowNull
$N = $A.GetChildContent("name")
foreach ($e in $a.getchildbyname("api-elements").getchildren()) {
$obj.API = $N
$obj.ElementName = $e.getchildcontent('name')
switch ($e.getchildcontent('type')) {
"string" {$obj.ElementType = "String"}
"integer" {$obj.ElementType = "int"}
"boolean" {$obj.ElementType = "Bool"}
Default {
$obj.ElementType = $_
$objElem = $true
}
}
IF (!$e.getchildbyname('is-optional')) {
$Obj.Optional = $False
} Else {
$Obj.Optional = $true
}
IF (!$e.getchildbyname('is-output')) {
$objOutput = $False
} Else {
$objOutput = $true
}
IF (!$e.getchildbyname('is-optional')) {
$Obj.Optional = $False
} Else {
$Obj.Optional = $true
}
IF (
(!$e.getchildbyname('is-nonempty')) -or `
$e.GetChildContent('is-nonempty') -match "false"
) {
$Obj.AllowNull = $True
} Else {
$Obj.AllowNull = $False
}
Switch ($objOutput) {
{($Output -eq $true) -and ($_ -eq $true)}
{write-output $obj}
{($Output -eq $false) -and ($_ -eq $false)}
{write-output $obj}
}
}
}
}
}
# Get-NaType
# The OnTap API only supports three primitive types Int, String, and Bool.
# It also has over 80 NaTypes; NaTypes are similar to PSObjects in that
# there is no formal class. They are build on the fly, this function
# returns what is required to construct a new NaElement as the given Natype.
#########################################################################
# Usage:
# Connect to the filler
# $Filer = 'TOASTER'
# $NetApp = New-Object NetApp.Manage.NaServer($filer,1,0)
# $NetApp.SetAdminUser(UserName,Password)
#
# Example
# Get-NaType -NaServer $NaServer -Type "volume-info"
#
# Will return all the elements that comprise a volume-info NaElement type.
Function Get-NaType {
Param(
[NetApp.Manage.NaServer]$NaServer,
[string]$Type
)
process {
$NaElement = New-Object NetApp.Manage.NaElement("system-api-list-types")
$results = $NaServer.InvokeElem($NaElement).GetChildByName("type-entries").getchildren()
If ($type) {
$results = $results | ?{$_.GetChildContent("name") -eq $type}
}
$results.GetChildByName("type-elements").getchildren() | Select @{
n='name'
E={$_.GetChildContent("name")}
}, @{
n='type'
E={$_.GetChildContent("type")}
}, @{
n='optional'
E={$_.GetChildContent("is-optional")}
}
}
}
|
PowerShellCorpus/PoshCode/Import-Methods_1.ps1
|
Import-Methods_1.ps1
|
# [CmdletBinding()]
param(
#[Parameter(Position=1,ValueFromPipeline=$true)]
[type]$type
,
#[Parameter()]
#[Alias("Properties")]
[switch]$IncludeProperties
)
BEGIN {
function MakeFunction() {
PROCESS {
$func = "function:global:$($_.name)"
if (test-path $func) { remove-item $func }
$flags = 'Public,Static,InvokeMethod,DeclaredOnly'
new-item $func -value "[$($type.fullname)].InvokeMember('$($_.name)',$flags, `$null, `$null, `$args[0])"
}
}
function MakeVariable($type) {
PROCESS {
$var = "variable:global:$($_.name)"
if (test-path $var) { Remove-Variable $var -ErrorAction SilentlyContinue }
new-variable -Name $($_.name) -Value $(Invoke-Expression "[$($type.fullname)]::$($_.name)") `
-Description "Imported from $($type.FullName)" -Force -Scope Global `
-Option AllScope, Constant, ReadOnly
}
}
}
PROCESS {
if($_) { $type = $_ }
$type | gm -static -membertype "method" | MakeFunction
## Properties as variables:
if($IncludeProperties) {
$type | gm -static -membertype "property" | MakeVariable $type
}
}
|
PowerShellCorpus/PoshCode/PowerShell_ISE Profile_1.ps1
|
PowerShell_ISE Profile_1.ps1
|
#--------------------------------------------------------------------------------------------------------------
#Convert Untitled1.ps1 to ASCII encoding
$psise.CurrentPowerShellTab.Files | % {
# set private field which holds default encoding to ASCII
$_.gettype().getfield("encoding","nonpublic,instance").setvalue($_, [text.encoding]::ascii)
}
# watch for changes to the Files collection of the current Tab
register-objectevent $psise.CurrentPowerShellTab.Files collectionchanged -action {
# iterate ISEFile objects
$event.sender | % {
# set private field which holds default encoding to ASCII
$_.gettype().getfield("encoding","nonpublic,instance").setvalue($_, [text.encoding]::ascii)
}
}
#--------------------------------------------------------------------------------------------------------------
|
PowerShellCorpus/PoshCode/COE_IMAGE.ps1
|
COE_IMAGE.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -originalPCname CurrentName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/Execute in PowerShell.ps1
|
Execute in PowerShell.ps1
|
#===================================================================================
#
# Filename: AddExecuteInPowerShellToPS1Files.ps1
#
# Author: Nigel Boulton
#
# Version: 1.00
#
# Date: 9 Nov 2008
#
# Mod dates:
#
# Purpose: To add context menu items for .ps1 files in Windows Explorer, to
# allow PowerShell scripts to be executed by right-clicking them
#
# Action: Gets the path to PowerShell.exe by reading the Path property of
# the process. If PowerShell is not running (e.g. if using a GUI/IDE),
# prompts the user to enter the path. Quotes the path if it contains
# any spaces
# Gets the class key for .ps1 files from the registry and adds the
# appropriate subkeys and values to it to add "Execute in PowerShell"
# and "Execute in PowerShell (-NoExit)" context menu items
#
# Notes: USE AT YOUR OWN RISK! Backup your system first and all that...
# Must be run as an administrator
#
#===================================================================================
# Get the full path to PowerShell.exe, or prompt if using a GUI
$PoSH = Get-Process | Where-Object {$_.Name -eq "PowerShell"} | Select-Object -First 1
If ($PoSH -eq $null) {
$PoSHPath = Read-Host "Please enter the full path to PowerShell.exe, or cancel and run this script in a PowerShell console session"
If ($PoSHPath -eq $Null) {exit 1}
}
Else
{
$PoSHPath = $PoSH.Path
}
# Quote PowerShell path if it isn't already
If ($PoSHPath.Substring(0,1) -ne "`"") {$PoSHPath = "`"" + $PoSHPath}
If ($PoSHPath.Substring($PoSHPath.Length - 1,1) -ne "`"") {$PoSHPath += "`""}
# Get class for .ps1 files
$PS1Class = (Get-ItemProperty -Path HKLM:SOFTWARE\\Classes\\.ps1)."(Default)"
# Build hash table of registry data to add
# $_.Name is the registry key and $_.Value is the data for the "(Default)" value in that key
$RegData = @{"HKLM:Software\\Classes\\$PS1Class\\shell\\Execute in PowerShell\\command" = $PoSHPath + " &'%1'";`
"HKLM:Software\\Classes\\$PS1Class\\shell\\Execute in PowerShell (-NoExit)\\command" = $PoSHPath + " -NoExit &'%1'"}
# Check for an existing "Open" action. If there isn't one we need to add one in to ensure that "Open"
# remains the default. If we didn't do this, in future double-clicking .ps1 files would execute them!
If ((Test-Path "HKLM:Software\\Classes\\$PS1Class\\shell\\open\\command") -eq $False) {$RegData.Add("HKLM:Software\\Classes\\$PS1Class\\shell\\open\\command", "notepad.exe `"%1`"")}
# Iterate hash table to create registry keys and set values
$RegData.GetEnumerator() | ForEach-Object {
# Create registry path
If ((Test-Path $_.Name) -eq $False) {New-Item -Path $_.Name -Force | Out-Null}
# Set "(Default)" value
Set-ItemProperty -Path $_.Name -Name "(Default)" -Value $_.Value
}
Write-Output "Processing complete"
|
PowerShellCorpus/PoshCode/AutoArchive.ps1
|
AutoArchive.ps1
|
# AutoArchive PowerShell Script
# http://powershell.codeplex.com
param (
[ValidateNotNullOrEmpty()]
[Parameter(
Mandatory = $true)
]
[string] $Source,
[int] $RetentionDays,
[array] $Include,
[array] $Exclude,
[switch] $Recurse )
# Load Zip Module
Import-Module PowerZip
# Check source presence
if ( -not ( Test-Path -Path "$Source" -ErrorAction SilentlyContinue ) )
{
throw "ERROR : Source not found { $Source }"
}
# Set variables
$DirectoryTimeStamp = (Get-Date).ToString("yyyy\\\\MM")
$ArchiveTimeStamp = (Get-Date).ToString("yyyyMMddHHmmss")
if ( $Recurse -eq $true ) { $RecurseArgument = "-Recurse" }
if ( $Include )
{
$Include = $Include -join ","
$IncludeArgument = "-Include $Include"
$Source = $Source+"\\*"
}
$Exclude += @("*.zip")
$Exclude = $Exclude -join ","
$ExcludeArgument = "-Exclude $Exclude"
$GetCommand = "Get-ChildItem -Path '$Source' $IncludeArgument $ExcludeArgument $RecurseArgument"
Invoke-Expression -Command $GetCommand | Where-Object { ( $_.LastWriteTime -lt (Get-Date).AddDays(-$RetentionDays) ) -and ( $_.psIsContainer -eq $false ) -and ( $_ -cnotmatch "\\\\_AutoArchive_\\\\" ) } | ForEach-Object {
$ArchiveDirectory = $_.DirectoryName
$ArchiveDirectory = "$ArchiveDirectory\\_AutoArchive_\\$DirectoryTimeStamp"
Write-Output "Moving { $($_.FullName) } to { $ArchiveDirectory } ..."
$DirectoryToZipArray += @($ArchiveDirectory)
if ( -not ( Test-Path -Path "$ArchiveDirectory" -ErrorAction SilentlyContinue ) )
{
New-Item -ItemType Directory -Path "$ArchiveDirectory" | Out-Null
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to create directory {$ArchiveDirectory}")
}
}
Move-Item -Path $_.FullName -Destination "$ArchiveDirectory" -Force -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to move file {$($_.FullName)}")
}
}
foreach ( $DirectoryToZip in $DirectoryToZipArray | Sort-Object -Unique )
{
Write-Output "Zipping { $DirectoryToZip } ..."
$ZipFile = "$DirectoryToZip\\$ArchiveTimeStamp.zip"
$Zip = New-Zip -Source "$DirectoryToZip" -ZipFile "$ZipFile" -DeleteAfterZip -Exclude "*.zip"
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to zip directory {$DirectoryToZip}")
}
}
if ( $ErrorsArray )
{
Write-Output "`n[ ERRORS OCCURED ]"
$ErrorsArray
return $false
}
else
{
return $true
}
|
PowerShellCorpus/PoshCode/Demo-ShouldProcess.ps1
|
Demo-ShouldProcess.ps1
|
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")]
param([Switch]$Force)
$RejectAll = $false;
$ConfirmAll = $false;
foreach($file in ls) {
if($PSCmdlet.ShouldProcess( "Removed the file '$($file.Name)'",
"Remove the file '$($file.Name)'?",
"Removing Files" )) {
if($Force -Or $PSCmdlet.ShouldContinue("Are you REALLY sure you want to remove '$($file.Name)'?", "Removing '$($file.Name)'", [ref]$ConfirmAll, [ref]$RejectAll)) {
"Removing $File"
}
}
}
|
PowerShellCorpus/PoshCode/ISE-CopyOutPutToEditor_2.ps1
|
ISE-CopyOutPutToEditor_2.ps1
|
function ISE-CopyOutPutToEditor () {
$count = $psise.CurrentPowerShellTab.Files.count
$psIse.CurrentPowerShellTab.Files.Add()
$Newfile = $psIse.CurrentPowerShellTab.Files[$count]
$Newfile.Editor.Text = $psIse.CurrentPowerShellTab.Output.Text
$Newfile.Editor.Focus()
}
$null = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Copy Output to Editor", {ISE-CopyOutPutToEditor}, 'Ctrl+O')
|
PowerShellCorpus/PoshCode/Desktop.ps1
|
Desktop.ps1
|
#region License
// Desktop 1.1
// *
// Copyright (C) 2004 http://www.onyeyiri.co.uk
// Coded by: Nnamdi Onyeyiri
//
// This code may be used in any way you desire except for commercial use.
// The code can be freely redistributed unmodified as long as all of the authors
// copyright notices remain intact, as long as it is not being sold for profit.
// Although I have tried to ensure the stability of the code, I will not take
// responsibility for any loss, damages, or death it may cause.
//
// This software is provided "as is" without any expressed or implied warranty.
//
// -------------------------
// Change Log
//
// Version 1.0: -First Release
//
// Version 1.1: -Added Window and WindowCollection classes
// 6/6/2004 -Added another GetWindows overload, that used WindowCollection
// -Added GetInputProcesses method to retrieve processes on Input desktop
// -Changed GetWindows and GetDesktops to return arrays, instead of them being passed by ref
//
// Version 1.2 -Implemented IDisposable
// 8/7/2004 -Implemented ICloneable
// -Overrided ToString to return desktop name
//
// Version 2.0 -Switched to Generic Collections
// 7/19/2010 -Added enumeration of process from alternate desktops
// Joel Bennett -Renamed a lot of methods to remove duplication
#endregion
using System;
using System.Threading;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
/// <summary>
/// Encapsulates the Desktop API.
/// </summary>
public class Desktop : IDisposable, ICloneable
{
#region Imports
[DllImport("kernel32.dll")]
private static extern int GetThreadId(IntPtr thread);
[DllImport("kernel32.dll")]
private static extern int GetProcessId(IntPtr process);
//
// Imported winAPI functions.
//
[DllImport("user32.dll")]
private static extern IntPtr CreateDesktop(string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, int dwFlags, long dwDesiredAccess, IntPtr lpsa);
[DllImport("user32.dll")]
private static extern bool CloseDesktop(IntPtr hDesktop);
[DllImport("user32.dll")]
private static extern IntPtr OpenDesktop(string lpszDesktop, int dwFlags, bool fInherit, long dwDesiredAccess);
[DllImport("user32.dll")]
private static extern IntPtr OpenInputDesktop(int dwFlags, bool fInherit, long dwDesiredAccess);
[DllImport("user32.dll")]
private static extern bool SwitchDesktop(IntPtr hDesktop);
[DllImport("user32.dll")]
private static extern bool EnumDesktops(IntPtr hwinsta, EnumDesktopProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetProcessWindowStation();
[DllImport("user32.dll")]
private static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDesktopWindowsProc lpfn, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool SetThreadDesktop(IntPtr hDesktop);
[DllImport("user32.dll")]
public static extern IntPtr GetThreadDesktop(int dwThreadId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetUserObjectInformation(IntPtr hObj, int nIndex, IntPtr pvInfo, int nLength, ref int lpnLengthNeeded);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, IntPtr lpString, int nMaxCount);
private delegate bool EnumDesktopProc(string lpszDesktop, IntPtr lParam);
private delegate bool EnumDesktopWindowsProc(IntPtr desktopHandle, IntPtr lParam);
// The Unicode version of this function, CreateProcessW, can modify the contents of the lpCommandLine string.
// Therefore, you can't just pass a string (because it's a constant, so it becomes a pointer to read-only memory).
[return: MarshalAs(UnmanagedType.Bool)][DllImport("kernel32.dll")]
private static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, [Out]out PROCESS_INFORMATION lpProcessInformation);
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
#endregion
#region Constants
/// <summary>
/// Size of buffer used when retrieving window names.
/// </summary>
public const int MaxWindowNameLength = 100;
//
// winAPI constants.
//
private const short SW_HIDE = 0;
private const short SW_NORMAL = 1;
private const int STARTF_USESTDHANDLES = 0x00000100;
private const int STARTF_USESHOWWINDOW = 0x00000001;
private const int UOI_NAME = 2;
private const int STARTF_USEPOSITION = 0x00000004;
private const int NORMAL_PRIORITY_CLASS = 0x00000020;
private const long DESKTOP_CREATEWINDOW = 0x0002L;
private const long DESKTOP_ENUMERATE = 0x0040L;
private const long DESKTOP_WRITEOBJECTS = 0x0080L;
private const long DESKTOP_SWITCHDESKTOP = 0x0100L;
private const long DESKTOP_CREATEMENU = 0x0004L;
private const long DESKTOP_HOOKCONTROL = 0x0008L;
private const long DESKTOP_READOBJECTS = 0x0001L;
private const long DESKTOP_JOURNALRECORD = 0x0010L;
private const long DESKTOP_JOURNALPLAYBACK = 0x0020L;
private const long AccessRights = DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP | DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL | DESKTOP_READOBJECTS;
#endregion
#region Structures
/// <summary>
/// Stores window handles and titles.
/// </summary>
public struct Window
{
#region Private Variables
private IntPtr m_handle;
private string m_text;
#endregion
#region Public Properties
/// <summary>
/// Gets the window handle.
/// </summary>
public IntPtr Handle
{
get
{
return m_handle;
}
}
/// <summary>
/// Gets teh window title.
/// </summary>
public string Text
{
get
{
return m_text;
}
}
#endregion
#region Construction
/// <summary>
/// Creates a new window object.
/// </summary>
/// <param name="handle">Window handle.</param>
/// <param name="text">Window title.</param>
public Window(IntPtr handle, string text)
{
m_handle = handle;
m_text = text;
}
#endregion
}
#endregion
#region Private Variables
private IntPtr m_desktop;
private string m_desktopName;
private static List<String> m_sc;
private List<IntPtr> m_windows;
private bool m_disposed;
#endregion
#region Public Properties
/// <summary>
/// Gets if a desktop is open.
/// </summary>
public bool IsOpen
{
get
{
return (m_desktop != IntPtr.Zero);
}
}
/// <summary>
/// Gets the name of the desktop, returns null if no desktop is open.
/// </summary>
public string DesktopName
{
get
{
return m_desktopName;
}
}
/// <summary>
/// Gets a handle to the desktop, IntPtr.Zero if no desktop open.
/// </summary>
public IntPtr DesktopHandle
{
get
{
return m_desktop;
}
}
/// <summary>
/// Opens the default desktop.
/// </summary>
public static readonly Desktop Default = Desktop.OpenDefault();
/// <summary>
/// Opens the desktop the user if viewing.
/// </summary>
public static readonly Desktop Input = Desktop.OpenInput();
#endregion
#region Construction/Destruction
/// <summary>
/// Creates a new Desktop object.
/// </summary>
public Desktop()
{
// init variables.
m_desktop = IntPtr.Zero;
m_desktopName = String.Empty;
m_windows = new List<IntPtr>();
m_disposed = false;
}
/// <summary>
/// Creates a new Desktop object.
/// </summary>
public Desktop(string name)
{
// init variables.
m_desktop = IntPtr.Zero;
m_desktopName = name;
m_windows = new List<IntPtr>();
m_disposed = false;
}
// constructor is private to prevent invalid handles being passed to it.
private Desktop(IntPtr desktop)
{
// init variables.
m_desktop = desktop;
m_desktopName = Desktop.GetName(desktop);
m_windows = new List<IntPtr>();
m_disposed = false;
}
~Desktop()
{
// clean up, close the desktop.
Close();
}
#endregion
#region Methods
/// <summary>
/// Closes the handle to a desktop.
/// </summary>
/// <returns>True if an open handle was successfully closed.</returns>
public bool Close()
{
// make sure object isnt disposed.
CheckDisposed();
// check there is a desktop open.
if (m_desktop != IntPtr.Zero)
{
// close the desktop.
bool result = CloseDesktop(m_desktop);
if (result)
{
m_desktop = IntPtr.Zero;
m_desktopName = String.Empty;
}
return result;
}
// no desktop was open, so desktop is closed.
return true;
}
/// <summary>
/// Opens a desktop.
/// </summary>
/// <param name="name">The name of the desktop to open.</param>
/// <returns>True if the desktop was successfully opened.</returns>
public bool Open()
{
// make sure object isnt disposed.
CheckDisposed();
// close the open desktop.
if (m_desktop != IntPtr.Zero)
{
// attempt to close the desktop.
if (!Close()) return false;
}
// open the desktop.
m_desktop = OpenDesktop(m_desktopName, 0, true, AccessRights);
// something went wrong.
if (m_desktop == IntPtr.Zero) return false;
return true;
}
/// <summary>
/// Switches input to the currently opened desktop.
/// </summary>
/// <returns>True if desktops were successfully switched.</returns>
public bool Show()
{
// make sure object isnt disposed.
CheckDisposed();
// make sure there is a desktop to open.
if (m_desktop == IntPtr.Zero) return false;
// attempt to switch desktops.
bool result = SwitchDesktop(m_desktop);
return result;
}
/// <summary>
/// Enumerates the windows on a desktop.
/// </summary>
/// <param name="windows">Array of Desktop.Window objects to recieve windows.</param>
/// <returns>A window colleciton if successful, otherwise null.</returns>
public List<Window> GetWindows()
{
// make sure object isnt disposed.
CheckDisposed();
// make sure a desktop is open.
if (!IsOpen) return null;
// init the List.
m_windows.Clear();
List<Window> windows = new List<Window>();
// get windows.
bool result = EnumDesktopWindows(m_desktop, new EnumDesktopWindowsProc(DesktopWindowsProc), IntPtr.Zero);
// check for error.
if (!result) return null;
// get window names.
IntPtr ptr = Marshal.AllocHGlobal(MaxWindowNameLength);
foreach(IntPtr wnd in m_windows)
{
GetWindowText(wnd, ptr, MaxWindowNameLength);
windows.Add(new Window(wnd, Marshal.PtrToStringAnsi(ptr)));
}
Marshal.FreeHGlobal(ptr);
return windows;
}
private bool DesktopWindowsProc(IntPtr wndHandle, IntPtr lParam)
{
// add window handle to colleciton.
m_windows.Add(wndHandle);
return true;
}
/// <summary>
/// Creates a new process in a desktop.
/// </summary>
/// <param name="path">Path to application.</param>
/// <returns>The process object for the newly created process.</returns>
public Process CreateProcess(string path)
{
return CreateProcess(path, null);
}
/// <summary>
/// Creates a new process in a desktop.
/// </summary>
/// <param name="path">Path to application.</param>
/// <param name="commandLineParameters">Arguments for the application.</param>
/// <returns>The process object for the newly created process.</returns>
public Process CreateProcess(string path, string commandLineParameters)
{
// make sure object isnt disposed.
CheckDisposed();
return Desktop.CreateProcess(path,commandLineParameters,m_desktopName);
}
/// <summary>
/// Prepares a desktop for use by launching the Explorer Shell. For use only on newly created desktops, call straight after CreateDesktop.
/// </summary>
public void Prepare()
{
// make sure object isnt disposed.
CheckDisposed();
// make sure a desktop is open.
if (IsOpen)
{
// load explorer.
CreateProcess("explorer.exe");
}
}
/// <summary>
/// Gets an array of all the processes running on this desktop.
/// </summary>
/// <returns>An array of the processes.</returns>
public Process[] GetProcesses()
{
return GetProcesses( m_desktopName, StringComparison.InvariantCulture);
}
#endregion
#region Static Methods
/// <summary>
/// Enumerates all of the desktops.
/// </summary>
/// <param name="desktops">String array to recieve desktop names.</param>
/// <returns>True if desktop names were successfully enumerated.</returns>
public static string[] GetDesktops()
{
// attempt to enum desktops.
IntPtr windowStation = GetProcessWindowStation();
// check we got a valid handle.
if (windowStation == IntPtr.Zero) return new string[0];
string[] desktops;
// lock the object. thread safety and all.
lock(m_sc = new List<String>())
{
bool result = EnumDesktops(windowStation, new EnumDesktopProc(DesktopProc), IntPtr.Zero);
// something went wrong.
if (!result) return new string[0];
// // turn the collection into an array.
desktops = new string[m_sc.Count];
for(int i = 0; i < desktops.Length; i++) desktops[i] = m_sc[i];
}
return desktops;
}
private static bool DesktopProc(string lpszDesktop, IntPtr lParam)
{
// add the desktop to the collection.
m_sc.Add(lpszDesktop);
return true;
}
/// <summary>
/// Switches to the specified desktop.
/// </summary>
/// <param name="name">Name of desktop to switch input to.</param>
/// <returns>True if desktops were successfully switched.</returns>
public static bool Show(string name)
{
// attmempt to open desktop.
bool result = false;
using (Desktop d = new Desktop(name))
{
result = d.Open();
// something went wrong.
if (!result) return false;
// attempt to switch desktops.
result = d.Show();
}
return result;
}
/// <summary>
/// Gets the desktop of the calling thread.
/// </summary>
/// <returns>Returns a Desktop object for the valling thread.</returns>
public static Desktop GetCurrent()
{
// get the desktop.
return new Desktop(GetThreadDesktop(System.Threading.Thread.CurrentThread.ManagedThreadId));
}
/// <summary>
/// Sets the desktop of the calling thread.
/// NOTE: Function will fail if thread has hooks or windows in the current desktop.
/// </summary>
/// <param name="desktop">Desktop to put the thread in.</param>
/// <returns>True if the threads desktop was successfully changed.</returns>
public static bool SetCurrent(Desktop desktop)
{
// set threads desktop.
if (!desktop.IsOpen) return false;
return SetThreadDesktop(desktop.DesktopHandle);
}
/// <summary>
/// Opens a desktop.
/// </summary>
/// <param name="name">The name of the desktop to open.</param>
/// <returns>If successful, a Desktop object, otherwise, null.</returns>
public static Desktop Open(string name)
{
// open the desktop.
Desktop desktop = new Desktop(name);
bool result = desktop.Open();
// something went wrong.
if (!result) return null;
return desktop;
}
/// <summary>
/// Opens the current input desktop.
/// </summary>
/// <returns>If successful, a Desktop object, otherwise, null.</returns>
public static Desktop OpenInput()
{
// open the desktop.
IntPtr deskptr = OpenInputDesktop(0, true, AccessRights);
if (deskptr == IntPtr.Zero) return null;
return new Desktop(deskptr);
}
/// <summary>
/// Opens the default desktop.
/// </summary>
/// <returns>If successful, a Desktop object, otherwise, null.</returns>
public static Desktop OpenDefault()
{
// opens the default desktop.
return Desktop.Open("Default");
}
/// <summary>
/// Creates a new desktop.
/// </summary>
/// <param name="name">The name of the desktop to create. Names are case sensitive.</param>
/// <returns>If successful, a Desktop object, otherwise, null.</returns>
public static Desktop Create(string name)
{
// make sure desktop doesnt already exist.
if (Desktop.Exists(name))
{
// it exists, so open it.
return Open(name);
}
// attempt to create desktop.
IntPtr deskptr = CreateDesktop(name, IntPtr.Zero, IntPtr.Zero, 0, AccessRights, IntPtr.Zero);
if (deskptr == IntPtr.Zero) return null;
// open the desktop.
return Open(name);
}
/// <summary>
/// Gets the name of a given desktop.
/// </summary>
/// <param name="desktop">Desktop object whos name is to be found.</param>
/// <returns>If successful, the desktop name, otherwise, null.</returns>
public static string GetName(Desktop desktop)
{
// get name.
if (desktop.IsOpen) return null;
return GetName(desktop.DesktopHandle);
}
public static Win32Exception LastError;
/// <summary>
/// Gets the name of a desktop from a desktop handle.
/// </summary>
/// <param name="desktopHandle"></param>
/// <returns>If successful, the desktop name, otherwise, null.</returns>
public static string GetName(IntPtr desktopHandle)
{
// check its not a null pointer.
// null pointers wont work.
if (desktopHandle == IntPtr.Zero) return null;
// get the length of the name.
int needed = 0;
string name = null;
// always returns false, because we pass 0 for available size
GetUserObjectInformation(desktopHandle, UOI_NAME, IntPtr.Zero, 0, ref needed);
// get the name.
IntPtr ptr = Marshal.AllocHGlobal(needed);
if(!GetUserObjectInformation(desktopHandle, UOI_NAME, ptr, needed, ref needed)) {
Marshal.FreeHGlobal(ptr);
LastError = new Win32Exception();
} else {
name = Marshal.PtrToStringAnsi(ptr);
Marshal.FreeHGlobal(ptr);
}
return name;
}
/// <summary>
/// Checks if the specified desktop exists (using a case sensitive search).
/// </summary>
/// <param name="name">The name of the desktop.</param>
/// <returns>True if the desktop exists, otherwise false.</returns>
public static bool Exists(string name)
{
return Desktop.Exists(name, StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Checks if the specified desktop exists.
/// </summary>
/// <param name="name">The name of the desktop.</param>
/// <param name="comparisonType">The type of string comparison to do.</param>
/// <returns>True if the desktop exists, otherwise false.</returns>
public static bool Exists(string name, StringComparison comparisonType)
{
// enumerate desktops.
string[] desktops = Desktop.GetDesktops();
// return true if desktop exists.
foreach(string desktop in desktops)
{
if(desktop.Equals( name, comparisonType )) return true;
}
return false;
}
/// <summary>
/// Creates a new process on the specified desktop.
/// </summary>
/// <param name="path">Path to application.</param>
/// <param name="commandLineParameters">Arguments for the application.</param>
/// <param name="desktop">Desktop name.</param>
/// <returns>A Process object for the newly created process, otherwise, null.</returns>
public static Process CreateProcess(string path, string commandLineParameters, string desktop)
{
if (!Desktop.Exists(desktop)) return null;
// set startup parameters.
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = desktop;
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
//StringBuilder lpPath = new StringBuilder(path);
StringBuilder lpCommandLine = new StringBuilder();
lpCommandLine.Append("\\"");
lpCommandLine.Append(path);
lpCommandLine.Append("\\" ");
lpCommandLine.Append(commandLineParameters);
// lpPath.EnsureCapacity(256);
// create the process.
if(!CreateProcess(null, lpCommandLine.ToString(), IntPtr.Zero, IntPtr.Zero, true, NORMAL_PRIORITY_CLASS, IntPtr.Zero, null, ref si, out pi) ) {
throw new Win32Exception();
}
// Get the process.
return Process.GetProcessById(pi.dwProcessId);
}
/// <summary>
/// Gets an array of all the processes running on the Input desktop.
/// </summary>
/// <returns>An array of the processes.</returns>
public static Process[] GetInputProcesses()
{
return GetProcesses( GetName(Desktop.Input.DesktopHandle), StringComparison.InvariantCulture);
}
/// <summary>
/// Gets an array of all the processes running on the specified desktop.
/// </summary>
/// <param name="desktop">The name of the desktop for which to return processes</param>
/// <returns>An array of the processes.</returns>
public static Process[] GetProcesses(string desktop)
{
return GetProcesses( desktop, StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Gets an array of all the processes running on the specified desktop (using the speficied string comparison)
/// </summary>
/// <param name="desktop">The name of the desktop for which to return processes</param>
/// <param name="comparisonType">The type of string comparison to do</param>
/// <returns>An array of the processes.</returns>
public static Process[] GetProcesses(string desktop, StringComparison comparisonType)
{
// get all processes.
Process[] processes = Process.GetProcesses();
List<Process> procs = new List<Process>();
// cycle through the processes.
foreach(Process process in processes)
{
// check the threads of the process - are they in this one?
foreach(ProcessThread pt in process.Threads)
{
string deskname = GetName(GetThreadDesktop(pt.Id));
if(deskname == null) continue;
// check for a desktop name match.
if (deskname.Equals(desktop,comparisonType))
{
// found a match, add to list, and bail.
procs.Add(process);
break;
} else {
Console.WriteLine("Wow, Really? The '" + deskname + "' desktop showed up!");
}
}
}
return procs.ToArray();
}
#endregion
#region IDisposable
/// <summary>
/// Dispose Object.
/// </summary>
public void Dispose()
{
// dispose
Dispose(true);
// suppress finalisation
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose Object.
/// </summary>
/// <param name="disposing">True to dispose managed resources.</param>
public virtual void Dispose(bool disposing)
{
if (!m_disposed)
{
// dispose of managed resources,
// close handles
Close();
}
m_disposed = true;
}
private void CheckDisposed()
{
// check if disposed
if (m_disposed)
{
// object disposed, throw exception
throw new ObjectDisposedException("");
}
}
#endregion
#region ICloneable
/// <summary>
/// Creates a new Desktop object with the same desktop open.
/// </summary>
/// <returns>Cloned desktop object.</returns>
public object Clone()
{
// make sure object isnt disposed.
CheckDisposed();
Desktop desktop = new Desktop(m_desktopName);
// if a desktop is open, make the clone open it.
if (IsOpen) desktop.Open();
return desktop;
}
#endregion
#region Overrides
/// <summary>
/// Gets the desktop name.
/// </summary>
/// <returns>The desktop name, or a blank string if no desktop open.</returns>
public override string ToString()
{
// return the desktop name.
return m_desktopName;
}
#endregion
}
|
PowerShellCorpus/PoshCode/get-ESXiHostConfigBackup_1.ps1
|
get-ESXiHostConfigBackup_1.ps1
|
<#
.SYNOPSIS
Creates config bundle backup for ESXi hosts. Works where 80 is blocked to ESXi host
Originally script by Alan Renouf (http://www.virtu-al.net/2011/02/23/backing-up-the-esxi-system-image)
Heavily Modified by Jimmy Hester
.DESCRIPTION
Checks for connection to a vCenter or ESXi server
If not connected, connects to the server specified
If already connected, connects to the server listed in $Global:DefaultVIServer
Connects to each vmhost in a vCenter, pulls a backup of its configuration, and saves it to the client machine.
If connected to an ESXi host, it will backup that host.
Once backed up, it will disconnect from the server if the connection was intially created by this script. It will leave pre-existing connections intact.
If run in an environment where access to the ESXi host(s) on port 80 (from the machine running this script) is blocked,
the script will bypass the access failure and download the config bundle directly.
See this VMware Community thread for details: http://communities.vmware.com/thread/419926
.PARAMETER <paramName>
VIServer = The name of the vCenter server or ESXi host to use. If a vCenter server is specified, all the hosts in the vCenter will be backed up
If an ESXi host is specified, only that host will be backed up.
#>
Param (
[string]$VIServer
)
#Check for PowerCLI
If ( (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin VMware.VimAutomation.Core
}
#Change this to a local folder that already exists
$RootFolder = "C:\\admin\\ESXi_Backups\\"
If (($VIServer) -and (-not($VIServer -eq $global:defaultviserver))) {
Connect-VIServer $VIServer -Credential (Get-Credential) | Out-Null
Write-Host ""
Write-Host "Connecting to $VIServer"
Write-Host ""
$Disconnect = $true
}
elseif (!$global:DefaultVIServer) {
Write-Host "Cannot determine which VCenter to use. No backups taken."
Write-Host ""
break
}
else {
$VIServer = $global:DefaultVIServer
Write-Host "Connected to $VIServer"
Write-Host ""
}
$VMhosts = Get-VMHost -Server $VIServer
Foreach ($VMhost in $VMhosts) {
Write-Host "Backing up state for $VMhost"
$Date = Get-Date -f yyyyMMdd_hhmm
$Folder = $RootFolder + "$($VIServer)\\" + $Date
If (-not (test-path $Folder)) {
MD $Folder | Out-Null
}
Get-VMHostFirmware $VMhost -BackupConfiguration -DestinationPath $Folder -ErrorAction SilentlyContinue | Out-Null
#Uncomment next line if the path for $Folder has hyphens
#MV ($RootFolder + "*") $Folder -ErrorAction SilentlyContinue
#This will bypass the port http get failure in environments where port 80 is blocked to the ESXi host.
#This tests to see if the Get-VMHostFirmware cmdlet was able to download the config bundle.
#If not, calls the same https URL as the Get-VMHostFirmware cmdlet
If (-not (test-path $Folder\\configBundle-$vmhost.tgz)){
Invoke-Webrequest https://$vmhost/downloads/configBundle-$vmhost.tgz -outfile $folder\\configBundle-$vmhost.tgz
}
}
If ($Disconnect) {
Write-Host "Disconnecting from $VIServer"
Disconnect-VIServer $VIServer -Confirm:$false | Out-Null
}
Write-Host ""
Write-Host "The config backups for $VIServer are located at:"
Write-Host $Folder
Write-Host ""
|
PowerShellCorpus/PoshCode/Set-OutlookSignature_2.ps1
|
Set-OutlookSignature_2.ps1
|
###########################################################################¡±
#
# NAME: Set-OutlookSignature.ps1
#
# AUTHOR: Jan Egil Ring
# Modifications by Darren Kattan
#
# COMMENT: Script to create an Outlook signature based on user information from Active Directory.
# Adjust the variables in the ¡°Custom variables¡±-section
# Create an Outlook-signature from Microsoft Word (logo, fonts etc) and copy this signature to \\\\domain\\NETLOGON\\sig_files\\$CompanyName\\$CompanyName.docx
# This script supports the following keywords:
# DisplayName
# Title
# Email
#
# See the following blog-posts for more information:
# http://blog.powershell.no/2010/01/09/outlook-signature-based-on-user-information-from-active-directory
# http://www.immense.net/deploying-unified-email-signature-template-outlook
#
# Tested on Office 2003, 2007 and 2010
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 09.01.2010 ¨C Initial release
# 1.1 11.09.2010 ¨C Modified by Darren Kattan
# - Removed bookmarks. Now uses simple find and replace for DisplayName, Title, and Email.
# - Email address is generated as a link
# - Signature is generated from a single .docx file
# - Removed version numbers for script to run. Script runs at boot up when it sees a change in the ¡°Date Modified¡± property of your signature template.
#
#
###########################################################################¡±
#Custom variables
$CompanyName = ¡®Contoso¡¯
$DomainName = ¡®contoso.local¡¯
$SigSource = ¡°\\\\$DomainName\\netlogon\\sig_files\\$CompanyName¡±
$ForceSignatureNew = ¡¯1¡ä #When the signature are forced the signature are enforced as default signature for new messages the next time the script runs. 0 = no force, 1 = force
$ForceSignatureReplyForward = ¡¯1¡ä #When the signature are forced the signature are enforced as default signature for reply/forward messages the next time the script runs. 0 = no force, 1 = force
#Environment variables
$AppData=(Get-Item env:appdata).value
$SigPath = ¡®\\Microsoft\\Signatures¡¯
$LocalSignaturePath = $AppData+$SigPath
$RemoteSignaturePathFull = $SigSource+¡¯\\'+$CompanyName+¡¯.docx¡¯
#Get Active Directory information for current user
$UserName = $env:username
$Filter = ¡°(&(objectCategory=User)(samAccountName=$UserName))¡±
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = $Filter
$ADUserPath = $Searcher.FindOne()
$ADUser = $ADUserPath.GetDirectoryEntry()
$ADDisplayName = $ADUser.DisplayName
$ADEmailAddress = $ADUser.mail
$ADTitle = $ADUser.title
$ADTelePhoneNumber = $ADUser.TelephoneNumber
#Setting registry information for the current user
$CompanyRegPath = ¡°HKCU:\\Software\\¡±+$CompanyName
if (Test-Path $CompanyRegPath)
{}
else
{New-Item -path ¡°HKCU:\\Software¡± -name $CompanyName}
if (Test-Path $CompanyRegPath¡¯\\Outlook Signature Settings¡¯)
{}
else
{New-Item -path $CompanyRegPath -name ¡°Outlook Signature Settings¡±}
$SigVersion = (gci $RemoteSignaturePathFull).LastWriteTime #When was the last time the signature was written
$ForcedSignatureNew = (Get-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯).ForcedSignatureNew
$ForcedSignatureReplyForward = (Get-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯).ForcedSignatureReplyForward
$SignatureVersion = (Get-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯).SignatureVersion
Set-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯ -name SignatureSourceFiles -Value $SigSource
$SignatureSourceFiles = (Get-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯).SignatureSourceFiles
#Forcing signature for new messages if enabled
if ($ForcedSignatureNew -eq ¡¯1¡ä)
{
#Set company signature as default for New messages
$MSWord = New-Object -com word.application
$EmailOptions = $MSWord.EmailOptions
$EmailSignature = $EmailOptions.EmailSignature
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries
$EmailSignature.NewMessageSignature=$CompanyName
$MSWord.Quit()
}
#Forcing signature for reply/forward messages if enabled
if ($ForcedSignatureReplyForward -eq ¡¯1¡ä)
{
#Set company signature as default for Reply/Forward messages
$MSWord = New-Object -com word.application
$EmailOptions = $MSWord.EmailOptions
$EmailSignature = $EmailOptions.EmailSignature
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries
$EmailSignature.ReplyMessageSignature=$CompanyName
$MSWord.Quit()
}
#Copying signature sourcefiles and creating signature if signature-version are different from local version
if ($SignatureVersion -eq $SigVersion){}
else
{
#Copy signature templates from domain to local Signature-folder
Copy-Item ¡°$SignatureSourceFiles\\*¡± $LocalSignaturePath -Recurse -Force
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False
#Insert variables from Active Directory to rtf signature-file
$MSWord = New-Object -com word.application
$fullPath = $LocalSignaturePath+¡¯\\'+$CompanyName+¡¯.docx¡¯
$MSWord.Documents.Open($fullPath)
$FindText = ¡°DisplayName¡±
$ReplaceText = $ADDisplayName.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )
$FindText = ¡°Title¡±
$ReplaceText = $ADTitle.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $ReplaceAll )
$MSWord.Selection.Find.Execute(¡°Email¡±)
$MSWord.ActiveDocument.Hyperlinks.Add($MSWord.Selection.Range, ¡°mailto:¡±+$ADEmailAddress.ToString(), $missing, $missing, $ADEmailAddress.ToString())
$MSWord.ActiveDocument.Save()
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], ¡°wdFormatHTML¡±);
[ref]$BrowserLevel = ¡°microsoft.office.interop.word.WdBrowserLevel¡± -as [type]
$MSWord.ActiveDocument.WebOptions.OrganizeInFolder = $true
$MSWord.ActiveDocument.WebOptions.UseLongFileNames = $true
$MSWord.ActiveDocument.WebOptions.BrowserLevel = $BrowserLevel::wdBrowserLevelMicrosoftInternetExplorer6
$path = $LocalSignaturePath+¡¯\\'+$CompanyName+¡±.htm¡±
$MSWord.ActiveDocument.saveas([ref]$path, [ref]$saveFormat)
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], ¡°wdFormatRTF¡±);
$path = $LocalSignaturePath+¡¯\\'+$CompanyName+¡±.rtf¡±
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat)
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], ¡°wdFormatText¡±);
$path = $LocalSignaturePath+¡¯\\'+$CompanyName+¡±.rtf¡±
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$saveFormat)
$path = $LocalSignaturePath+¡¯\\'+$CompanyName+¡±.txt¡±
$MSWord.ActiveDocument.SaveAs([ref] $path, [ref]$SaveFormat::wdFormatText)
$MSWord.ActiveDocument.Close()
$MSWord.Quit()
}
#Stamp registry-values for Outlook Signature Settings if they doesn`t match the initial script variables. Note that these will apply after the second script run when changes are made in the ¡°Custom variables¡±-section.
if ($ForcedSignatureNew -eq $ForceSignatureNew){}
else
{Set-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯ -name ForcedSignatureNew -Value $ForceSignatureNew}
if ($ForcedSignatureReplyForward -eq $ForceSignatureReplyForward){}
else
{Set-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯ -name ForcedSignatureReplyForward -Value $ForceSignatureReplyForward}
if ($SignatureVersion -eq $SigVersion){}
else
{Set-ItemProperty $CompanyRegPath¡¯\\Outlook Signature Settings¡¯ -name SignatureVersion -Value $SigVersion}
|
PowerShellCorpus/PoshCode/Start-Verify.ps1
|
Start-Verify.ps1
|
# Author: Steven Murawski http://www.mindofroot.com
# This script creates two functions (and a helper function). One starts logging all commands entered,
# and the second removes the logging.
# This script is similar to the Start-Transcript, but only logs the command line and not the output.
function New-ScriptBlock()
{
param ([string]$scriptblock)
$executioncontext.InvokeCommand.NewScriptBlock($scriptblock.trim())
}
function Start-Verify ()
{
param ($logfile = 'c:\\scripts\\powershell\\logs\\verify.txt')
$lastcmd = 'get-history | select -property CommandLine -Last 1 | Out-File -Append {0}' -f $logfile
Get-Content -Path function:\\prompt | ForEach-Object { $function:prompt = New-ScriptBlock ($_.toString() +"`n$lastcmd") } | Out-Null
}
function Stop-Verify ()
{
$lastcmd = 'get-history.*$'
Get-Content -Path function:\\prompt | ForEach-Object { $function:prompt = New-ScriptBlock ($_.tostring() -replace "$lastcmd")} | Out-Null
}
|
PowerShellCorpus/PoshCode/Get-ADGroupMembers_4.ps1
|
Get-ADGroupMembers_4.ps1
|
Function Get-ADGroupMembers
{
<#
.SYNOPSIS
Return a collection of users in an ActiveDirectory group.
.DESCRIPTION
This function returns an object that contains all the properties of a user object. This function
works for small groups as well as groups in excess of 1000.
.PARAMETER UserGroup
The name of the group to get membership from.
.PARAMETER UserDomain
The LDAP URL of the domain that the group resides in.
.EXAMPLE
Get-ADGroupMembers -UserGroup Managers |Format-Table -Property name, distinguishedName, cn
name distinguishedName cn
---- ----------------- --
{Steve Roberts} {CN=Steve Roberts,CN=Users,DC... {Steve Roberts}
{S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533...
{S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533...
{Matt Temple} {CN=Matt Temple,CN=Users,DC=c... {Matt Temple}
...
Description
-----------
This example shows passing in a group name, but leaving the default domain name in place.
.NOTES
The context under which this script is run must have rights to pull infromation from ActiveDirectory.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement#Get-ADGroupMembers
#>
Param
(
$UserGroup = "Domain Users",
$UserDomain = ([ADSI]"LDAP://DC=company,DC=com")
)
Begin
{
$DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($UserDomain.Path)
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$LDAPFilter = "(&(objectCategory=Group)(name=$($UserGroup)))"
$DirectorySearcher.SearchRoot = $DirectoryEntry
$DirectorySearcher.PageSize = 1000
$DirectorySearcher.Filter = $LDAPFilter
$DirectorySearcher.SearchScope = "Subtree"
$SearchResult = $DirectorySearcher.FindAll()
$UserAccounts = @()
}
Process
{
foreach ($Item in $SearchResult)
{
$Group = $Item.GetDirectoryEntry()
$Members = $Group.member
If ($Members -ne $Null)
{
foreach ($User in $Members)
{
$UserObject = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($User)")
If ($UserObject.objectCategory.Value.Contains("Group"))
{
}
Else
{
$ThisUser = New-Object -TypeName PSObject -Property @{
cn = $UserObject.cn
distinguishedName = $UserObject.distinguishedName
name = $UserObject.name
nTSecurityDescriptor = $UserObject.nTSecurityDescriptor
objectCategory = $UserObject.objectCategory
objectClass = $UserObject.objectClass
objectGUID = $UserObject.objectGUID
objectSID = $UserObject.objectSID
showInAdvancedViewOnly = $UserObject.showInAdvancedViewOnly
}
}
$UserAccounts += $ThisUser
}
}
}
}
End
{
Return $UserAccounts
}
}
|
PowerShellCorpus/PoshCode/LibraryDirectory.ps1
|
LibraryDirectory.ps1
|
## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nSet-StrictMode -Version Latest\n\n## Get the size of all the items in the current directory\nfunction Get-DirectorySize\n{\n <#\n\n .EXAMPLE\n\n PS > $DebugPreference = "Continue"\n PS > Get-DirectorySize\n DEBUG: Current Directory: D:\\lee\\OReilly\\Scripts\\Programs\n Directory size: 46,581 bytes\n PS > $DebugPreference = "SilentlyContinue"\n PS > $VerbosePreference = "Continue"\n PS > Get-DirectorySize\n VERBOSE: Getting size\n VERBOSE: Got size: 46581\n Directory size: 46,581 bytes\n PS > $VerbosePreference = "SilentlyContinue"\n\n #>\n\n Write-Debug "Current Directory: $(Get-Location)"\n\n Write-Verbose "Getting size"\n $size = (Get-ChildItem | Measure-Object -Sum Length).Sum\n Write-Verbose "Got size: $size"\n\n Write-Host ("Directory size: {0:N0} bytes" -f $size)\n}\n\n## Get the list of items in a directory, sorted by length\nfunction Get-ChildItemSortedByLength($path = (Get-Location), [switch] $Problematic)\n{\n <#\n \n .EXAMPLE\n\n PS > Get-ChildItemSortedByLength -Problematic\n out-lineoutput : Object of type "Microsoft.PowerShell.Commands.Internal.Fo\n rmat.FormatEntryData" is not legal or not in the correct sequence. This is\n likely caused by a user-specified "format-*" command which is conflicting\n with the default formatting.\n\n #>\n\n if($Problematic)\n {\n ## Problematic version\n Get-ChildItem $path | Format-Table | Sort Length\n }\n else\n {\n ## Fixed version\n Get-ChildItem $path | Sort Length | Format-Table\n }\n}
|
PowerShellCorpus/PoshCode/Import Group Policies.ps1
|
Import Group Policies.ps1
|
##############################################
##Import group policies from a folder to a Domain Controller
##Author: Adam Liquorish
##
##*Currently will only run on Server 2008 R2
##*Script is based on the Microsoft Visual Basic Script for importing group policies.
##*Server doesnt need to be defined as PDC emulator will be contacted by default
##############################################
######Define Parameters
param(
[Parameter(Mandatory=$true,
HelpMessage="Enter Path for input ie c:\\Temp\\output.html.")]
[ValidateNotNullOrEmpty()]
[string]$outputpath=$(Read-Host -prompt "Path for input"),
[Parameter(Mandatory=$true,
HelpMessage="Enter Domain")]
[ValidateNotNullOrEmpty()]
[string]$computername=$(Read-Host -prompt "Domain Name")
)
######Import Modules
import-module grouppolicy
######End Import Modules
######Define Variables
#Commented out due to introduction of parameters
#zeroize variables
$start=get-date
$prog=1
$i=$null
$a=$null
$b=$null
$c=$null
$max=$null
##Function to take gpo name from each xml
#Start Function
function GPOName ($b)
{
([xml](get-content $b)).GPO.Name
}
#End function
$a=get-childitem -recurse $path
$b=$a|where-object {$_.Name -eq "gpreport.xml"}
$c=foreach ($test in $b){GPOName($test.fullname)}
$c|
Foreach-object {
#Counter for Progress Bar
$max=$b.length
$i++
#Import GPO
Import-GPO -BackupGpoName $_ -TargetName $_ -path $path -CreateIfNeeded -Dom $domain
#Write Progress
Write-Progress -activity "Adding GPO's" -status "Added $i of $max" -PercentComplete (($i/$b.length)*100) -CurrentOperation $_}
Write-Host "Completed....Total Number of GPO's imported:"$b.length
|
PowerShellCorpus/PoshCode/finddupe_18.ps1
|
finddupe_18.ps1
|
# new version has more error handling, "-delete" and "-noprompt" options.
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
$starttime=[datetime]::now
write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]"
$matches = 0 # initialize number of matches for summary.
$filesdeleted = 0 # number of files deleted.
$bytesrec = 0 # Number of bytes recovered.
$del = $false # delete duplicates
$noprompt = $false # delete without prompting toggle
$args | ?{$_ -eq "-delete"} |%{$del=$true}
$args | ?{$_ -eq "-noprompt"} | %{$noprompt=$true}
$files=@(dir -ea 0 -recurse ($args | ?{$_ -ne "-delete" -and $_ -ne "-noprompt"} |?{if ((get-item -ea 0 $_) -eq $null){write-host "`aError: " -f red -nonewline; write-host "$_ not found.";exit} else {$_}})|?{$_.psiscontainer -ne $true} )
if ($files.count -lt 2) {"Need at least two files to compare.`a";exit}
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($filecheck.md5 -eq $null)
{
$md5 = (get-md5 $filecheck.fullname)
$filecheck = $filecheck | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($files[$c].md5 -eq $null)
{
$md5 = (get-md5 $files[$c].fullname)
$files[$c] = $files[$c] | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($filecheck.md5 -eq $files[$c].md5)
{
write-host "Size and MD5 match: " -fore red -nonewline
write-host "`"$($filecheck.fullname)`"" -nonewline
write-host " and " -nonewline
write-host "`"$($files[$c].fullname)`""
$matches += 1
if ($del -eq $true)
{
if ($noprompt -eq $true)
{
del $files[$c].fullname
write-host "Deleted duplicate: " -f red -nonewline
write-host "$($files[$c].fullname)."
}
else
{
del $files[$c].fullname -confirm
}
if ((get-item -ea 0 $files[$c].fullname) -eq $null)
{
$filesdeleted += 1
$bytesrec += $files[$c].length
}
}
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of duplicates found: $matches."
Write-host "Number of duplicates deleted: $filesdeleted." # Display number of duplicate files deleted and bytes recovered.
write-host "$bytesrec bytes recovered."
write-host ""
write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)"
write-host ""
|
PowerShellCorpus/PoshCode/WhoIs_1.ps1
|
WhoIs_1.ps1
|
param([String] $DomainName = '192.168.0.1')
$socket = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
$Socket.Connect('whois.arin.net', 43) | out-null
$bytes = [System.Text.Encoding]::ASCII.GetBytes($domainName + "`n")
$Socket.Send($bytes) | out-null
$bytes = [Array]::CreateInstance("byte", 2048)
$Socket.Receive($bytes) | out-null
$result = [System.Text.Encoding]::ASCII.GetString($bytes).Trim()
$Socket.Close()
$Data = New-Object Object
$Data | Add-Member NoteProperty Raw ($result)
$result -split "`n" | % {
if (![String]::IsNullOrEmpty($_)) {
$num = $_.IndexOf(":")
if ($num -gt 0) {
$itemName = $_.SubString(0,$num).Trim()
$itemValue = $_.SubString($num+1).Trim()
if (($Data | Get-Member $itemName)) {
$Data.($itemName) += "|" + $itemValue
}
else {
$Data | Add-Member NoteProperty ($itemName) ($itemValue)
}
}
}
}
$Data
|
PowerShellCorpus/PoshCode/Enable_Configure SNMP.ps1
|
Enable_Configure SNMP.ps1
|
#Powershell Script To Install SNMP Services (SNMP Service, SNMP WMI Provider)
#Variables :)
$pmanagers = "ADD YOUR MANAGER(s)"
$commstring = "ADD YOUR COMM STRING"
#Import ServerManger Module
Import-Module ServerManager
#Check If SNMP Services Are Already Installed
$check = Get-WindowsFeature | Where-Object {$_.Name -eq "SNMP-Services"}
If ($check.Installed -ne "True") {
#Install/Enable SNMP Services
Add-WindowsFeature SNMP-Services | Out-Null
}
##Verify Windows Servcies Are Enabled
If ($check.Installed -eq "True"){
#Set SNMP Permitted Manager(s) ** WARNING : This will over write current settings **
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v 1 /t REG_SZ /d localhost /f | Out-Null
#Used as counter for incremting permitted managers
$i = 2
Foreach ($manager in $pmanagers){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v $i /t REG_SZ /d $manager /f | Out-Null
$i++
}
#Set SNMP Community String(s)- *Read Only*
Foreach ( $string in $commstring){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\ValidCommunities" /v $string /t REG_DWORD /d 4 /f | Out-Null
}
}
Else {Write-Host "Error: SNMP Services Not Installed"}
|
PowerShellCorpus/PoshCode/Out-Balloon_3.ps1
|
Out-Balloon_3.ps1
|
<#
.Synopsis
Makes a baloon tip in the notification area
.Description
With just a few arguments, it is easy to make some text appear in a little balloon.
You can specify an icon file (*.ico) with the -icon argument, if you don't then
the first icon of the host is used.
out-balloon accepts pipeline input, strings only please.
It blocks for the duration of the balloon display, 3 seconds by default. Simple
fixes for this are welcome.
timeout should be an integer value.
INSTALLATION:
um, save this text in a file named out-balloon.ps1 in your path
.Parameter BuiltInIcon
Must be one of none, Info, warning, error.
.Parameter TimeoutSeconds
Number of Seconds to display the Tool tip for
.Example
"job done." | out-balloon
.Example
out-balloon "hey, your job is done." -icon "C:\\Program Files\\Microsoft Office\\Office12\\MYSL.ICO"
.Example
out-balloon "hey, your job is done." -title "Printer Server" -BuiltInIcon info
#>
param(
[Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)]
[Alias('output')]
[string]$text,
[string]$iconFile,
[string]$title,
[string]$BuiltInIcon,
[int32]$TimeoutSeconds = 3
)
begin
{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
if( $BuiltInIcon )
{
if( $title -eq $null )
{
write-error "You must supply a title to dislay the BuiltInIcon!"
}
}
if( $iconFile -and $ToolTipIcon)
{
write-error "Cannot supply -IconFile and ToolTipIcon parameters together."
}
$not = new-object System.Windows.Forms.NotifyIcon
if ($icon -eq $null)
{
if ($win32extraciconex -eq $null)
{
$script:ExtractIconEx = Add-Type ¢memberDefinition @"
[DllImport("Shell32", CharSet=CharSet.Auto)]
private static extern int ExtractIconEx (string lpszFile, int nIconIndex,
IntPtr[] phIconLarge,IntPtr[] phIconSmall,int nIcons);
[DllImport("user32.dll", EntryPoint="DestroyIcon", SetLastError=true)]
private static extern int DestroyIcon(IntPtr hIcon);
public static System.Drawing.Icon ExtractIconFromExe(string file, bool large)
{
int readIconCount = 0;
IntPtr[] hDummy = new IntPtr[1] {IntPtr.Zero};
IntPtr[] hIconEx = new IntPtr[1] {IntPtr.Zero};
try
{
if(large)
readIconCount = ExtractIconEx(file,0, hIconEx, hDummy, 1);
else
readIconCount = ExtractIconEx(file,0, hDummy, hIconEx, 1);
if(readIconCount > 0 && hIconEx[0] != IntPtr.Zero)
{
System.Drawing.Icon extractedIcon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(hIconEx[0]).Clone();
return extractedIcon;
}
else // NO ICONS READ
return null;
}
catch(Exception ex)
{
throw new ApplicationException("Failed extracting icon", ex);
}
finally
{
foreach(IntPtr ptr in hIconEx)
if(ptr != IntPtr.Zero)
DestroyIcon(ptr);
foreach(IntPtr ptr in hDummy)
if(ptr != IntPtr.Zero)
DestroyIcon(ptr);
}
}
"@ -name ōWin32ExtractIconExö -namespace win32api ¢passThru -ReferencedAssemblies "System.Drawing"
}
$not.Icon = $extractIconEx::ExtractIconFromExe((get-process -Id $pid).mainmodule.filename, $true)
}
else
{
$not.Icon = new-object System.Drawing.Icon($iconFile)
}
$not.visible = $true
}
process
{
$not.BalloonTipText = $text
$not.BalloonTipTitle = $title
if( $BuiltInIcon) { $not.BalloonTipIcon = $BuiltInIcon }
$not.ShowBalloonTip($timeout)
sleep $TimeoutSeconds
}
end
{
$not.dispose()
}
|
PowerShellCorpus/PoshCode/test connectivity.ps1
|
test connectivity.ps1
|
$ping = new-object System.Net.NetworkInformation.Ping
$isbad = $true;
do {
try {
$Reply = $ping.send('www.yahoo.com')
if ($Reply.status –ne “Success”) { $txt = "$(get-date) problem" ; write-Host $txt ; $txt | out-File -append c:\\downloads\\jetstreamlog.txt}
else {
if ($isbad) {$isbad = $false;$txt = "$(get-date) RECOVERED";write-Host $txt ; $txt | out-File -append c:\\downloads\\jetstreamlog.txt }
$txt = "$(get-date) good" ;write-Host $txt }
}
catch {
$isbad = $true;
$txt = "$(get-date) EXCEPTION" ; write-Host $txt ; $txt | out-File -append c:\\downloads\\jetstreamlog.txt
}
sleep 4
}
while ($true)
|
PowerShellCorpus/PoshCode/LNK file testing_1.ps1
|
LNK file testing_1.ps1
|
param(
$Path = (Split-Path $PSHOME -Qualifier)
)
if($lnks -eq $null) {
$lnks = ls $Path -Recurse -Filter "*.lnk"
}
$wsh = New-Object -ComObject WScript.Shell;
foreach($lnk in $lnks) {
$lnko = $wsh.CreateShortcut($lnk.fullname);
$rtn = New-Object psobject -Property @{
"FilePath" = $lnk.FullName;
"TargetPath" = $lnko.TargetPath;
};
Add-Member -InputObject $rtn -MemberType NoteProperty -Name TargetExists -Value ($lnko.TargetPath -ne "" -and (Test-Path $lnko.TargetPath))
Add-Member -InputObject $rtn -MemberType ScriptProperty -Name IsUNC -Value {return $this.TargetPath.StartsWith("\\\\"); }
$rtn;
}
|
PowerShellCorpus/PoshCode/DefaultParameterValues_3.ps1
|
DefaultParameterValues_3.ps1
|
# DefaultParameters Module
# 1.4 - removed extra parameter set to get parameter binding working better
# - added default aliases (sdp/gdp/rmdp)
#requires -version 3.0
# 1.3 - fixed denable/disable, added get and remove, and improved import and set
# 1.2 - added help and commands to enable/disable the defaults
# 1.0 - initial release
function Export-DefaultParameter {
#.Synopsis
# Exports the current default parameter values
[CmdletBinding()]
param(
# The path to export default parameter values to (defaults to "DefaultParameterValues.clixml" in your profile directory)
[String]$Path = $(Join-Path (Split-Path $Profile.CurrentUserAllHosts -Parent) DefaultParameterValues.clixml)
)
Export-CliXml -InputObject $Global:PSDefaultParameterValues -Path $Path
}
function Import-DefaultParameter {
#.Synopsis
# Imports new default parameter values
[CmdletBinding()]
param(
# The path to import default parameter values from (defaults to "DefaultParameterValues.clixml" in your profile directory)
[String]$Path = $(Join-Path (Split-Path $Profile.CurrentUserAllHosts -Parent) DefaultParameterValues.clixml),
# If set, overwrite current values (otherwise, keep current values)
[Switch]$Force
)
$TempParameterValues = $Global:PSDefaultParameterValues
if(Test-Path $Path) {
[System.Management.Automation.DefaultParameterDictionary]$NewValues =
Import-CliXml -Path ${ProfileDir}\\DefaultParameterValues.clixml
$repeats = @()
foreach($key in $NewValues.Keys) {
# don't import the disabled state, that's just silly
if($key -eq "disabled") { continue }
if($Global:PSDefaultParameterValues.ContainsKey($key)) {
$command,$parameter = $key -split ":"
if($Force) {
$repeats += [PSCustomObject]@{Command=$Command;Parameter=$Parameter;NewDefault=$NewValues.$key;OldDefault=$Global:PSDefaultParameterValues.$Key}
$Global:PSDefaultParameterValues.$Key = $NewValues.$key
} else {
$repeats += [PSCustomObject]@{Command=$Command;Parameter=$Parameter;CurrentDefault=$Global:PSDefaultParameterValues.$Key;SkippedValue=$NewValues.$key}
}
} else {
$Global:PSDefaultParameterValues.$Key = $NewValues.$key
}
}
if($repeats.Count) {
$Width = &{
$Local:ErrorActionPreference = "SilentlyContinue"
$Width = $Host.UI.RawUI.BufferSize.Width - 2
if($Width) { $Width } else { 80 }
}
if($Force) {
Write-Warning ("Some defaults overwritten:`n{0}" -f ($repeats | Out-String -Width $Width))
} else {
Write-Warning ("Some defaults already defined, use -Force to overwrite:`n{0}" -f ($repeats | Out-String -Width $Width))
}
}
# Make sure that everything is enabled
$Global:PSDefaultParameterValues["Disabled"] = $false
} else {
Write-Warning "Default Parameter file not found: '$Path'"
}
}
function Set-DefaultParameter {
#.Synopsis
# Sets a default parameter value for a command
#.Description
# Safely sets the default parameter value for a command, making sure that you've correctly typed the command and parameter combination
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")]
param(
# The command that you want to change the default value of a parameter for
[parameter(Position=0,Mandatory=$true)]
$Command,
# The name of the parameter that you want to change the default value for
[parameter(Position=1,Mandatory=$true)]
[String]$Parameter,
# The new default parameter value
[parameter(Position=2,Mandatory=$true)]
$Value
)
Write-Verbose ($PSBoundParameters | Out-String)
if($parameter.StartsWith("-")) {
$parameter = $parameter.TrimStart("-")
}
## Resolve the parameter to be sure
$cmd = Get-Command $command | Select -First 1
while($cmd.CommandType -eq "Alias") {
$cmd = Get-Command $cmd.Definition | Select -First 1
}
$parameters = $cmd.Parameters.Values
$param = @($parameters | Where-Object { $_.Name -match $parameter -or $_.Aliases -match $parameter} | Select -Expand Name -Unique)
if(!$param) {
$param = @($parameters | Where-Object { $_.Name -match "${parameter}*"} | Select -First 1 -Expand Name)
if(!$param) {
$param = @($parameters | Where-Object { $_.Aliases -match "${parameter}*"} | Select -First 1 -Expand Name)
}
}
if($param.Count -eq 1) {
$Command = $Cmd.Name
Write-Verbose "Setting Parameter $parameter on ${Command} to default: $($param[0])"
$Key = "${Command}:$($param[0])"
if( $Global:PSDefaultParameterValues.ContainsKey($Key) ) {
$WI = "Overwrote the default parameter value for '$Key' with $Value"
$CF = "Overwrite the existing default parameter value for '$Key'? ($($Global:PSDefaultParameterValues.$Key))"
} else {
$WI = "Added a default parameter value for '$Key' = $Value"
$CF = "Add a default parameter value for '$Key'? ($($Global:PSDefaultParameterValues.$Key))"
}
if($PSCmdlet.ShouldProcess( $WI, $CI, "Setting Default Parameter Values" )) {
$Global:PSDefaultParameterValues.$Key = $Value
}
} else {
Write-Warning "Parameter $parameter not found on ${Command}"
}
}
function Get-DefaultParameter {
#.Synopsis
# Gets the default parameter value for a command, if it's been set
#.Description
# Gets the default parameter value for a command from $PSDefaultParameterValues
[CmdletBinding()]
param(
# The command that you want to change the default value of a parameter for (allows wildcards)
[parameter(Position=0,Mandatory=$false)]
[string]$Command = "*",
# The name of the parameter that you want to change the default value for (allows wildcards)
[parameter(Position=1,Mandatory=$true)]
[string]$Parameter = "*"
)
if($parameter.StartsWith("-")) {
$parameter = $parameter.TrimStart("-")
}
$repeats = @()
foreach($key in $Global:PSDefaultParameterValues.Keys) {
# Handle the disabled state:
if($key -eq "disabled" -and $Global:PSDefaultParameterValues["Disabled"]) {
Write-Warning "Default Parameter Values are DISABLED and will not be used:"
continue
}
if($key -like "${Command}:${Parameter}*") {
$Cmd,$Param = $key -split ":"
$repeats += [PSCustomObject]@{Command=$Cmd;Parameter=$Param;CurrentDefault=$Global:PSDefaultParameterValues.$Key}
} else {
Write-Verbose "'$key' is -not -like '${Command}:${Parameter}*'"
}
}
$repeats
}
function Remove-DefaultParameter {
#.Synopsis
# Removed the default parameter value for a command, if it's been set
#.Description
# Removes the default parameter value for a command from $PSDefaultParameterValues
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")]
param(
# The command that you want to change the default value of a parameter for (allows wildcards)
[parameter(Position=0,Mandatory=$false)]
[string]$Command = "*",
# The name of the parameter that you want to change the default value for (allows wildcards)
[parameter(Position=1,Mandatory=$true)]
[string]$Parameter
)
if($parameter.StartsWith("-")) {
$parameter = $parameter.TrimStart("-")
}
$keys
foreach($key in $Global:PSDefaultParameterValues.Keys | Where { $_ -like "${Command}:${Parameter}*" }) {
# Handle the disabled state:
if($key -ne "disabled") {
if($PSCmdlet.ShouldProcess( "Removed the default parameter value for '$Key'",
"Remove the default parameter value for '$Key'?",
"Removing Default Parameter Values" )) {
$Global:PSDefaultParameterValues.Remove($key)
}
}
}
}
function Disable-DefaultParameter {
#.Synopsis
# Turns OFF default parameters
#.Description
# By setting $PSDefaultParameterValues["Disabled"] to $true, we make sure that NONE of our default parameter values will be used
[CmdletBinding()]
param()
$Global:PSDefaultParameterValues["Disabled"]=$true
}
function Enable-DefaultParameter {
#.Synopsis
# Turns ON default parameters
#.Description
# By setting $PSDefaultParameterValues["Disabled"] to $false, we make sure that all of our default parameter values will be used
[CmdletBinding()]
param()
$Global:PSDefaultParameterValues["Disabled"]=$false
}
Set-Alias Add-DefaultParameter Set-DefaultParameter -ErrorAction SilentlyContinue
Set-Alias sdp Set-DefaultParameter -ErrorAction SilentlyContinue
Set-Alias gdp Get-DefaultParameter -ErrorAction SilentlyContinue
Set-Alias rmdp Remove-DefaultParameter -ErrorAction SilentlyContinue
Set-Alias ipdp Import-DefaultParameter -ErrorAction SilentlyContinue
Set-Alias exdp Export-DefaultParameter -ErrorAction SilentlyContinue
# Set-Alias ddp Disable-DefaultParameter -ErrorAction SilentlyContinue
# Set-Alias edp Disable-DefaultParameter -ErrorAction SilentlyContinue
Import-DefaultParameter
Export-ModuleMember -Alias * -Function Set-DefaultParameter, Get-DefaultParameter, Remove-DefaultParameter, `
Import-DefaultParameter, Export-DefaultParameter, `
Enable-DefaultParameter, Disable-DefaultParameter
|
PowerShellCorpus/PoshCode/4bbeb588-aa6d-475c-861b-05a432703d58.ps1
|
4bbeb588-aa6d-475c-861b-05a432703d58.ps1
|
function CreateVDS(
$dvsName, $datacenter, $vmHost, $physicalNic, $portGroupType = "earlyBinding", `
[array]$portGroupNameList = @(),[array]$uplinkList = @() ) {
# ------- Create vDS ------- #
$dvsCreateSpec = New-Object VMware.Vim.DVSCreateSpec
$dvsCreateSpec.configSpec = New-Object VMware.Vim.DVSConfigSpec
$dvsCreateSpec.configSpec.name = $dvsName
$dvsCreateSpec.configSpec.uplinkPortPolicy =
New-Object VMware.Vim.DVSNameArrayUplinkPortPolicy
if ($uplinkList.Count -eq 0) {
$dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName =
New-Object System.String[] (2)
$dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[0] = "dvUplink1"
$dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[1] = "dvUplink2"
} else {
$dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName =
New-Object System.String[] ($uplinkList.Count)
for ($i = 0; $i -lt $uplinkList.Count; $i++){
$dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[$i] =
$uplinkList[$i]
}
}
$hostIdValue = ($vmHost.Id.Split('-', 2))[1]
$dvsCreateSpec.configSpec.host =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec[] (1)
$dvsCreateSpec.configSpec.host[0] =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec
$dvsCreateSpec.configSpec.host[0].operation = "add"
$dvsCreateSpec.configSpec.host[0].host =
New-Object VMware.Vim.ManagedObjectReference
$dvsCreateSpec.configSpec.host[0].host.type = "HostSystem"
$dvsCreateSpec.configSpec.host[0].host.value = $hostIdValue
$dvsCreateSpec.configSpec.host[0].backing =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking
$dvsCreateSpec.configSpec.host[0].backing =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking
$dvsCreateSpec.configSpec.host[0].backing.pnicSpec =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec[] (1)
$dvsCreateSpec.configSpec.host[0].backing.pnicSpec[0] =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec
$dvsCreateSpec.configSpec.host[0].backing.pnicSpec[0].pnicDevice =
$physicalNic.DeviceName
$networkFolderView = Get-View -Id (($datacenter | Get-View).NetworkFolder)
$dvsMoRef = $networkFolderView.CreateDVS($dvsCreateSpec)
# ------- Add vDPortGroup ------- #
if ($portGroupNameList.Count -eq 0){
$portGroupNameList += "dvPortGroup"
}
$dvProtGroupSpec =
New-Object VMware.Vim.DVPortgroupConfigSpec[] ($portGroupNameList.Length)
for ($i = 0; $i -lt $portGroupNameList.Length; $i++){
$dvProtGroupSpec[$i] = New-Object VMware.Vim.DVPortgroupConfigSpec
$dvProtGroupSpec[$i].name = $portGroupNameList[$i]
$dvProtGroupSpec[$i].numPorts = 128
$dvProtGroupSpec[$i].defaultPortConfig =
New-Object VMware.Vim.VMwareDVSPortSetting
$dvProtGroupSpec[$i].defaultPortConfig.vlan =
New-Object VMware.Vim.VmwareDistributedVirtualSwitchVlanIdSpec
$dvProtGroupSpec[$i].defaultPortConfig.vlan.inherited = $false
$dvProtGroupSpec[$i].defaultPortConfig.vlan.vlanId = 0
$dvProtGroupSpec[$i].type = $portGroupType
}
$dvsView = Get-View -Id $dvsMoRef.ToString()
$dvsView.AddDVPortgroup($dvProtGroupSpec)
return $dvsMoRef
}
|
PowerShellCorpus/PoshCode/Join-Collections 2.0.ps1
|
Join-Collections 2.0.ps1
|
#requires -version 2.0
####################################################################################################
## Version History:
##
## Version 2.0 Added Join-Object and removed dependency on ConvertFrom-Hashtable
## Now works on DataTables!
## Version 1.1 Fixed column uniqueness bug http://poshcode.org/1460
## Version 1.0 First post http://poshcode.org/1459
#.Note
# This script includes a Join-Object function you could use outside
#.Synopsis
# Performs a inner join on two collections of objects based on a common key column.
#.Description
# Takes two sets of objects where there are multiple "rows" and where each set has a shared column where the values match, and generates new objects with all the values from each.
#.Parameter GroupOnColumn
# The name of the property to merge on. Items with the same value in this column will be combined.
#.Parameter FirstCollection
# The first set of data
#.Parameter FirstJoinColumn
# The name of the key id column in the first set
#.Parameter SecondCollection
# The second set of data
#.Parameter SecondJoinColumn
# The name of the matching key id column in the second set
# OPTIONAL. Defaults to the same as FirstJoinColum
#.Example
# Import-CSV data.csv | Pivot-Objects SamAccountName Attribute Value
#
# Imports csv data containing multiple rows per-record such that a pair of columns named "Attribute" and "Value" are actually different in each row, and contain a name and value pair for attributes you want to add to the output objects.
#
#.Example
# $FirstCollection = @"
# FirstName, LastName, MailingAddress, EmployeeID
# John, Doe, 123 First Ave, J8329029
# Susan Q., Public, 3025 South Street, K4367143
#"@.Split("`n") | ConvertFrom-Csv
#
# $SecondCollection = @"
# ID, Week, HrsWorked, PayRate, EmployeeID
# 12276, 12, 40, 55, J8329029
# 12277, 13, 40, 55, J8329029
# 12278, 14, 42, 55, J8329029
# 12279, 12, 35, 40, K4367143
# 12280, 13, 32, 40, K4367143
# 12281, 14, 48, 40, K4367143
#"@.Split("`n") | ConvertFrom-Csv
#
# Join-Collections $FirstCollection EmployeeID $SecondCollection | ft -auto
#
#.Notes
# Author: Joel Bennett
# function Join-Collections {
PARAM(
$FirstCollection
, [string]$FirstJoinColumn
, $SecondCollection
, [string]$SecondJoinColumn=$FirstJoinColumn
)
PROCESS {
$ErrorActionPreference = "Inquire"
foreach($first in $FirstCollection) {
$SecondCollection | Where{ $_."$SecondJoinColumn" -eq $first."$FirstJoinColumn" } | Join-Object $first
}
}
BEGIN {
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(ValueFromPipeline=$true)]
$Second
)
BEGIN {
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
Process {
$Output = $First | Select $p1
foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
}
$Output
}
}
}
#}
|
PowerShellCorpus/PoshCode/LoadModuleConfig.ps1
|
LoadModuleConfig.ps1
|
################################################################################
## Script Name: LoadModuleConfig
## Created On: 01/21/2010
## Author: Thell Fowler
## File: LoadModuleConfig.ps1
## Usage: Called from the NestedModules value from a module manifest.
## Version: 1.0.0.0
## Purpose: Provides automated loading of local configuration data.
##
## Requirements: PowerShell Version 2
## Last Updated: 01/22/2010
## History:
## 1.0.0.0 01/21/2010 - Initial implementation.
##
##
################################################################################
<#
To make use of this script use new-modulemanifest to create a manifest named
the with the same name as the manifest you are loading data for but with an
extension of 'config.psd1'
Enter LoadModuleConfig.ps1 in the NestedModules field.
After creating the manifest open it in your editor and edit the PrivateData
field to include hashes for LocalUser and Settings. After the Settings key
add values as you see fit.
Here is an example, as used in the FuncGuard module.
# Private data to pass to the module specified in ModuleToProcess
PrivateData = @{
"LocalUser" = @{
"Settings"=@{
"ActiveConfiguration" = "PSUnit"
"Configurations"=@{
"PSUnit" =@{
"Name"="PSUnit";
"Path"=$(join-path -Path $Env:Temp -ChildPath "FuncGuard.PSUnit");
"Prefix"="PSUNIT"
}
}
}
}
}
After loading the module a global variable will be available with a name
convention of $($ModuleName)Settings and the values can be accessed using
normal hash retrieval.
$config = $FuncGuardSettings["Configurations"].$($FuncGuardSettings["ActiveConfiguration"])
$Path = $config.Path
#>
#requires -version 2.0
Set-StrictMode -Version 2
$Module = $ExecutionContext.SessionState.Module
if (! $Module) {
throw ( New-Object System.Management.Automation.SessionStateException `
"An active module was not found! LoadModuleConfig must be run from a module manifest's NestedModules field.")
}
$ModuleName = $Module.Name.Replace(".config",$null)
$AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData)
$ModuleConfigPath = join-path -Path $AppData `
-ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$ModuleName.config.xml"
$configurations = $null
if ( Test-Path $ModuleConfigPath -PathType Leaf ) {
$configurations = Import-Clixml -Path $ModuleConfigPath
} else {
# Generate new default config file.
$configurations = $Module.PrivateData.LocalUser.Settings
Export-Clixml -InputObject $configurations -Path $ModuleConfigPath
}
if ($configurations) {
Add-Member -InputObject $configurations -Name ModuleName -MemberType NoteProperty `
-Value $ModuleName
Add-Member -InputObject $configurations -Name Export -MemberType ScriptMethod `
-Value {
$AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData)
$ModuleConfigPath = join-path -Path $AppData `
-ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$($this.ModuleName).config.xml"
Export-Clixml -InputObject $this -Path $ModuleConfigPath
}
Set-Variable -Name "$($ModuleName)Settings" -Value $($configurations) -Scope Global `
-Description "$($ModuleName) module configuration settings."
}
|
PowerShellCorpus/PoshCode/Get # of Web Connections.ps1
|
Get # of Web Connections.ps1
|
function Get-WebServiceConnections()
{
$results = @{}
$perfmon = new-object System.Diagnostics.PerformanceCounter
$perfmon.CategoryName = "Web Service"
$perfmon.CounterName = "Current Connections"
$cat = new-object System.Diagnostics.PerformanceCounterCategory("Web Service")
$instances = $cat.GetInstanceNames()
foreach ($instance in $instances)
{
$perfmon.InstanceName = $instance
$results.Add($instance, $perfmon.NextValue())
}
write-output $results
}
|
PowerShellCorpus/PoshCode/Enable_Configure SNMP_1.ps1
|
Enable_Configure SNMP_1.ps1
|
#Powershell Script To Install SNMP Services (SNMP Service, SNMP WMI Provider)
#Variables :)
$pmanagers = "ADD YOUR MANAGER(s)"
$commstring = "ADD YOUR COMM STRING"
#Import ServerManger Module
Import-Module ServerManager
#Check If SNMP Services Are Already Installed
$check = Get-WindowsFeature | Where-Object {$_.Name -eq "SNMP-Services"}
If ($check.Installed -ne "True") {
#Install/Enable SNMP Services
Add-WindowsFeature SNMP-Services | Out-Null
}
##Verify Windows Servcies Are Enabled
If ($check.Installed -eq "True"){
#Set SNMP Permitted Manager(s) ** WARNING : This will over write current settings **
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v 1 /f /t REG_SZ /d localhost | Out-Null
#Used as counter for incremting permitted managers
$i = 2
Foreach ($manager in $pmanagers){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v $i /f /t REG_SZ /d $manager | Out-Null
$i++
}
#Set SNMP Community String(s)- *Read Only*
Foreach ( $string in $commstring){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\ValidCommunities" /v $string /f /t REG_DWORD /d 4 | Out-Null
}
}
Else {Write-Host "Error: SNMP Services Not Installed"}
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\ValidCommunities" /v $string /f /t REG_DWORD /d 4 | Out-Null
}
}
Else {Write-Host "Error: SNMP Services Not Installed"}
|
PowerShellCorpus/PoshCode/Security group monitor_3.ps1
|
Security group monitor_3.ps1
|
#Get group membership for a list of security
#groups and export to an XML for comparison
#against baseline.
#
$script:WorkingDirectory = split-path $myinvocation.Mycommand.Definition -parent
Function Re-Baseline
{
#First, declare array and hashtable.
$securitygroups = @()
$table = @{}
#Import Security Group list from XML and add to "securitygroups" array.
$securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml")
$securitygroups += $securitygroupsxml.objs.S
#Get membership for each group
foreach($securitygroup in $securitygroups){
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))"
$group = $searcher.findone()
$table += @{"$securitygroup"= $group.properties.member}
}
#Export hashtable to XML. So nice.
$table | export-clixml $script:WorkingDirectory\\baseline.xml
}
#
#First, declare hashtable.
$comparetable = @{}
#Import Security Group list from XML and add to "securitygroups" array.
$securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml")
$securitygroups = $securitygroupsxml.objs.S
#Get membership for each group and create a compare table.
foreach($securitygroup in $securitygroups){
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))"
$group = $searcher.findone()
$comparetable += @{"$securitygroup"= $group.properties.member}
}
#Export hashtable to XML. So nice.
$comparetable | export-clixml "$script:WorkingDirectory\\compare.xml"
#Import baseline XML to hashtable.
$baselinetable = @{}
$baselinetable += import-clixml "$script:WorkingDirectory\\baseline.xml"
#Import baseline XML to hashtable.
$comparetable = @{}
$comparetable += import-clixml "$script:WorkingDirectory\\compare.xml"
#Compare respective Keys and Values for $comparetable against
#$baselinetable and get differences.
$passtoemailsubuser = @()
$passtoemailbody = @()
foreach($securitygroup in $securitygroups) {
If($comparetable."$securitygroup" -eq $NULL)
{
If($baselinetable."$securitygroup" -eq $NULL)
{
(get-date).tostring() + " - Security Group $securitygroup is empty in the compare and the baseline" >> $script:WorkingDirectory\\log.txt
}
Else
{
foreach($entry in $baselinetable."$securitygroup")
{$passtoemailbody += "`r" + $entry + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r"}
$passtoemailbody += "`r" + $securitygroup + " " + "`r`r" + "in AD contains no more objects" + "`r`r"
(get-date).tostring() + " - $securitygroup in AD contains no more objects" >> $script:WorkingDirectory\\log.txt
}
}
Else
{
$baseline = @($baselinetable."$securitygroup")
$compare = @($comparetable."$securitygroup")
$results = Compare-Object $baseline $compare
foreach($result in $results){
if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "=>")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS ADDED TO***: " + "`r`r" + $securitygroup + "`r`r"
$user = $result.inputobject
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))"
$user = $searcher.FindOne()
$passtoemailsubuser += $user.properties.samaccountname
$mod = $true
}
if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "<=")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r"
$user = $result.inputobject
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))"
$user = $searcher.FindOne()
$passtoemailsubuser += $user.properties.samaccountname
$mod = $true
}}
}
}
if ($mod -eq $true) {
$from = New-Object System.Net.Mail.MailAddress "from@address.com"
$to = New-Object System.Net.Mail.MailAddress "to@address.com"
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = "The following accounts were involved in a security group modification: $passtoemailsubuser"
$message.Body = "Note the following security group modification information: `r`r $passtoemailbody"
$server = "SMTPSERVERNAME"
$client = new-object system.net.mail.smtpclient $server
$client.port = 125
$client.Send($message)
foreach($entry in $passtoemailbody)
{(get-date).tostring() + " - " + $Entry >> $script:WorkingDirectory\\Log.txt}
(get-date).tostring() + " - Group Membership compare has been baselined" >> $script:WorkingDirectory\\log.txt
re-baseline
}
else {
$from = New-Object System.Net.Mail.MailAddress "from@address.com"
$to = New-Object System.Net.Mail.MailAddress "to@address.com"
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = "No modifications to the audited security groups have been made."
$message.Body = "No modifications to the audited security groups have been made."
$server = "SMTPSERVERNAME"
$client = new-object system.net.mail.smtpclient $server
$client.port = 125
$client.Send($message)
"No Changes have been made"
}
|
PowerShellCorpus/PoshCode/ErrorLogstoHTML.ps1
|
ErrorLogstoHTML.ps1
|
$a="<style>"
$a=$a+"BODY{background-color :#FFFFF}"
$a=$a+"TABLE{Border-width:thin;border-style: solid;border-color:Black;border-collapse: collapse;}"
$a=$a+"TH{border-width: 0px;padding: 0px;border-style: solid;border-color: black;background-color: ThreeDShadow}"
$a=$a+"TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: Transparent}"
$a=$a+"</style>"
$log = Get-EventLog -LogName "Security" -Newest 20
$log = $log | ConvertTo-Html -Property EventID,Category,EntryType,UserName,TimeGenerated,Message -head $a -body "<H2>Restricted Folder Audit Log</H2>"
$log | Out-File C:\\PowerShellLog.html -Force
|
PowerShellCorpus/PoshCode/Find-GeoCode_1.ps1
|
Find-GeoCode_1.ps1
|
$mappoint = New-WebServiceProxy http://staging.mappoint.net/standard-30/mappoint.wsdl -Namespace MapPoint
$FindService = new-object MapPoint.FindServiceSoap
# You need an account, sign up here: https://mappoint-css.live.com/mwssignup
$FindService.Credentials = Get-Credential
function Find-ReverseGeoCode( [double]$Latitude, [double]$longitude, [switch]$force )
{
$Coords = new-object MapPoint.LatLong
$Coords.Latitude = $Latitude
$Coords.Longitude = $longitude
$Locations = $FindService.GetLocationInfo( $Coords, "MapPoint.NA", $null)
if($force) {
return $Locations
} elseif($Locations[0].Address) {
return $Locations[0].Address # .FormattedAddress + " - " + $Locations[0].Address.CountryRegion
} else {
return $Locations | ?{ $_.Entity.TypeName -eq "PopulatedPlace" } # | %{ $_.Entity.DisplayName }
}
}
function Find-GeoCode( $address, $country = "US" )
{
$spec = new-object MapPoint.FindAddressSpecification
$spec.DataSourceName = "MapPoint.NA"
$spec.InputAddress = $FindService.ParseAddress( $address, $country )
$Found = $FindService.FindAddress( $spec )
if($Found.NumberFound) {
$found.Results | Select -expand FoundLocation | Select -Expand LatLong
}
# if($Found.NumberFound -gt 1) {
# $found.Results| Select -expand FoundLocation | Select -Expand Address
# }
}
## This is how non-geography geeks think of them:
Set-Alias Find-Address Find-ReverseGeoCode
Set-Alias Find-Coordinates Find-GeoCode
|
PowerShellCorpus/PoshCode/Get KB-articles of SP_1.ps1
|
Get KB-articles of SP_1.ps1
|
function Get-Sp1Articles()
{
$web = New-Object System.Net.WebClient
# Microsoft XLS-Datei über google herunterladen, damit kommt die XLS-Datei als in HTML konvertierte Datei
$html = $web.DownloadString(‘http://webcache.googleusercontent.com/search?q=cache:trZowCK8jvcJ:download.microsoft.com/download/8/B/3/8B37425B-AB6E-4C9C-9361-ECC15771BC5C/Hotfixes%2520and%2520Security%2520Updates%2520included%2520in%2520Windows%25207%2520and%2520Windows%2520Server%25202008%2520R2%2520Service%2520Pack%25201.xls’)
# zuerst den Google Header und das unnötige Blabla wegbekommen
$html = $html.Substring($html.IndexOf("KBTitle"))
# jetzt das nächste <tr> finden
$html = $html.Substring($html.IndexOf("<tr"))
# einzelne Zeile mit KB-Eintrag erkennen
$regex = ‘<tr([\\s\\S]*?)</tr>’
# HTML in Objektauflistung überführen
($html |Select-String -Pattern $regex -AllMatches).matches |foreach {
# durch überführen in ein XML-Objekt läßt sich die Zeile leichter verarbeiten
[xml]$tmp = $_
# neues Objekt erzeugen, dem die 4 wichtigen Eigenschaften zugeordnet werden, wenn eine KB-Nummer eingetragen ist
if ($tmp.tr.td[0].font.’#text’ -gt 0)
{
$obj = New-Object psobject
$obj |Add-Member -MemberType NoteProperty -Name KBArticle -Value $tmp.tr.td[0].font.’#text’
$obj |Add-Member -MemberType NoteProperty -Name Classification -Value $tmp.tr.td[1].font.’#text’
$obj |Add-Member -MemberType NoteProperty -Name KBTitle -Value $tmp.tr.td[2].font.’#text’
$obj |Add-Member -MemberType NoteProperty -Name Link -Value $tmp.tr.td[3].a.href
$obj
}
}
}
|
PowerShellCorpus/PoshCode/Get-ObservedIPRange.ps1
|
Get-ObservedIPRange.ps1
|
function Get-ObservedIPRange {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Physical NIC from Get-VMHostNetworkAdapter")]
[VMware.VimAutomation.ViCore.Impl.V1.Host.Networking.Nic.PhysicalNicImpl]
$Nic
)
process {
$hostView = Get-VMHost -Id $Nic.VMHostId | Get-View -Property ConfigManager
$ns = Get-View $hostView.ConfigManager.NetworkSystem
$hints = $ns.QueryNetworkHint($Nic.Name)
foreach ($hint in $hints) {
foreach ($subnet in $hint.subnet) {
$observed = New-Object -TypeName PSObject
$observed | Add-Member -MemberType NoteProperty -Name Device -Value $Nic.Name
$observed | Add-Member -MemberType NoteProperty -Name VMHostId -Value $Nic.VMHostId
$observed | Add-Member -MemberType NoteProperty -Name IPSubnet -Value $subnet.IPSubnet
$observed | Add-Member -MemberType NoteProperty -Name VlanId -Value $subnet.VlanId
Write-Output $observed
}
}
}
}
# Example use:
# Get-VMHost esx01a.vmworld.com | Get-VMHostNetworkAdapter | Where { $_.Name -eq "vmnic1" } | Get-ObservedIPRange
# Example output:
#Device VMHostId IPSubnet VlanId
#------ -------- -------- ------
#vmnic1 HostSystem-host-102 10.91.245.128-10.91... 2907
#vmnic1 HostSystem-host-102 10.91.244.133-10.91... 2905
#vmnic1 HostSystem-host-102 10.91.243.253-10.91... 2903
#vmnic1 HostSystem-host-102 10.91.246.11-10.91.... 2908
#vmnic1 HostSystem-host-102 10.91.246.129-10.91... 2909
|
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail.ps1
|
Send-HTMLFormattedEmail.ps1
|
#-------------------------------------------------
# Send-HTMLFormattedEmail
#-------------------------------------------------
# Usage: Used to display help information.
# **Parameters are not for interactive execution.**
#-------------------------------------------------
function Send-HTMLFormattedEmail{
param ( [string] $To,
[string] $ToDisName,
[string] $BCC,
[string] $From,
[string] $FromDisName,
[string] $Subject,
[string] $Content,
[string] $Relay,
[string] $XSLPath)
try {
# Load XSL Argument List
$XSLArg = New-Object System.Xml.Xsl.XsltArgumentList
$XSLArg.Clear()
$XSLArg.AddParam("To", $Null, $ToDisName)
$XSLArg.AddParam("Content", $Null, $Content)
# Load Documents
$BaseXMLDoc = New-Object System.Xml.XmlDocument
$BaseXMLDoc.LoadXml("<root/>")
$XSLTrans = New-Object System.Xml.Xsl.XslCompiledTransform
$XSLTrans.Load($XSLPath)
#Perform XSL Transform
$FinalXMLDoc = New-Object System.Xml.XmlDocument
$MemStream = New-Object System.IO.MemoryStream
$XMLWriter = [System.Xml.XmlWriter]::Create($MemStream)
$XSLTrans.Transform($BaseXMLDoc, $XSLArg, $XMLWriter)
$XMLWriter.Flush()
$MemStream.Position = 0
# Load the results
$FinalXMLDoc.Load($MemStream)
$Body = $FinalXMLDoc.Get_OuterXML()
# Create from, To, BCC and the message strucures
$MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName
$MessTo = New-Object System.Net.Mail.Mailaddress $To
$MessBCC = New-Object System.Net.Mail.Mailaddress $BCC
$Message = New-Object System.Net.Mail.MailMessage $MessFrom, $MessTo
# Populate message
$Message.Subject = $Subject
$Message.Body = $Body
$Message.IsBodyHTML = $True
# Add BCC
$Message.BCC.Add($MessBCC)
# Create SMTP Client
$Client = New-Object System.Net.Mail.SmtpClient $Relay
# Send The Message
$Client.Send($Message)
}
catch {
return $Error[0]
}
}
### XSLT Template Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output media-type="xml" omit-xml-declaration="yes" />
<xsl:param name="To"/>
<xsl:param name="Content"/>
<xsl:template match="/">
<html>
<head>
<title>My First Formatted Email</title>
</head>
<body>
<div width="400px">
<p>Dear <xsl:value-of select="$To" />,</p>
<p></p>
<p><xsl:value-of select="$Content" /></p>
<p></p>
<p><strong>Please do not respond to this email!</strong><br />
An automated system sent this email, if any point you have any questions or concerns please open a help desk ticket.</p>
<p></p>
<Address>
Many thanks from your:<br />
Really Cool IT Team<br />
</Address>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
|
PowerShellCorpus/PoshCode/usr mailbox in exch 07.ps1
|
usr mailbox in exch 07.ps1
|
#Generamos los usuarios por buzon y comprimimos el resultado
#Autor: Pedro Genil
#Fecha: 2012/11/21
#Version: 1.0
# Aþadimos modulo
If ((Get-PSSnapin | where {$_.Name -match "Exchange.Management"}) -eq $null)
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
}
# Creamos el alias para el 7zip
if (-not (test-path "$env:ProgramFiles\\7-Zip\\7z.exe")) {throw "$env:ProgramFiles\\7-Zip\\7z.exe needed"}
set-alias sz "$env:ProgramFiles\\7-Zip\\7z.exe"
#Directorios
$filePath = 'F:\\Scripts\\users_Acount\\'
$fecha = get-date
$fecha= $fecha.toString("yyyyMMdd")
$filedate = $fecha
$info = Get-Mailbox -resultsize unlimited -ignoredefaultscope |select database,displayname,samaccountname,PrimarySmtpAddress,EmailAddresses -expandproperty EmailAddresses | out-file F:\\Scripts\\users_Acount\\$filedate.txt
$files = Get-ChildItem -Recurse -Path $filePath | Where-Object { $_.name -eq "$fecha.txt" }
#Cogemos el fichero , y creamos el zip
sz a "F:\\Scripts\\users_Acount\\$fecha.zip" "$filepath\\$files"
#Borramos el txt
remove-item "F:\\Scripts\\users_Acount\\$filedate.txt"
#foreach ($file in $files)
#{
# $name = $file.name
# $directory = $file.DirectoryName
# sz a "F:\\Scripts\\users_Acount\\$zipfile.zip" "$directory\\$name"
#}
|
PowerShellCorpus/PoshCode/BinaryClock V_1.0.ps1
|
BinaryClock V_1.0.ps1
|
Function Start-BinaryClock {
<#
.SYNOPSIS
This is a binary clock that lists the time in hours, minutes and seconds
.DESCRIPTION
This is a binary clock that lists the time in hours, minutes and seconds.
Key Input Tips:
r: Toggles the resize mode of the clock so you can adjust the size.
d: Toggles the date to hide/show
o: Toggles whether the clock remains on top of windows or not.
+: Increases the opacity of the clock so it is less transparent.
-: Decreases the opacity of the clock so it appears more transparent.
Right-Click to close.
Use left mouse button to drag clock.
.PARAMETER OnColor
Define the color used for the active time (1).
.PARAMETER OffColor
Define the color used for the inactive time (0).
.PARAMETER RandomColor
Default parameter if manual colors are not used. Picks a random color for On and Off colors.
.NOTES
Name: BinaryClock.ps1
Author: Boe Prox
DateCreated: 07/05/2011
Version 2.0
.EXAMPLE
Start-BinaryClock
Description
-----------
Starts the binary clock using randomly generated colors
.EXAMPLE
Start-BinaryClock -OnColor Red -OffColor Gold -DateColor Black
Description
-----------
Starts the binary clock using using specified colors.
#>
[cmdletbinding(
DefaultParameterSetName = 'RandomColor'
)]
Param (
[parameter(Mandatory = 'True',ParameterSetName = 'SetColor')]
[String] $OnColor,
[parameter(Mandatory = 'True',ParameterSetName = 'SetColor')]
[String] $OffColor,
[parameter(ParameterSetName = 'RandomColor')]
[Switch]$RandomColor,
[parameter(Mandatory = 'True',ParameterSetName = 'SetColor')]
[String] $DateColor
)
If ($PSCmdlet.ParameterSetName -eq 'RandomColor') {
[switch]$RandomColor = $True
}
$Global:rs = [RunspaceFactory]::CreateRunspace()
$rs.ApartmentState = “STA”
$rs.ThreadOptions = “ReuseThread”
$rs.Open()
$psCmd = {Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase}.GetPowerShell()
$rs.SessionStateProxy.SetVariable('OnColor',$OnColor)
$rs.SessionStateProxy.SetVariable('OffColor',$OffColor)
$rs.SessionStateProxy.SetVariable('RandomColor',$RandomColor)
$rs.SessionStateProxy.SetVariable('DateColor',$DateColor)
$psCmd.Runspace = $rs
$psCmd.Invoke()
$psCmd.Commands.Clear()
$psCmd.AddScript({
#Load Required Assemblies
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
##Colors
If ($RandomColor) {
#On Color
$OnColor = "#{0:X}" -f (Get-Random -min 1 -max 16777215)
Try {
[system.windows.media.brush]$OnColor | Out-Null
}
Catch {
$OnColor = "White"
}
#Off Color
$OffColor = "#{0:X}" -f (Get-Random -min 1 -max 16777215)
Try {
[system.windows.media.brush]$OffColor | Out-Null
}
Catch {
$OffColor = "Black"
}
#DateColor Color
$DateColor = "#{0:X}" -f (Get-Random -min 1 -max 16777215)
Try {
[system.windows.media.brush]$DateColor | Out-Null
}
Catch {
$DateColor = "Black"
}
}
[xml]$xaml = @"
<Window
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
x:Name='Window' WindowStyle = 'None' WindowStartupLocation = 'CenterScreen' Width = '170' Height = '101' ShowInTaskbar = 'True'
ResizeMode = 'NoResize' Title = 'Clock' AllowsTransparency = 'True' Background = 'Transparent' Opacity = '1' Topmost = 'True'>
<Grid x:Name = 'Grid' HorizontalAlignment="Stretch" ShowGridLines='false' Background = 'Transparent'>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*" x:Name = 'DayColumn'/>
<ColumnDefinition Width="*" x:Name = 'MonthColumn'/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition x:Name = 'timerow' Height = '0'/>
</Grid.RowDefinitions>
<Ellipse Grid.Row = '0' Grid.Column = '0' Fill = 'Transparent'/>
<Ellipse Grid.Row = '2' Grid.Column = '0' Fill = 'Transparent' />
<Ellipse x:Name = 'HourA0' Grid.Row = '6' Grid.Column = '0' Fill = 'Transparent' />
<Ellipse x:Name = 'HourA1' Grid.Row = '4' Grid.Column = '0' Fill = 'Transparent' />
<Ellipse x:Name = 'HourB0' Grid.Row = '6' Grid.Column = '2' Fill = 'Transparent'/>
<Ellipse x:Name = 'HourB1' Grid.Row = '4' Grid.Column = '2' Fill = 'Transparent' />
<Ellipse x:Name = 'HourB2' Grid.Row = '2' Grid.Column = '2' Fill = 'Transparent' />
<Ellipse x:Name = 'HourB3' Grid.Row = '0' Grid.Column = '2' Fill = 'Transparent' />
<Ellipse Grid.Row = '0' Grid.Column = '4' Fill = 'Transparent'/>
<Ellipse x:Name = 'MinuteA0' Grid.Row = '6' Grid.Column = '4' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteA1' Grid.Row = '4' Grid.Column = '4' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteA2' Grid.Row = '2' Grid.Column = '4' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteB0' Grid.Row = '6' Grid.Column = '6' Fill = 'Transparent'/>
<Ellipse x:Name = 'MinuteB1' Grid.Row = '4' Grid.Column = '6' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteB2' Grid.Row = '2' Grid.Column = '6' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteB3' Grid.Row = '0' Grid.Column = '6' Fill = 'Transparent' />
<Ellipse Grid.Row = '0' Grid.Column = '8' Fill = 'Transparent'/>
<Ellipse x:Name = 'SecondA0' Grid.Row = '6' Grid.Column = '8' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondA1' Grid.Row = '4' Grid.Column = '8' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondA2' Grid.Row = '2' Grid.Column = '8' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondB0' Grid.Row = '6' Grid.Column = '10' Fill = 'Transparent'/>
<Ellipse x:Name = 'SecondB1' Grid.Row = '4' Grid.Column = '10' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondB2' Grid.Row = '2' Grid.Column = '10' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondB3' Grid.Row = '0' Grid.Column = '10' Fill = 'Transparent' />
<Viewbox VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch' Grid.Column = '12' Grid.RowSpan = '7'
StretchDirection = 'Both' Stretch = 'Fill'>
<TextBlock x:Name = 'DayLabel' VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch'
FontWeight = 'Bold'>
<TextBlock.LayoutTransform>
<RotateTransform Angle="90" />
</TextBlock.LayoutTransform>
</TextBlock>
</Viewbox>
<Viewbox VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch' Grid.Column = '13' Grid.RowSpan = '7'
StretchDirection = 'Both' Stretch = 'Fill'>
<TextBlock x:Name = 'MonthLabel' VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch'
FontWeight = 'Bold'>
<TextBlock.LayoutTransform>
<RotateTransform Angle="90" />
</TextBlock.LayoutTransform>
</TextBlock>
</Viewbox>
</Grid>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Global:Window=[Windows.Markup.XamlReader]::Load( $reader )
$Global:DayLabel = $Global:window.FindName("DayLabel")
$Global:MonthLabel = $Global:window.FindName("MonthLabel")
$Global:DayColumn = $Global:window.FindName("DayColumn")
$Global:MonthColumn = $Global:window.FindName("MonthColumn")
$Global:TimeRow = $Global:window.FindName("TimeRow")
$Global:Grid = $Global:window.FindName("Grid")
##Events
#Key Events
$Global:Window.Add_KeyDown({
Switch ($_.Key) {
{'Add','OemPlus' -contains $_} {
If ($Window.Opacity -lt 1) {
$Window.Opacity = $Window.Opacity + .1
$Window.UpdateLayout()
}
}
{'Subtract','OemMinus' -contains $_} {
If ($Window.Opacity -gt .2) {
$Window.Opacity = $Window.Opacity - .1
$Window.UpdateLayout()
}
}
"r" {
If ($Window.ResizeMode -eq 'NoResize') {
$Window.ResizeMode = 'CanResizeWithGrip'
}
Else {
$Window.ResizeMode = 'NoResize'
}
}
"d" {
Switch ($MonthLabel.visibility) {
'Collapsed' {$MonthLabel.visibility = 'Visible';$DayLabel.Visibility = 'Visible'}
'Visible' {$MonthLabel.visibility = 'Collapsed ';$DayLabel.Visibility = 'Collapsed '}
}
}
"o" {
If ($Window.TopMost) {
$Window.TopMost = $False
}
Else {
$Window.TopMost = $True
}
}
}
})
$Window.Add_MouseRightButtonUp({
$This.close()
})
$Window.Add_MouseLeftButtonDown({
$This.DragMove()
})
$update = {
$DayLabel.Text = "$(((Get-Date).ToLongDateString() -split ',')[0] -split '')"
$DayLabel.Foreground = $DateColor
$MonthLabel.Text = Get-Date -u "%B %d %G"
$MonthLabel.Foreground = $DateColor
$hourA,$hourB = [string](Get-Date -f HH) -split "" | Where {$_}
$minuteA,$minuteB = [string](Get-Date -f mm) -split "" | Where {$_}
$secondA,$secondB = [string](Get-Date -f ss) -split "" | Where {$_}
$hourAdock = $grid.children | Where {$_.Name -like "hourA*"}
$minuteAdock = $grid.children | Where {$_.Name -like "minuteA*"}
$secondAdock = $grid.children | Where {$_.Name -like "secondA*"}
$hourBdock = $grid.children | Where {$_.Name -like "hourB*"}
$minuteBdock = $grid.children | Where {$_.Name -like "minuteB*"}
$secondBdock = $grid.children | Where {$_.Name -like "secondB*"}
#hourA
[array]$splittime = ([convert]::ToString($houra,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $hourAdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#hourB
[array]$splittime = ([convert]::ToString($hourb,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $hourBdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#minuteA
[array]$splittime = ([convert]::ToString($minutea,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $minuteAdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#minuteB
[array]$splittime = ([convert]::ToString($minuteb,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $minuteBdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#secondA
[array]$splittime = ([convert]::ToString($seconda,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $secondAdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#secondB
[array]$splittime = ([convert]::ToString($secondb,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $secondBdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
}
$Global:Window.Add_KeyDown({
If ($_.Key -eq "F5") {
&$update
}
})
#Timer Event
$Window.Add_SourceInitialized({
#Create Timer object
Write-Verbose "Creating timer object"
$Global:timer = new-object System.Windows.Threading.DispatcherTimer
Write-Verbose "Adding interval to timer object"
$timer.Interval = [TimeSpan]"0:0:.10"
#Add event per tick
Write-Verbose "Adding Tick Event to timer object"
$timer.Add_Tick({
&$update
Write-Verbose "Updating Window"
})
#Start timer
Write-Verbose "Starting Timer"
$timer.Start()
If (-NOT $timer.IsEnabled) {
$Window.Close()
}
})
&$update
$window.Showdialog() | Out-Null
}).BeginInvoke() | out-null
}
|
PowerShellCorpus/PoshCode/8796ba7c-730c-45aa-ac56-3b561a1149d2.ps1
|
8796ba7c-730c-45aa-ac56-3b561a1149d2.ps1
|
# Copyright (c) 2011 Code Owls LLC, All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# http://www.opensource.org/licenses/mit-license.php
#
# PowerShell module for iSCSI management
#
# author:
# jim christopher <jimchristopher@gmail.com>
#
# notes:
#
#Target Mappings:
# <Target Lun> is the LUN value the target uses to expose the LUN.
# It must be in the form 0x0123456789abcdef
# <OS Bus> is the bus number the OS should use to surface the LUN
# <OS Target> is the target number the OS should use to surface the LUN
# <OS LUN> is the LUN number the OS should use to surface the LUN
#
#CHAP secrets, CHAP passwords and IPSEC preshared keys can be specified as
#a text string or as a sequence of hexadecimal values. The value specified on
#the command line is always considered a string unless the first two characters
#0x in which case it is considered a hexadecimal value.
#
#For example 0x12345678 specifies a 4 byte secret
#
#All numerical values are assumed decimal unless preceeded by 0x. If
#preceeded by 0x then value is assumed to be hex
#
#iscsicli can also be run in command line mode where iscsicli commands
#can be entered directly from the console. To enter command line
#mode, just run iscsicli without any parameters
###########################################################
## flags and enumerations
#Payload Id Type:
# ID_IPV4_ADDR is 1 - Id format is 1.2.3.4
# ID_FQDN is 2 - Id format is ComputerName
# ID_IPV6_ADDR is 5 - Id form is IPv6 Address
#
$payloadIPV4 = 1;
$payloadFQDN = 2;
$payloadIPV6 = 5;
#Security Flags:
# TunnelMode is 0x00000040
# TransportMode is 0x00000020
# PFS Enabled is 0x00000010
# Aggressive Mode is 0x00000008
# Main mode is 0x00000004
# IPSEC/IKE Enabled is 0x00000002
# Valid Flags is 0x00000001
#
$securityTunnelMode = 0x40;
$securityTransportMode = 0x20;
$securityPFSEnable = 0x10;
$securityAggressiveMode = 0x08;
$securityMainMode = 0x04;
$securityIPSECIKEEnabled = 0x02;
$securityValidFlags = 0x01;
#Login Flags:
# ISCSI_LOGIN_FLAG_REQUIRE_IPSEC 0x00000001
# IPsec is required for the operation
#
# ISCSI_LOGIN_FLAG_MULTIPATH_ENABLED 0x00000002
# Multipathing is enabled for the target on this initiator
#
$loginRequireIPSEC = 0x01;
$loginMultipathEnabled = 0x02;
#AuthType:
# ISCSI_NO_AUTH_TYPE = 0,
# No iSCSI in-band authentication is used
#
# ISCSI_CHAP_AUTH_TYPE = 1,
# One way CHAP (Target authenticates initiator is used)
#
# ISCSI_MUTUAL_CHAP_AUTH_TYPE = 2
# Mutual CHAP (Target and Initiator authenticate each other is used)
#
$authTypeNone = 0;
$authTypeChap = 1;
$authTypeMutualChap = 2;
#Target Flags:
# ISCSI_TARGET_FLAG_HIDE_STATIC_TARGET 0x00000002
# If this flag is set then the target will never be reported unless it
# is also discovered dynamically.
#
# ISCSI_TARGET_FLAG_MERGE_TARGET_INFORMATION 0x00000004
# If this flag is set then the target information passed will be
# merged with any target information already statically configured for
# the target
#
$targetHideStaticTarget = 0x02;
$targetMergeTargetInfo = 0x04;
###########################################################
## cmdlets
#iscsicli AddTarget <TargetName> <TargetAlias> <TargetPortalAddress>
# <TargetPortalSocket> <Target flags>
# <Persist> <Login Flags> <Header Digest> <Data Digest>
# <Max Connections> <DefaultTime2Wait>
# <DefaultTime2Retain> <Username> <Password> <AuthType>
# <Mapping Count> <Target Lun> <OS Bus> <Os Target>
# <OS Lun> ...
#
#iscsicli QAddTarget <TargetName> <TargetPortalAddress>
#
function Add-Target
{
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[Alias("Name")]
[string]
# the name of the target
$targetName,
[Parameter(Mandatory=$true)]
[Alias("Address")]
[string]
# the IP or DNS address of the target portal
$targetPortalAddress
)
process
{
& iscsicli qaddtarget $targetName, $targetPortalAddress;
}
}
#iscsicli RemoveTarget <TargetName>
#
#RemovePersistentTarget <Initiator Name> <TargetName>
# <Initiator Port Number>
# <Target Portal Address>
# <Target Portal Socket>
#
function Remove-Target
{
<#
This command will remove a target from the list of persisted targets.
Boot Configuration Known Issues (Windows Server 2003 Boot Initiator)
The Microsoft iSCSI Software Initiator boot version GUI does not allow you to view which adapter is set to boot. In order
to determine which adapter the system is set to boot with, you can use the following command:
From a command prompt type “iscsibcg /showibf” to find the MAC address of the boot adapter
Then run the command “ipconfig /all”
Compare the MAC address of the adapter to those listed with ipconfig /all
MPIO Failover in an iSCSI boot configuration using the Microsoft iSCSI Software Initiator
In Fail Over Only, no load balancing is performed. The primary path functions as the active path and all other paths are
standby paths. The active path is used for sending all I/O. If the active path fails, one of the standby paths becomes
the active path. When the formerly active path is reconnected, it becomes a standby path and a "failback" does not
occur. This behavior is due to Media Sensing is disabled by default in the boot version of the Microsoft iSCSI Software
Initiator and is by design. However, the registry key can be changed to enable fail back. For more information, please
see
For more information:
239924 How to disable the Media Sensing feature for TCP/IP in Windows
http://support.microsoft.com/default.aspx?scid=kb;EN-US;239924
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='high')]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Name")]
[string]
# the name of the target to remove
$targetName,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias("Address")]
[string]
# the IP or DNS address of the target portal
$targetPortalAddress,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias('Port')]
[int]
#the TCP port number of the target portal. Typically this is 3260, which is the well-known port number
defined for use by iSCSI.
$TargetPortalSocket = 3260,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias( "InitiatorInstanceName" )]
[string]
#the name of the initiator via which the SendTargets operation is performed. If not specified then the
initiator used is selected by the iSCSI initiator service.
$InitiatorName,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string]
#is the physical port number on the initiator via which the SendTargets operation is performed. If not
specified then the kernel mode initiator driver chooses the initiator port used.
$InitiatorPort = '*',
[Parameter()]
[switch]
# specify to remove a persistent connection
$persist,
[Parameter()]
[switch]
# specify to bypass standard PowerShell confirmation procedures
$force
)
process
{
Write-Verbose "remove-target ...";
Write-Verbose " TargetName: $targetName";
Write-Verbose " TargetPortalAddress: $targetPortalAddress";
Write-Verbose " TargetPortalSocket: $targetPortalSocket";
Write-Verbose " InitiatorInstanceName: $InitiatorName";
Write-Verbose " InitiatorPort: $initiatorPort";
Write-Verbose " Persist: $persist";
Write-Verbose " Force: $force";
if( -not ( $force -or $pscmdlet.ShouldProcess( $targetName, 'Remove iSCSI target' ) ) )
{
return;
}
if( $persist -and $InitiatorName )
{
$iscsi = "iscsicli removepersistenttarget $InitiatorName $targetName $InitiatorPort
$targetPortalAddress $TargetPortalSocket"
Write-Verbose $iscsi;
invoke-expression $iscsi
}
else
{
$iscsi = "iscsicli removetarget $targetName";
Write-Verbose $iscsi;
invoke-expression $iscsi
}
}
}
#iscsicli AddTargetPortal <TargetPortalAddress> <TargetPortalSocket>
# [HBA Name] [Port Number]
# <Security Flags>
# <Login Flags> <Header Digest> <Data Digest>
# <Max Connections> <DefaultTime2Wait>
# <DefaultTime2Retain> <Username> <Password> <AuthType>
#
#iscsicli QAddTargetPortal <TargetPortalAddress>
# [CHAP Username] [CHAP Password]
#
function Add-TargetPortal
{
<#
This command will add a target portal to the list of persisted target portals. The iSCSI initiator service will perform a
SendTargets operation to each target portal in the list whenever the service starts and whenever a full refresh of the
target list is requested.
#>
#[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[Alias("Address")]
[string]
# the IP or DNS address of the target portal.
$targetPortalAddress,
[Parameter()]
[string]
#Username is the string that should be used as the CHAP username when logging into the target. By
specifying * for this parameter, the iSCSI initiator service will use the initiator node name as the CHAP username.
$username,
[Parameter()]
[string]
#Password is the string that should be used as the target’s CHAP secret when logging into the target. The
initiator will use this secret to compute a hash value based on the challenge sent by the target.
$password
)
process
{
if( $username )
{
& iscsicli qaddtargetportal $targetPortalAddress $username $password;
}
else
{
& iscsicli qaddtargetportal $targetPortalAddress;
}
}
}
#iscsicli RemoveTargetPortal <TargetPortalAddress> <TargetPortalSocket> [HBA Name] [Port Number]
#
function Remove-TargetPortal
{
<#
This command will remove a target portal from the list of persisted target portals. The iSCSI initiator service will
perform a SendTargets operation to each target portal in the list whenever the service starts and whenever a full refresh
of the target list is requested. Note that the command does not purge the targets discovered via this target portal from
the list of targets maintained by the service.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[Alias('Name')]
[string]
# the IP or DNS address of the target portal.
$targetPortalAddress,
[Parameter()]
[Alias('Port')]
[int]
#the TCP port number of the target portal. Typically this is 3260, which is the well-known port number
defined for use by iSCSI.
$TargetPortalSocket = 3260,
[Parameter()]
[string]
#the name of the initiator via which the SendTargets operation is performed. If not specified then the
initiator used is selected by the iSCSI initiator service.
$InitiatorName = '',
[Parameter()]
[string]
#is the physical port number on the initiator via which the SendTargets operation is performed. If not
specified then the kernel mode initiator driver chooses the initiator port used.
$InitiatorPort = ''
)
process
{
& iscsicli removetargetportal $targetPortalAddress $TargetPortalSocket $InitiatorName $InitiatorPort
}
}
#iscsicli RefreshTargetPortal <TargetPortalAddress> <TargetPortalSocket> [HBA Name] [Port Number]
#
function Update-TargetPortal
{
<#
This command will perform a SendTargets operation to the target portal and include the discovered targets into the list of
targets maintained by the service. It does not add the target portal to the persistent list.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[Alias("Address")]
[string]
# the IP or DNS address of the target portal.
$targetPortalAddress,
[Parameter()]
[Alias("Port")]
[int]
#the TCP port number of the target portal. Typically this is 3260, which is the well-known port number
defined for use by iSCSI.
$TargetPortalSocket = 3260,
[Parameter()]
[string]
#the name of the initiator via which the SendTargets operation is performed. If not specified then the
initiator used is selected by the iSCSI initiator service.
$InitiatorName,
[Parameter()]
[int]
#is the physical port number on the initiator via which the SendTargets operation is performed. If not
specified then the kernel mode initiator driver chooses the initiator port used.
$InitiatorPort
)
process
{
& iscsicli refreshtargetportal $targetPortalAddress $TargetPortalSocket $InitiatorName $InitiatorPort
}
}
#iscsicli ListTargets [ForceUpdate]
#
#iscsicli ListPersistentTargets
#
function Get-Target
{
<#
This command will display the list of persistent targets configured for all initiators.
#>
[CmdletBinding(DefaultParameterSetName='Local')]
param(
[Parameter( ParameterSetName='Persistent' )]
[switch]
# specify to get persistent targets
$persistent,
[Parameter( ParameterSetName='Local' )]
[switch]
# specify to force refresh of target list during retrieval
$force
)
process
{
if( $persistent )
{
$data = & iscsicli ListPersistentTargets | Out-String;
$data | Write-Verbose;
$data -replace "[`r`n]+","=" -split "==" | where { $_ -match ':\\s+' } | foreach {
$_ | convertFrom-iSCSIOutput
# Write-Verbose "section $_";
# $a = @{};
# $_ -split '=' | Select-String '^\\s+[\\S\\s]+:\\s+' | foreach{
# Write-Verbose "item entry $_";
# $k,$v = $_ -split ':',2
# $a[$k.trim(' ')] = $v.trim(' ');
#
# #todo - massage to match remove-target inputs
# }
# new-object psobject -Property $a;
}
}
else
{
if( $force )
{
$data = & iscsicli ListTargets T
}
else
{
$data = & iscsicli ListTargets
}
$data | Select-String '^\\s+\\S+:\\S+$' | foreach{ $_ -replace '^\\s+','' -replace '\\s+$','' };
}
}
}
#iscsicli ListTargetPortals
#
function Get-TargetPortal
{
[CmdletBinding()]
param()
process
{
$data = & iscsicli ListTargetPortals | Out-String;
$data | Write-Verbose;
$data -replace "[`r`n]+","=" -split "==" | where { $_ -match ':\\s+' } | foreach {
$_ | convertFrom-iSCSIOutput
# Write-Debug "section $_";
# $a = @{};
# $_ -split '=' | Select-String '^\\s+[\\S\\s]+:\\s+' | foreach{
# Write-Debug "item entry $_";
# $k,$v = $_ -split ':',2
# $a[$k.trim(' ')] = $v.trim(' ');
# }
# new-object psobject -Property $a;
}
}
}
#iscsicli TargetInfo <TargetName> [Discovery Mechanism]
#
function Get-TargetInfo
{
<#
This command will return information about the target specified by TargetName. The iSCSI initiator service maintains a
separate set of information about every target organized by each mechanism by which it was discovered. This means that
each instance of a target can have different information such as target portal groups. Discovery Mechanism is an optional
parameter and if not specified then only the list of discovery mechanisms for the target are displayed. If Discovery
Mechanism is specified then information about the target instance discovered by that mechanism is displayed.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]
$targetName,
[Parameter()]
[string]
$discoveryMechanism
)
process
{
}
}
#iscsicli LoginTarget <TargetName> <ReportToPNP>
# <TargetPortalAddress> <TargetPortalSocket>
# <InitiatorInstance> <Port number> <Security Flags>
# <Login Flags> <Header Digest> <Data Digest>
# <Max Connections> <DefaultTime2Wait>
# <DefaultTime2Retain> <Username> <Password> <AuthType> <Key>
# <Mapping Count> <Target Lun> <OS Bus> <Os Target>
# <OS Lun> ...
#
#iscsicli PersistentLoginTarget <TargetName> <ReportToPNP>
# <TargetPortalAddress> <TargetPortalSocket>
# <InitiatorInstance> <Port number> <Security Flags>
# <Login Flags> <Header Digest> <Data Digest>
# <Max Connections> <DefaultTime2Wait>
# <DefaultTime2Retain> <Username> <Password> <AuthType> <Key>
# <Mapping Count> <Target Lun> <OS Bus> <Os Target>
# <OS Lun> ...
#
#iscsicli QLoginTarget <TargetName> [CHAP Username] [CHAP Password]
#
function Connect-Target
{
<#
This command will login to a target
#>
#iscsicli persistentlogintarget $t T * * * * * * * * * * * [* * *] * 0
[CmdletBinding( SupportsShouldProcess=$true )]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[Alias("Name")]
[string]
# the name of the target
$targetName,
[Parameter()]
[string]
# Username is the string that should be used as the CHAP username when logging into the target. By
specifying * for this parameter, the iSCSI initiator service will use the initiator node name as the CHAP username.
$username,
[Parameter()]
[string]
# Password is the string that should be used as the target’s CHAP secret when logging into the target. The
initiator will use this secret to compute a hash value based on the challenge sent by the target.
$password,
[Parameter()]
[switch]
# specify to persist the login information upon reboot
$persist
)
process
{
if( $username )
{
$data = & iscsicli qlogintarget $targetName $username $password
Write-Verbose "Raw iSCSIcli output: $data";
}
else
{
$data = & iscsicli qlogintarget $targetName
Write-Verbose "Raw iSCSIcli output: $data";
$username = '*';
$password = '*';
}
Write-Verbose "Raw iSCSIcli output: $data";
if( $data -match 'already.+logged' )
{
$s = get-session | where { $_.targetname -eq $targetName };
New-Object psobject -Property @{ SessionId=$s.SessionId; ConnectionId=$s.Connection.ConnectionID
};
}
else
{
# Session Id is 0xfffffa800f7900a8-0x4000013700000015
# Connection Id is 0xfffffa800f7900a8-0x23
( $data | Out-String ) -replace '0x','' -replace "[`r`n]+",'=' | convertFrom-iSCSIOutput -field '
is ';
}
if( $persist )
{
& iscsicli persistentlogintarget $targetName T * * * * * * * * * * * $username $password * * 0 |
Out-Null
}
}
}
#iscsicli LogoutTarget <SessionId>
#
function Disconnect-Session
{
<#
This command will attempt to logout of a target which was logged in via the session specified by SessionId. The iSCSI
initiator service will not logout of a session if any devices exposed by it are currently in use. If the command fails
then consult the system eventlog for additional information about the component that is using the device.
#>
[CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='high' )]
param(
[Parameter( Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )]
[string]
$sessionId,
[Parameter()]
[switch]
# specify to bypass standard PowerShell confirmation processes
$force
)
process
{
if( -not( $force -or $pscmdlet.shouldProcess( $sessionId, "Disconnect Session" ) ) )
{
return;
}
$data = & iscsicli logouttarget $sessionId | Out-String;
if( $data -notmatch 'success' )
{
throw $data;
}
}
}
#iscsicli ListInitiators
#
function Get-Initiators
{
<#
This command will display the list of initiator instance names that are running and operating with the iSCSI initiator
service.
#>
[CmdletBinding()]
param()
process
{
& iscsicli listinitiators
}
}
#iscsicli SessionList <Show Session Info>
#
function Get-Session
{
<#
This command displays the list of active sessions for all initiators. Note that a session that has no connections is not
connected to the target and is in a retry state.
Microsoft iSCSI Initiator Version 6.1 Build 7601
Total of 2 sessions
Session Id : fffffa800f7900a8-400001370000000d
Initiator Node Name : iqn.1991-05.com.microsoft:archimedes
Target Node Name : (null)
Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-target1
ISID : 40 00 01 37 00 00
TSID : 27 00
Number Connections : 1
Connections:
Connection Id : fffffa800f7900a8-1b
Initiator Portal : 0.0.0.0/58847
Target Portal : 192.168.1.108/3260
CID : 01 00
Devices:
Device Type : Disk
Device Number : 1
Storage Device Type : 7
Partition Number : 0
Friendly Name : ROCKET RAM DISK 1024 M SCSI Disk Device
Device Description : Disk drive
Reported Mappings : Port 1, Bus 0, Target Id 0, LUN 0
Location : Bus Number 0, Target Id 0, LUN 0
Initiator Name : ROOT\\ISCSIPRT\\0000_0
Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-target1
Device Interface Name : \\\\?\\scsi#disk&ven_rocket&prod_ram_disk_1024_m#1&1c121344&0&000000#{53f56307-b6bf-11d0-9
4f2-00a0c91efb8b}
Legacy Device Name : \\\\.\\PhysicalDrive1
Device Instance : 0x82c
Volume Path Names :
E:\\
Session Id : fffffa800f7900a8-400001370000000f
Initiator Node Name : iqn.1991-05.com.microsoft:archimedes
Target Node Name : (null)
Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-scratch
ISID : 40 00 01 37 00 00
TSID : 2b 00
Number Connections : 1
Connections:
Connection Id : fffffa800f7900a8-1d
Initiator Portal : 0.0.0.0/59359
Target Portal : 192.168.1.106/3260
CID : 01 00
Devices:
Device Type : Disk
Device Number : 2
Storage Device Type : 7
Partition Number : 0
Friendly Name : ROCKET RAM DISK 256 MB SCSI Disk Device
Device Description : Disk drive
Reported Mappings : Port 1, Bus 0, Target Id 1, LUN 0
Location : Bus Number 0, Target Id 1, LUN 0
Initiator Name : ROOT\\ISCSIPRT\\0000_0
Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-scratch
Device Interface Name : \\\\?\\scsi#disk&ven_rocket&prod_ram_disk_256_mb#1&1c121344&0&000100#{53f56307-b6bf-11d0-9
4f2-00a0c91efb8b}
Legacy Device Name : \\\\.\\PhysicalDrive2
Device Instance : 0x8ac
#>
[CmdletBinding()]
param(
[Parameter( ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )]
[string]
$sessionId = '.*'
)
process
{
Write-Verbose "Session ID filter: $sessionId";
$data = ( & iscsicli sessionlist ) | out-string;
$data = $data -replace "[`r`n]+",'='
Write-Verbose "raw sessionlist info : $data";
$sessions = $data -split "Session Id\\s+:\\s+";
$sessions = $sessions | where { $_ -match "Connections:" } | foreach {
$session, $data = ( "Session Id : " + $_ ) -split 'Connections:', 2;
$connection, $device = $data -split "Devices:", 2;
Write-Verbose "session $session";
Write-Verbose "connection $connection";
Write-Verbose "device $device";
$session, $connection, $device = $session, $connection, $device | convertFrom-iSCSIOutput;
$session | Add-Member -PassThru -MemberType NoteProperty -Name Connection -Value $connection |
Add-Member -MemberType NoteProperty -Name Device -Value $device;
$session;
}
if( -not $sessions )
{
Write-Verbose "no sessions found"
return;
}
$sessions | write-verbose;
$sessions | where { write-verbose "filtering $($_.SessionId) by $sessionId"; $_.SessionId -match
$sessionId }
}
}
function convertFrom-iSCSIOutput
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[string]
$data,
[Parameter()]
[string]
$itemDelimiter = '=',
[Parameter()]
[string]
$fieldSeparator = ':'
)
process
{
Write-Debug "convertFrom-iSCSIOutput ..."
Write-Debug " Data: $data";
Write-Debug " Item Delimiter: $itemdelimiter";
Write-Debug " Field Separator: $fieldSeparator";
$a = @{};
$data -split $itemDelimiter | where { $_ -match "$fieldSeparator\\s*" } | foreach {
function add-ToA( $k, $v )
{
$k = $k -replace ' ','';
Write-Debug "item key $k; value $v";
$a[$k] = $v;
}
Write-Debug "item entry $_";
$k,$v = $_ -split "\\s*$fieldSeparator\\s*",2;
if( $k -match ' and ' )
{
$k1, $k2 = $k -split ' and ';
$v1, $v2 = $v -split '\\s+',2;
add-ToA $k1 $v1
add-ToA $k2 $v2
}
else
{
add-ToA $k $v
}
}
new-object psobject -Property $a;
}
}
###########################################################
## initialization
Export-ModuleMember -Function '*';
|
PowerShellCorpus/PoshCode/Watch-Process_1.ps1
|
Watch-Process_1.ps1
|
Function Watch-Process {
<#
.DESCRIPTION
Creates an event handler for monitoring either process creation or deletion. This requires to be run as administrator.
.SYNOPSIS
Watches for process creation or deletion.
.PARAMETER computerName
Name of the remote computer. Make sure you have privileges to access remote WMI namespaces.
The default value is local computer.
.PARAMETER Name
Name of the process to monitor.
.PARAMETER Id
Processs ID of the process to monitor.
.PARAMETER Creation
Switch Parameter. Use this to start process creation monitor.
.PARAMETER Deletion
Switch Parameter. Use this to start process deletion monitor.
.PARAMETER Timeout
By default there is no timeout. The process monitor will wait forever. You can specify the maximum timeout period in seconds.
.OUTPUTS
Returns a process object in case of process creation
and returns process exit status in case of process deletion
.EXAMPLE
Watch-Process -computerName TestServer01 -Name "Notepad.exe" -Creation
Description
-----------
The above example demonstrates to how to start a process creation monitor for a remote process
.EXAMPLE
Watch-Process -computerName TestServer01 -Name "notepad.exe" -Deletion
Watch-Process -computerName TestServer01 -Id 3123 -Deletion
Description
-----------
The above creates process deletion monitor for notepad.exe on computer TestServer01 and also creates a process deletion monitor for process ID 3123 on the remote computer.
.LINK
Online version: http://www.ravichaganti.com/blog
#>
[CmdletBinding()]
param (
[Parameter(ParameterSetName="pCreation",Mandatory=$false)]
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[String]$computerName=".",
[Parameter(ParameterSetName="pCreation",Mandatory=$true)]
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[String]$name,
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[int]$Id,
[Parameter(ParameterSetName="pCreation",Mandatory=$false)]
[Switch]$creation,
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[Switch]$deletion,
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[Parameter(ParameterSetName="pCreation",Mandatory=$false)]
[int]$timeout=-1
)
if ($deletion) {
if (($PSBoundParameters.Keys -contains "Name") -and ($PSBoundParameters.Keys -Contains "Id")) {
Write-Error "Both Name and Id parameters are specified. Specify any of these parameters."
return
} elseif ($name) {
$query = "SELECT * FROM Win32_ProcessStopTrace WHERE ProcessName='$($name)'"
Write-Verbose $query
} elseif ($id) {
$query = "SELECT * FROM Win32_ProcessStopTrace WHERE ProcessID='$($Id)'"
Write-Verbose $query
} else {
Write-Error "Neither -Name nor -Id provided. You must provide one of these parameters."
return
}
} elseif ($creation) {
$query = "SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='$($name)'"
Write-Verbose $query
} else {
Write-Error "You must specify an event to monitor. The valid parameters are -deletion or -creation"
return
}
if ($query) {
$srcId = [guid]::NewGuid()
if ($computerName -eq ".") {
#Register a WMI event for process creation or deletion
Write-Verbose "Registering a WMI event"
Register-WmiEvent -Query $query -SourceIdentifier $srcID
#Wait for the event to trigger
Wait-Event -SourceIdentifier $srcID -Timeout $timeout
#Unregister the event. We don't need it anymore
Write-Verbose "Unregistering a WMI event"
Unregister-Event -SourceIdentifier $srcID
} else {
#Register a WMI event for process creation or deletion
Write-Verbose "Registering a WMI event"
Register-WmiEvent -ComputerName $computerName -Query $query -SourceIdentifier $srcID
#Wait for the event to trigger
Wait-Event -SourceIdentifier $srcID -Timeout $timeout
#Unregister the event. We don't need it anymore
Write-Verbose "Unregistering a WMI event"
Unregister-Event -SourceIdentifier $srcID
}
}
}
|
PowerShellCorpus/PoshCode/Restart-IISAppPool_1.ps1
|
Restart-IISAppPool_1.ps1
|
function Restart-IISAppPool {
[CmdletBinding(SupportsShouldProcess=$true)]
#.Synopsis
# Restarts an IIS AppPool
#.Parameter ComputerName
# The name of an IIS web server where the AppPool resides
#.Parameter AppPool
# The name of the AppPool to recycle (if you include wildcards, results in an initial call to list all app pools)
#.Parameter Credential
# Credentials to connect to the IIS Server
#.Example
# Restart-IISAppPool "Classic .NET AppPool" -Cn WebServer1
#
# Description
# -----------
# Restart the "Classic .NET AppPool" on WebServer1
#.Example
# Restart-IISAppPool *Classic* -Confirm
#
# Description
# -----------
# Restart all of the app pools with "Classic" in the name on the local IIS server, prompting for each one
param(
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory= $true, Position=0)]
[Alias("Name","Pool")]
[String[]]$AppPool
,
[Parameter(ValueFromPipelineByPropertyName=$true, Position=1)]
[Alias("CN","Server","__Server")]
[String]$ComputerName
,
[Parameter()]
[System.Management.Automation.Credential()]
$Credential = [System.Management.Automation.PSCredential]::Empty
)
begin {
if ($Credential -and ($Credential -ne [System.Management.Automation.PSCredential]::Empty)) {
$Credential = $Credential.GetNetworkCredential()
}
Write-Debug ("BEGIN:`n{0}" -f ($PSBoundParameters | Out-String))
$Skip = $false
## Need to test for AppPool existence (it's not defined in BEGIN if it's piped in)
if($PSBoundParameters.ContainsKey("AppPool") -and $AppPool -match "\\*") {
$null = $PSBoundParameters.Remove("AppPool")
$null = $PSBoundParameters.Remove("WhatIf")
$null = $PSBoundParameters.Remove("Confirm")
Write-Verbose "Searching for AppPools matching: $($AppPool -join ', ')"
Get-WmiObject IISApplicationPool -Namespace root\\MicrosoftIISv2 -Authentication PacketPrivacy @PSBoundParameters |
Where-Object { @(foreach($pool in $AppPool){ $_.Name -like $Pool -or $_.Name -like "W3SVC/APPPOOLS/$Pool" }) -contains $true } |
Restart-IISAppPool
$Skip = $true
}
$ProcessNone = $ProcessAll = $false;
}
process {
Write-Debug ("PROCESS:`n{0}" -f ($PSBoundParameters | Out-String))
if(!$Skip) {
$null = $PSBoundParameters.Remove("AppPool")
$null = $PSBoundParameters.Remove("WhatIf")
$null = $PSBoundParameters.Remove("Confirm")
foreach($pool in $AppPool) {
Write-Verbose "Processing $Pool"
if($PSCmdlet.ShouldProcess("Would restart the AppPool '$Pool' on the '$(if($ComputerName){$ComputerName}else{'local'})' server.", "Restart ${Pool}?", "Restarting IIS App Pools on $ComputerName")) {
Write-Verbose "Restarting $Pool"
# if($PSCmdlet.ShouldContinue("Do you want to restart $Pool?", "Restarting IIS App Pools on $ComputerName", [ref]$ProcessAll, [ref]$ProcessNone)) {
Invoke-WMIMethod Recycle -Path "IISApplicationPool.Name='$Pool'" -Namespace root\\MicrosoftIISv2 -Authentication PacketPrivacy @PSBoundParameters
# }
}
}
}
}
}
|
PowerShellCorpus/PoshCode/NPS Server Synchronize_2.ps1
|
NPS Server Synchronize_2.ps1
|
###Network Policy Server Synchronization Script
#This script copies the configuration from the NPS Master Server and imports it on this server.
#The Account that this script runs under must have Local Administrator rights to the NPS Master.
#This was designed to be run as a scheduled task on the NPS Secondary Servers on an hourly,daily, or as-needed basis.
#Last Modified 01 Dec 2009 by JGrote <jgrote AT enpointe NOSPAM-DOTCOM>
###Variables
#NPSMaster - Your Primary Network Policy Server you want to copy the config from.
$NPSMaster = "Server1"
#NPSConfigTempFile - A temporary location to store the XML config. Use a UNC path so that the primary can save the XML file across the network. Be sure to set secure permissions on this folder, as the configuration including pre-shared keys is temporarily stored here during the import process.
$NPSConfigTempFile = "\\\\server2\\C$\\Temp\\NPSConfigTemp\\NPSConfig-$NPSMaster.xml"
#Create an NPS Sync Event Source if it doesn't already exist
if (!(get-eventlog -logname "System" -source "NPS-Sync")) {new-eventlog -logname "System" -source "NPS-Sync"}
#Write an error and exit the script if an exception is ever thrown
trap {write-eventlog -logname "System" -eventID 1 -source "NPS-Sync" -EntryType "Error" -Message "An Error occured during NPS Sync: $_. Script run from $($MyInvocation.MyCommand.Definition)"; exit}
#Connect to NPS Master and export configuration
$configExportResult = invoke-command -ComputerName $NPSMaster -ArgumentList $NPSConfigTempFile -scriptBlock {param ($NPSConfigTempFile) netsh nps export filename = $NPSConfigTempFile exportPSK = yes}
#Verify that the import XML file was created. If it is not there, it will throw an exception caught by the trap above that will exit the script.
$NPSConfigTest = Get-Item $NPSConfigTempFile
#Clear existing configuration and import new NPS config
$configClearResult = netsh nps reset config
$configImportResult = netsh nps import filename = $NPSConfigTempFile
#Delete Temporary File
remove-item -path $NPSConfigTempFile
#Compose and Write Success Event
$successText = "Network Policy Server Configuration successfully synchronized from $NPSMaster.
Export Results: $configExportResult
Import Results: $configImportResult
Script was run from $($MyInvocation.MyCommand.Definition)"
write-eventlog -logname "System" -eventID 1 -source "NPS-Sync" -EntryType "Information" -Message $successText
|
PowerShellCorpus/PoshCode/Invoke-MoveRequest_2.ps1
|
Invoke-MoveRequest_2.ps1
|
###########################################################################
#
# NAME: Invoke-MoveRequest.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jer@powershell.no
#
# COMMENT: Script to use when migrating mailboxes to Microsoft Exchange Server 2010 Cross-Forest. Prepares user objects already
# moved to the target forest using Active Directory Migration Tool or other tools, and then invokes the mailbox move request.
# For more information, see the following blog-post: http://blog.powershell.no/2010/04/23/exchange-server-2010-cross-forest-migration
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 23.04.2010 - Initial release
#
###########################################################################
#Adding Quest AD PowerShell Commands Snapin and Microsoft Exchange Server 2010 PowerShell Snapin
Add-PSSnapin Quest.ActiveRoles.ADManagement
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
#Custom variables, edit this section
$TargetDatabase = "Mailbox Database A"
$TargetDeliveryDomain = "domain.com"
$TargetForest="DomainA.local"
$SourceForest="domainB.local"
$SourceForestGlobalCatalog = "dc-01.domainB.local"
$SourceForestCredential = Get-Credential -Credential "Domain\\SourceForestAdministrator"
#Connect to source forest to collect users to migrate
Connect-QADService -Service $SourceForest | Out-Null
$SourceForestUsersToMigrate = Get-QADUser -SearchRoot "DomainA.local/Department A/Users"
foreach ($user in $SourceForestUsersToMigrate) {
Write-Host "Processing user $user" -ForegroundColor Yellow
#Connect to source forest to collect source object attributes
Connect-QADService -Service $SourceForest | Out-Null
$TargetObject=$user.samaccountname
$SourceObject=Get-QADUser $TargetObject -IncludeAllProperties
$mail=$SourceObject.Mail
$mailNickname=$SourceObject.mailNickname
[byte[]]$msExchMailboxGUID=(Get-QADuser $SourceObject -IncludedProperties msExchMailboxGUID -DontConvertValuesToFriendlyRepresentation).msExchMailboxGUID
$msExchRecipientDisplayType="-2147483642"
$msExchRecipientTypeDetails="128"
$msExchUserCulture=$SourceObject.msExchUserCulture
$msExchVersion="44220983382016"
$proxyAddresses=$SourceObject.proxyAddresses
$targetAddress=$SourceObject.Mail
$userAccountControl=514
#Connect to target forest to set target object attributes
Connect-QADService -Service $TargetForest | Out-Null
Set-QADUser -Identity $TargetObject -ObjectAttributes @{mail=$mail;mailNickname=$mailNickname;msExchMailboxGUID=$msExchMailboxGUID;msExchRecipientDisplayType=$msExchRecipientDisplayType;msExchRecipientTypeDetails=$msExchRecipientTypeDetails;msExchUserCulture=$msExchUserCulture;msExchVersion=$msExchVersion;proxyAddresses=$proxyAddresses;targetAddress=$targetAddress;userAccountControl=$userAccountControl} | Out-Null
#Update Exchange-attributes (LegacyExchangeDN etc.)
Get-MailUser $TargetObject | Update-Recipient
#Invoking a new move-request
New-MoveRequest -Identity $TargetObject -RemoteLegacy -TargetDatabase $TargetDatabase -RemoteGlobalCatalog $SourceForestGlobalCatalog -RemoteCredential $SourceForestCredential -TargetDeliveryDomain $TargetDeliveryDomain
#Enable target object and unset "User must change password at next logon"
Enable-QADUser -Identity $TargetObject | Out-Null
Set-QADUser -Identity $TargetObject -UserMustChangePassword $false | Out-Null
}
|
PowerShellCorpus/PoshCode/Get-LocalGroupMembers.ps1
|
Get-LocalGroupMembers.ps1
|
function Get-LocalGroupMembers {
param($groupname)
$pattern = "*Name=`"$groupname`""
$groupusers = gwmi Win32_GroupUser | Where { $_.GroupComponent -like $pattern }
# Now extract the usernames.
foreach ($user in $groupusers) {
if ($user.PartComponent -match 'Name="([^"]+)') {
Write-Output $matches[1]
}
}
}
# Use it like this.
# Get-GroupMembers Administrators
|
PowerShellCorpus/PoshCode/Security group monitor.ps1
|
Security group monitor.ps1
|
#Get group membership for a list of security
#groups and export to an XML for comparison
#against baseline.
#
$script:WorkingDirectory = split-path $myinvocation.Mycommand.Definition -parent
Function Re-Baseline
{
#First, declare array and hashtable.
$securitygroups = @()
$table = @{}
#Import Security Group list from XML and add to "securitygroups" array.
$securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml")
$securitygroups += $securitygroupsxml.objs.S
#Get membership for each group
foreach($securitygroup in $securitygroups){
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))"
$group = $searcher.findone()
$table += @{"$securitygroup"= $group.properties.member}
}
#Export hashtable to XML. So nice.
$table | export-clixml $script:WorkingDirectory\\baseline.xml
}
#
#First, declare hashtable.
$comparetable = @{}
#Import Security Group list from XML and add to "securitygroups" array.
$securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml")
$securitygroups = $securitygroupsxml.objs.S
#Get membership for each group and create a compare table.
foreach($securitygroup in $securitygroups){
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))"
$group = $searcher.findone()
$comparetable += @{"$securitygroup"= $group.properties.member}
}
#Export hashtable to XML. So nice.
$comparetable | export-clixml "$script:WorkingDirectory\\compare.xml"
#Import baseline XML to hashtable.
$baselinetable = @{}
$baselinetable += import-clixml "$script:WorkingDirectory\\baseline.xml"
#Import baseline XML to hashtable.
$comparetable = @{}
$comparetable += import-clixml "$script:WorkingDirectory\\compare.xml"
#Compare respective Keys and Values for $comparetable against
#$baselinetable and get differences.
$passtoemailsubuser = @()
$passtoemailbody = @()
foreach($securitygroup in $securitygroups) {
If($comparetable."$securitygroup" -eq $NULL)
{
If($baselinetable."$securitygroup" -eq $NULL)
{
(get-date).tostring() + " - Security Group $securitygroup is empty in the compare and the baseline" >> $script:WorkingDirectory\\log.txt
}
Else
{
foreach($entry in $baselinetable."$securitygroup")
{$passtoemailbody += "`r" + $entry + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r"}
$passtoemailbody += "`r" + $securitygroup + " " + "`r`r" + "in AD contains no more objects" + "`r`r"
(get-date).tostring() + " - $securitygroup in AD contains no more objects" >> $script:WorkingDirectory\\log.txt
}
}
Else
{
$baseline = @($baselinetable."$securitygroup")
$compare = @($comparetable."$securitygroup")
$results = Compare-Object $baseline $compare
foreach($result in $results){
if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "=>")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS ADDED TO***: " + "`r`r" + $securitygroup + "`r`r"
$user = $result.inputobject
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))"
$user = $searcher.FindOne()
$passtoemailsubuser += $user.properties.samaccountname
$mod = $true
}
if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "<=")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r"
$user = $result.inputobject
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))"
$user = $searcher.FindOne()
$passtoemailsubuser += $user.properties.samaccountname
$mod = $true
}}
}
}
if ($mod -eq $true) {
$from = New-Object System.Net.Mail.MailAddress "from@address.com"
$to = New-Object System.Net.Mail.MailAddress "to@address.com"
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = "The following accounts were involved in a security group modification: $passtoemailsubuser"
$message.Body = "Note the following security group modification information: `r`r $passtoemailbody"
$server = "SMTPSERVERNAME"
$client = new-object system.net.mail.smtpclient $server
$client.port = 125
$client.Send($message)
foreach($entry in $passtoemailbody)
{(get-date).tostring() + " - " + $Entry >> $script:WorkingDirectory\\Log.txt}
(get-date).tostring() + " - Group Membership compare has been baselined" >> $script:WorkingDirectory\\log.txt
re-baseline
}
else {
$from = New-Object System.Net.Mail.MailAddress "from@address.com"
$to = New-Object System.Net.Mail.MailAddress "to@address.com"
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = "No modifications to the audited security groups have been made."
$message.Body = "No modifications to the audited security groups have been made."
$server = "SMTPSERVERNAME"
$client = new-object system.net.mail.smtpclient $server
$client.port = 125
$client.Send($message)
"No Changes have been made"
}
|
PowerShellCorpus/PoshCode/Get-PendingUpdates.ps1
|
Get-PendingUpdates.ps1
|
Function Get-PendingUpdates {
<#
.SYNOPSIS
Retrieves the updates waiting to be installed from WSUS
.DESCRIPTION
Retrieves the updates waiting to be installed from WSUS
.PARAMETER Computer
Computer or computers to find updates for.
.EXAMPLE
Get-PendingUpdates
Description
-----------
Retrieves the updates that are available to install on the local system
.NOTES
Author: Boe Prox
Date Created: 05Mar2011
#>
#Requires -version 2.0
[CmdletBinding(
DefaultParameterSetName = 'computer'
)]
param(
[Parameter(
Mandatory = $False,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string[]]$Computer
)
Begin {
$scriptdir = { Split-Path $MyInvocation.ScriptName –Parent }
Write-Verbose "Location of function is: $(&$scriptdir)"
$psBoundParameters.GetEnumerator() | ForEach-Object { Write-Verbose "Parameter: $_" }
If (!$PSBoundParameters['computer']) {
Write-Verbose "No computer name given, using local computername"
[string[]]$computer = $Env:Computername
}
#Create container for Report
Write-Verbose "Creating report collection"
$report = @()
}
Process {
ForEach ($c in $Computer) {
Write-Verbose "Computer: $($c)"
If (Test-Connection -ComputerName $c -Count 1 -Quiet) {
Try {
#Create Session COM object
Write-Verbose "Creating COM object for WSUS Session"
$updatesession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session",$c))
}
Catch {
Write-Warning "$($Error[0])"
Break
}
#Configure Session COM Object
Write-Verbose "Creating COM object for WSUS update Search"
$updatesearcher = $updatesession.CreateUpdateSearcher()
#Configure Searcher object to look for Updates awaiting installation
Write-Verbose "Searching for WSUS updates on client"
$searchresult = $updatesearcher.Search("IsInstalled=0")
#Verify if Updates need installed
Write-Verbose "Verifing that updates are available to install"
If ($searchresult.Updates.Count -gt 0) {
#Updates are waiting to be installed
Write-Verbose "Found $($searchresult.Updates.Count) update\\s!"
#Cache the count to make the For loop run faster
$count = $searchresult.Updates.Count
#Begin iterating through Updates available for installation
Write-Verbose "Iterating through list of updates"
For ($i=0; $i -lt $Count; $i++) {
#Create object holding update
$update = $searchresult.Updates.Item($i)
#Verify that update has been downloaded
Write-Verbose "Checking to see that update has been downloaded"
If ($update.IsDownLoaded -eq "True") {
Write-Verbose "Auditing updates"
$temp = "" | Select Computer, Title, KB,IsDownloaded
$temp.Computer = $c
$temp.Title = ($update.Title -split('\\('))[0]
$temp.KB = (($update.title -split('\\('))[1] -split('\\)'))[0]
$temp.IsDownloaded = "True"
$report += $temp
}
Else {
Write-Verbose "Update has not been downloaded yet!"
$temp = "" | Select Computer, Title, KB,IsDownloaded
$temp.Computer = $c
$temp.Title = ($update.Title -split('\\('))[0]
$temp.KB = (($update.title -split('\\('))[1] -split('\\)'))[0]
$temp.IsDownloaded = "False"
$report += $temp
}
}
}
Else {
#Nothing to install at this time
Write-Verbose "No updates to install."
#Create Temp collection for report
$temp = "" | Select Computer, Title, KB,IsDownloaded
$temp.Computer = $c
$temp.Title = "NA"
$temp.KB = "NA"
$temp.IsDownloaded = "NA"
$report += $temp
}
}
Else {
#Nothing to install at this time
Write-Warning "$($c): Offline"
#Create Temp collection for report
$temp = "" | Select Computer, Title, KB,IsDownloaded
$temp.Computer = $c
$temp.Title = "NA"
$temp.KB = "NA"
$temp.IsDownloaded = "NA"
$report += $temp
}
}
}
End {
Write-Output $report
}
}
|
PowerShellCorpus/PoshCode/Get-Parameter_11.ps1
|
Get-Parameter_11.ps1
|
function Get-Parameter ( $Cmdlet, [switch]$ShowCommon, [switch]$Full ) {
$command = Get-Command $Cmdlet -ea silentlycontinue
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = Get-Command ($command.definition)
}
if (-not $command) { return }
foreach ($paramset in $command.ParameterSets){
$Output = @()
foreach ($param in $paramset.Parameters) {
if ( ! $ShowCommon ) {
if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue }
}
$process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory,
Pipeline, PipelineByPropertyName
$process.Name = $param.Name
if ( $param.ParameterType.Name -eq "SwitchParameter" ) {
$process.Type = "Boolean"
}
else {
switch -regex ( $param.ParameterType ) {
"Nullable``1\\[(.+)\\]" { $process.Type = $matches[1].Split('.')[-1] + " (nullable)" ; break }
default { $process.Type = $param.ParameterType.Name }
}
}
if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" }
else { $process.ParameterSet = $paramset.Name }
$process.Aliases = $param.aliases
if ( $param.Position -lt 0 ) { $process.Position = $null }
else { $process.Position = $param.Position }
$process.IsMandatory = $param.IsMandatory
$process.Pipeline = $param.ValueFromPipeline
$process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName
$output += $process
}
if ( ! $Full ) {
$Output | Select-Object Name, Type, ParameterSet, IsMandatory, Pipeline
}
else { Write-Output $Output }
}
}
|
PowerShellCorpus/PoshCode/Compare-DatabaseColumns.ps1
|
Compare-DatabaseColumns.ps1
|
param( [String[]]$Table = $null,
$SqlServerOne = 'YourDatabaseServer',
$FirstDatabase = 'FirstDatabaseToCompare',
$SqlUsernameOne = 'SQL Login',
$SqlPasswordOne = 'SQL Password',
$SqlServerTwo = 'YourDatabaseServer',
$SecondDatabase = 'SecondDatabaseToCompare',
$SqlUsernameTwo = 'SQL Login',
$SqlPasswordTwo = 'SQL Password',
$FilePrefix = 'Log',
[switch]$Log,
[switch]$Column)
if ($Input)
{
foreach ($item in $Input)
{
if ($item -is [string])
{
$Table += $item
}
else
{
foreach ($property in $item.psobject.properties)
{
if ('name', 'TableName' -contains $property.name)
{
$Table += $Property.value
break
}
}
}
}
}
if ($Table.count -eq 0)
{
throw 'A table to compare is required.'
}
$File = $FilePrefix + '{0}-{1}.csv'
$OFS = "', '"
$ColumnQuery = @"
SELECT sysobjects.name AS TableName, syscolumns.name AS ColumnName, systypes.name AS type,
syscolumns.length
FROM systypes
INNER JOIN syscolumns ON systypes.xusertype = syscolumns.xusertype --get data type info
INNER JOIN sysobjects ON syscolumns.id = sysobjects.id
WHERE
sysobjects.name IN ('$Table')
"@
function Run-Query()
{
param (
$SqlQuery,
$SqlServer,
$SqlCatalog,
$SqlUser,
$SqlPass
)
$SqlConnString = "Server = $SqlServer; Database = $SqlCatalog; user = $SqlUser; password = $SqlPass"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $SqlConnString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$a = $SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables | Select-Object -ExpandProperty Rows
}
[String[]]$Properties = 'TableName', 'ColumnName', 'Type', 'Length'
Write-Debug "Checking Tables: '$Table'"
$ColumnsDBOne = Run-Query -SqlQuery $ColumnQuery -SqlServer $SqlServerOne -SqlCatalog $FirstDatabase -SqlUser $SqlUsernameOne -SqlPass $SqlPasswordOne | Select-Object -Property $Properties
$ColumnsDBTwo = Run-Query -SqlQuery $ColumnQuery -SqlServer $SqlServerTwo -SqlCatalog $SecondDatabase -SqlUser $SqlUsernameTwo -SqlPass $SqlPasswordTwo | Select-Object -Property $Properties
Write-Host 'Differences in Columns: '
$Database = @{Name='Database';Expression={if ($_.SideIndicator -eq '<='){'{0} / {1}' -f $FirstDatabase, $SqlServerOne} else {'{0} / {1}' -f $SecondDatabase, $SqlServerTwo}}}
$ColumnDifference = Compare-Object $ColumnsDBOne $ColumnsDBTwo -SyncWindow (($TablesDBOne.count + $TablesDBTwo.count)/2) -Property $Properties | select 'TableName', 'ColumnName', 'Type', 'Length', $Database
if ($log)
{
$ColumnDifference | Export-Csv -Path ($file -f $FirstDatabase, $SecondDatabase) -NoTypeInformation
}
$OFS = ', '
$ColumnDifference | Sort-Object -Property 'TableName', 'ColumnName', 'Type', 'Length', 'Database'
|
PowerShellCorpus/PoshCode/Get-Parameter 2.5.ps1
|
Get-Parameter 2.5.ps1
|
#Requires -version 2.0
#.Synopsis
# Enumerates the parameters of one or more commands
#.Notes
# With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy
# Version 0.80 - April 2008 - By Hal Rottenberg http://poshcode.org/186
# Version 0.81 - May 2008 - By Hal Rottenberg http://poshcode.org/255
# Version 0.90 - June 2008 - By Hal Rottenberg http://poshcode.org/445
# Version 0.91 - June 2008 - By Oisin Grehan http://poshcode.org/446
# Version 0.92 - April 2008 - By Hal Rottenberg http://poshcode.org/549
# - Added resolving aliases and avoided empty output
# Version 0.93 - Sept 24, 2009 - By Hal Rottenberg http://poshcode.org/1344
# Version 1.0 - Jan 19, 2010 - By Joel Bennett http://poshcode.org/1592
# - Merged Oisin and Hal's code with my own implementation
# - Added calculation of dynamic paramters
# Version 2.0 - July 22, 2010 - By Joel Bennett http://poshcode.org/get/2005
# - Now uses FormatData so the output is objects
# - Added calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982, but with a correct implementation)
# Version 2.1 - July 22, 2010 - By Joel Bennett http://poshcode.org/2007
# - Fixed Help for SCRIPT file (script help must be separated from #Requires by an emtpy line)
# - Fleshed out and added dates to this version history after Bergle's criticism ;)
# Version 2.2 - July 29, 2010 - By Joel Bennett http://poshcode.org/2030
# - Fixed a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo
# Version 2.3 - July 29, 2010 - By Joel Bennett
# - Added a ToString ScriptMethod which allows queries like:
# $parameters = Get-Parameter Get-Process; $parameters -match "Name"
# Version 2.4 - July 29, 2010 - By Joel Bennett http://poshcode.org/2032
# - CHANGED "Name" to CommandName
# - ADDED ParameterName parameter to allow filtering parameters
# - Fixed bug in 2.3 and 2.2 with dynamic parameters
# Version 2.5 - December 13, 2010 - By Jason Archer (This Version)
# - CHANGED format temp file to have static name, prevents bloat of random temporary files
#
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[Alias("Name")]
[string[]]$CommandName
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
[string[]]$ParameterName="*"
,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$Force
)
Function global:Get-Parameter {
#.Synopsis
# Enumerates the parameters of one or more commands
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string[]]$CommandName
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
[string[]]$ParameterName="*"
,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$Force
)
begin {
$PropertySet = @( "Name",
@{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}},
"Aliases",
@{n="Short";e={$_.Name}},
@{n="Type";e={$_.ParameterType.Name}},
@{n="ParameterSet";e={$paramset}},
@{n="Command";e={$command}},
@{n="Mandatory";e={$_.IsMandatory}},
@{n="Provider";e={$_.DynamicProvider}},
@{n="ValueFromPipeline";e={$_.ValueFromPipeline}},
@{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}}
)
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(ValueFromPipeline=$true,Position=1)]
$Second
)
begin {
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
process {
$Output = $First | Select $p1
foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
}
$Output
}
}
}
process{
foreach($cmd in $CommandName) {
if($ModuleName) { $cmd = "$ModuleName\\$cmd" }
$commands = @(Get-Command $cmd)
foreach($command in $commands) {
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = @(Get-Command ($command.definition))[0]
}
if (-not $command) { continue }
$Parameters = @{}
foreach($provider in Get-PSProvider) {
$drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name
Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters")
[Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values
[Array]$Dynamic = $MoreParameters | Where { $_.IsDynamic }
foreach($p in $MoreParameters | Where { !$Parameters.ContainsKey( $_.Name ) } ){ $Parameters.($p.Name) = $p }
# Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)"
if($dynamic) {
foreach($d in $dynamic) {
if(Get-Member -input $Parameters.($d.Name) -Name DynamicProvider) {
Write-Debug ("ADD:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name).DynamicProvider += $provider.Name
} else {
Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru
}
}
}
}
## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else.
foreach($p in $($Parameters.Keys))
{
$shortest="^"
foreach($char in [char[]]$p)
{
$shortest += $char
$Matches = ($Parameters.Keys -match $Shortest).Count
Write-Debug "$($shortest.SubString(1)) $Matches"
if($Matches -eq 1)
{
$Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru
break
}
}
}
Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)"
foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){
foreach($parameter in $Parameters.Keys | Sort) {
Write-Verbose "Parameter: $Parameter"
if(!$Force -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue }
if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) {
if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet
} else {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets
}
Write-Output $Output | Select-Object $PropertySet | ForEach {
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata")
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx")
Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")"
$_
} |
Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru |
Where-Object { $(foreach($pn in $ParameterName){ $_ -like $Pn}) -contains $true }
}
}
}
}
}
}
}
# Since you can't update format data without a file that has a ps1xml ending, let's make one up...
$tempFile = "$([System.IO.Path]::GetTempPath())Get-Parameter.ps1xml"
Set-Content $tempFile @'
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<Controls>
<Control>
<Name>ParameterGroupingFormat</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<Frame>
<LeftIndent>4</LeftIndent>
<CustomItem>
<Text>Command: </Text>
<ExpressionBinding>
<ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock>
</ExpressionBinding>
<NewLine/>
<Text>Set: </Text>
<ExpressionBinding>
<ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock>
</ExpressionBinding>
<NewLine/>
</CustomItem>
</Frame>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</Control>
</Controls>
<ViewDefinitions>
<View>
<Name>ParameterMetadataEx</Name>
<ViewSelectedBy>
<TypeName>System.Management.Automation.ParameterMetadataEx</TypeName>
</ViewSelectedBy>
<GroupBy>
<PropertyName>ParameterSet</PropertyName>
<CustomControlName>ParameterGroupingFormat</CustomControlName>
</GroupBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Name</Label>
<Width>22</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Aliases</Label>
<Width>12</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Position</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Mandatory</Label>
<Width>9</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Pipeline</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>ByName</Label>
<Width>6</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Provider</Label>
<Width>15</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Type</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Aliases</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Position</PropertyName-->
<ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Mandatory</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipeline</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipelineByPropertyName</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Provider</PropertyName-->
<ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Type</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
'@
Update-FormatData -Append $tempFile
# This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that.
Get-Parameter @PSBoundParameters
|
PowerShellCorpus/PoshCode/Import-GalPhoto.ps1
|
Import-GalPhoto.ps1
|
<#
.Synopsis
Import Exchange 2010 Gal photo for one or more users.
.DESCRIPTION
This function invokes the Import-RecipientDataProperty cmdldet to import a picture into the thumbnailPhoto attribute of an Exchange mailbox.
It assumes you have a directory containing all images to import, with the file names corresponding to the usernames of the mailboxes.
PS X:\\> dir *.jpg
Directory: c:\\temp\\pics
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 07.08.2012 19:29 5984 user1.name.jpg
-a--- 16.05.2012 11:58 5984 user2.jpg
-a--- 23.07.2012 15:55 5984 user3.name.jpg
...
.EXAMPLE
PS C:\\> Import-GalPhoto -FilePath 'c:\\temp\\pics'
This example gets all .jpg pictures from c:\\temp\\pics and tries to find corresponding Exchange Users. If a user is found, the picture is imported using Import-RecipientDataProperty.
.EXAMPLE
PS C:\\> dir 'c:\\temp\\pics' | Select-Object -First 2 | Import-GalPhoto
This example shows how you can use Get-ChildItem (dir) and do some custom filtering (Where-Object, Select-Object) to get pictures.
Then it makes use of pipeline input to import pictures.
#>
function Import-GalPhoto
{
[CmdletBinding(SupportsShouldProcess=$true,
ConfirmImpact='High')]
Param
(
# Set the FilePath where pictures are located
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[Alias('FullName')]
[IO.FileInfo]
$FilePath,
# LogFile set the destination for LogFile, defaults to ".\\Import-GalPhoto.txt"
[Parameter(Mandatory=$false,
ParameterSetName='Parameter Set 1')]
$LogFile=".\\Import-GalPhoto.txt"
)
Begin
{
Write-Verbose 'Execute Begin Block'
# delete LogFile
Remove-Item $LogFile -ErrorAction SilentlyContinue
# load assembly, used to get Image Properties
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
# logging
"$(Get-Date) Function begin" | Add-Content -Path $LogFile -WhatIf:$false
}
Process
{
Write-Verbose 'Execute Process Block'
# create an array that contains all files
[array]$arrPics = Get-ChildItem -Path $FilePath -File -Filter '*.jpg'
"$(Get-Date) arrPics is $($arrPics)" | Add-Content -Path $LogFile -WhatIf:$false
$arrPics | ForEach-Object {
# objPicture contains full path to the picture
[IO.FileInfo]$objPicture = $_.FullName
# assume file BaseName equals UserName
[string]$strUserName = $_.BaseName
# logging
Write-Verbose "`$objPicture is $objPicture"
Write-Verbose "`$strUserName is $strUserName"
"$(Get-Date) objPicture is $($objPicture)" | Add-Content -Path $LogFile -WhatIf:$false
"$(Get-Date) strUserName is $($strUserName)" | Add-Content -Path $LogFile -WhatIf:$false
# some verification before manipulating stuff
try {
Write-Verbose "Try to find User $strUserName"
Start-Sleep -Seconds 1
$exchangeUser = Get-User -Identity $strUserName -ErrorAction Stop
$Continue = $true
# get Image Properties
$objImage = [System.Drawing.Image]::FromFile($objPicture)
# get content from image file, used with Import-RecipientDataProperty
$objFileData = ([Byte[]]$(Get-Content -Path $objPicture -Encoding Byte -ReadCount 0 -ErrorAction Stop))
# logging
Write-Verbose "`$exchangeUser is $($exchangeUser.SamAccountName)"
Write-Verbose "`$objImage PhysicalDimensionis is $($objImage.PhysicalDimension)"
Write-Verbose "`$objPicture filesize(KB) is $($objPicture.Length / 1kb)"
"$(Get-Date) exchangeUser is $($exchangeUser.SamAccountName)" | Add-Content -Path $LogFile -WhatIf:$false
"$(Get-Date) Image PhysicalDimension is $($objImage.PhysicalDimension)" | Add-Content -Path $LogFile -WhatIf:$false
"$(Get-Date) Image filesize(KB) is $($objPicture.Length / 1kb)" | Add-Content -Path $LogFile -WhatIf:$false
} catch {
$Continue = $false
# logging
Write-Warning "Could not find User $strUserName"
"$(Get-Date) Could not find $($strUserName)" | Add-Content -Path $LogFile -WhatIf:$false
}
# use objImage to check if image size is ok, max 96x96 pixels, max 10K
if ($Continue -and (($objImage.Height -le 96) -and ($objImage.Width -le 96) -and ($objPicture.Length -le 10kb))){
$Continue = $true
# get rid of objImage
$objImage.Dispose()
# logging
Write-Verbose "Picture $($objPicture) is ok"
} else {
$Continue = $false
# logging
Write-Verbose "Picture $($objPicture) is not ok"
"$(Get-Date) Skipped $($objPicture) size not ok" | Add-Content -Path $LogFile -WhatIf:$false
}
# if verification is ok, go ahead and import images
if ($Continue -and ($pscmdlet.ShouldProcess("$($exchangeUser.SamAccountName)", "Importing Recipient Data Property from file $objPicture"))) {
# invoke Import-RecipientDataProperty to import data into active directory
Import-RecipientDataProperty -Identity $exchangeUser.Identity -Picture -FileData $objFileData
}
}
}
End
{
Write-Verbose 'Execute End Block'
# logging
"$(Get-Date) Function end" | Add-Content -Path $LogFile -WhatIf:$false
}
}
|
PowerShellCorpus/PoshCode/ShowUI Weather Widget_1.ps1
|
ShowUI Weather Widget_1.ps1
|
## And a slick weather widget using Yahoo's forecast and images
New-UIWidget -AsJob {
Grid {
Rectangle -RadiusX 10 -RadiusY 10 -StrokeThickness 0 -Width 170 -Height 80 -HorizontalAlignment Left -VerticalAlignment Top -Margin "60,40,0,0" -Fill {
LinearGradientBrush -Start "0.5,0" -End "0.5,1" -Gradient {
GradientStop -Color "#FF007bff" -Offset 0
GradientStop -Color "#FF40d6ff" -Offset 1
}
}
Image -Name Image -Stretch Uniform -Width 250.0 -Height 180.0 -Source "http://l.yimg.com/a/i/us/nws/weather/gr/31d.png"
TextBlock -Name Temp -Text "99°" -FontSize 80 -Foreground White -Margin "130,0,0,0" -Effect { DropShadowEffect -Color Black -Shadow 0 -Blur 8 }
TextBlock -Name Forecast -Text "Forecast" -FontSize 12 -Foreground White -Margin "120,95,0,0"
}
} -Refresh "00:10" {
# To find your WOEID, browse or search for your city from the Weather home page.
# The WOEID is the LAST PART OF the URL for the forecast page for that city.
$woEID = 14586
$channel = ([xml](New-Object Net.WebClient).DownloadString("http://weather.yahooapis.com/forecastrss?p=$woEID")).rss.channel
$h = ([int](Get-Date -f hh))
if($h -gt ([DateTime]$channel.astronomy.sunrise).Hour -and $h -lt ([DateTime]$channel.astronomy.sunset).Hour) {
$dayOrNight = 'd'
} else {
$dayOrNight = 'n'
}
$source = "http`://l.yimg.com/a/i/us/nws/weather/gr/{0}{1}.png" -f $channel.item.condition.code, $dayOrNight
$Image.Source = $source
$Temp.Text = $channel.item.condition.temp + [char]176
$Forecast.Text = "High: {0}{2} Low: {1}{2}" -f $channel.item.forecast[0].high, $channel.item.forecast[0].low, [char]176
}
|
PowerShellCorpus/PoshCode/Migrate UserFolder.ps1
|
Migrate UserFolder.ps1
|
param(
$RootFolder = "\\\\domain.local\\users",
$NewRootFolder = "\\\\domain.local\\users2",
$LogFolder = "c:\\Projects\\HomeDirs",
$NewSubFolders = @("Documents","Favorites","Desktop","Links","Contacts","BlaBla"),
[switch]$SetACL
)
$UserFolders = gci -Path $RootFolder | ?{$_.PSIsContainer}
$UserFolders | foreach-object -Process {
#create new homedrive
$NewUserFolder = $NewRootFolder + "\\" + $_.name
if ($SetACL){
#set ACL rules for new homedrive
$acl = Get-Acl $_.FullName
$Owner = New-Object System.Security.Principal.NTAccount("uza.local",$_.name)
$acl.SetOwner($Owner)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($_.Name,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
}
#create required subfolders per homedrive
$NewSubFolders | foreach{New-Item -Path $($NewUserFolder + "\\" + $_) -type directory}
#build robocopy job per homedrive
$LogFile = $LogFolder + "\\" + $_.name + ".log"
$JobName = $_.name + "_RCsync"
$CommandString = "robocopy $($_.FullName) $($NewUserFolder + "\\Documents") /COPYALL /MIR /FFT /Z /Log+:$LogFile"
start-job -Scriptblock {invoke-Expression $input} -name $JobName -InputObject $CommandString
}
#Wait for all jobs
Get-Job | Wait-Job
#Get all job results
Get-Job | Receive-Job
|
PowerShellCorpus/PoshCode/Speech Recognition_1.ps1
|
Speech Recognition_1.ps1
|
$null = [Reflection.Assembly]::LoadWithPartialName("System.Speech")
## Create the two main objects we need for speech recognition and synthesis
if(!$Global:SpeechModuleListener){ ## For XP's sake, don't create them twice...
$Global:SpeechModuleSpeaker = new-object System.Speech.Synthesis.SpeechSynthesizer
$Global:SpeechModuleListener = new-object System.Speech.Recognition.SpeechRecognizer
}
$Script:SpeechModuleMacros = @{}
## Add a way to turn it off
$Script:SpeechModuleMacros.Add("Stop Listening", { $script:listen = $false; Suspend-Listening })
$Script:SpeechModuleComputerName = ${Env:ComputerName}
function Update-SpeechCommands {
#.Synopsis
# Recreate the speech recognition grammar
#.Description
# This parses out the speech module macros,
# and recreates the speech recognition grammar and semantic results,
# and then updates the SpeechRecognizer with the new grammar,
# and makes sure that the ObjectEvent is registered.
$choices = new-object System.Speech.Recognition.Choices
foreach($choice in $Script:SpeechModuleMacros.GetEnumerator()) {
$g = New-Object System.Speech.Recognition.GrammarBuilder
$phrases = @($choice.Key -split "\\s*\\*\\s*")
for($i=0;$i -lt $phrases.Count;$i++) {
if($phrases[$i].Length -gt 0) {
$g.Append( $phrases[$i] )
if($i+1 -lt $phrases.Count) {
$g.AppendDictation()
}
} elseif($i -eq 0) {
$g.AppendDictation()
}
}
$choices.Add( (New-Object System.Speech.Recognition.SemanticResultValue $g,
$choice.Value.ToString()).ToGrammarBuilder() )
}
if($VerbosePreference -ne "SilentlyContinue") { $Script:SpeechModuleMacros.Keys | ForEach-Object { Write-Host "$($Script:SpeechModuleComputerName), $_" -Fore Cyan } }
$builder = New-Object System.Speech.Recognition.GrammarBuilder "$($Script:SpeechModuleComputerName), "
$builder.Append((New-Object System.Speech.Recognition.SemanticResultKey "Commands", $choices.ToGrammarBuilder()))
$grammar = new-object System.Speech.Recognition.Grammar $builder
$grammar.Name = "Power VoiceMacros"
## Take note of the events, but only once (make sure to remove the old one)
Unregister-Event "SpeechModuleCommandRecognized" -ErrorAction SilentlyContinue
$null = Register-ObjectEvent $grammar SpeechRecognized `
-SourceIdentifier "SpeechModuleCommandRecognized" `
-Action { iex $event.SourceEventArgs.Result.Semantics.Item("Commands").Value }
$Global:SpeechModuleListener.UnloadAllGrammars()
$Global:SpeechModuleListener.LoadGrammarAsync( $grammar )
}
function Add-SpeechCommands {
#.Synopsis
# Add one or more commands to the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
[CmdletBinding()]
Param([hashtable]$VoiceMacros,[string]$Computer=$Script:SpeechModuleComputerName)
## Add the new macros
$Script:SpeechModuleMacros += $VoiceMacros
## Update the default if they change it, so they only have to do that once.
$Script:SpeechModuleComputerName = $Computer
Update-SpeechCommands
}
function Remove-SpeechCommands {
#.Synopsis
# Remove one or more command from the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
Param([string[]]$CommandText)
foreach($command in $CommandText) { $Script:SpeechModuleMacros.Remove($Command) }
Update-SpeechCommands
}
function Clear-SpeechCommands {
#.Synopsis
# Removes all commands from the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
$Script:SpeechModuleMacros = @{}
## Default value: A way to turn it off
$Script:SpeechModuleMacros.Add("Stop Listening", { Suspend-Listening })
Update-SpeechCommands
}
function Start-Listening {
#.Synopsis
# Sets the SpeechRecognizer to Enabled
$Global:SpeechModuleListener.Enabled = $true
Say "Speech Macros are $($Global:SpeechModuleListener.State)"
Write-Host "Speech Macros are $($Global:SpeechModuleListener.State)"
}
function Suspend-Listening {
#.Synopsis
# Sets the SpeechRecognizer to Disabled
$Global:SpeechModuleListener.Enabled = $false
Say "Speech Macros are disabled"
Write-Host "Speech Macros are disabled"
}
function Suspend-Speech {
$Global:SpeechModuleSpeaker.Pause()
}
function Resume-Speech {
$Global:SpeechModuleSpeaker.Resume()
}
function Out-Speech {
#.Synopsis
# Speaks the input object
#.Description
# Uses the default SpeechSynthesizer settings to speak the string representation of the InputObject
#.Parameter InputObject
# The object to speak
# NOTE: this should almost always be a pre-formatted string,
# most objects don't render to very speakable text.
Param(
[Parameter(Position=0)]
[Object[]]
$Property
,
[Parameter()]
[String]
$Expand
,
[Parameter()]
[Object]
$GroupBy
,
[Parameter(ValueFromPipeline=$true)]
[Alias("IO")]
[PSObject]$InputObject
,
[Parameter()]
[String]
$View
,
[Parameter()]
[Switch]
$Async
)
begin {
if($Async) {
$PSBoundParameters.Remove("Async") | out-null
}
$InputCollection = new-object System.Collections.Generic.List[PSObject]
}
process {
$InputCollection.Add($InputObject)
}
end {
# $PSBoundParameters.Remove("InputObject") | out-null
$PSBoundParameters["InputObject"] = $InputCollection
if(!$Async) {
# Write-Host $($PSBoundParameters | ft |out-string)
# Write-Host $($InputCollection | ft |out-string) -fore Gray
# Format-List @PSBoundParameters | Out-String -Stream | Write-Host -Fore Yellow
Format-List @PSBoundParameters | ForEach-Object {
if($_.GetType().Name -eq "FormatEntryData") { $_; sleep -milli 500} else {$_}
} | Out-String -stream | ForEach-Object {
Write-Host $_
$Global:SpeechModuleSpeaker.Speak($_)
}
} else {
$speech = (Format-List @PSBoundParameters | Out-String -width 1e4) -replace "`r`n`r`n","`r`n`r`n`r`n"
Write-Host $speech
$Global:SpeechModuleSpeaker.SpeakAsync($speech) | Out-Null
}
}
}
function Remove-SpeechXP {
#.Synopis
# Dispose of the SpeechModuleListener and SpeechModuleSpeaker
$Global:SpeechModuleListener.Dispose(); $Global:SpeechModuleListener = $null
$Global:SpeechModuleSpeaker.Dispose(); $Global:SpeechModuleSpeaker = $null
}
set-alias asc Add-SpeechCommands
set-alias rsc Remove-SpeechCommands
set-alias csc Clear-SpeechCommands
set-alias say Out-Speech
set-alias listen Start-Listening
Export-ModuleMember -Function * -Alias * -Variable SpeachModuleListener, SpeechModuleSpeaker
###################################################################################################
## USAGE EXAMPLES:
###################################################################################################
# Add-SpeechCommands @{
# "What time is it?" = { Say "It is $(Get-Date -f "h:mm tt")" }
# "What day is it?" = { Say $(Get-Date -f "dddd, MMMM dd") }
# "What's running?" = {
# $proc = ps | sort ws -desc
# Say $("$($proc.Count) processes, including $($proc[0].name), which is using " +
# "$([int]($proc[0].ws/1mb)) megabytes of memory")
# }
# } -Computer "Laptop" -Verbose
#
# Add-SpeechCommands @{ "Run Notepad" = { & "C:\\Programs\\DevTools\\Notepad++\\notepad++.exe" } }
# Add-SpeechCommands @{ "Check Gee Mail" = { Start-Process "https://mail.google.com" } }
# Add-SpeechCommands @{ "Run Notepad" = { & "C:\\Programs\\DevTools\\Notepad++\\notepad++.exe" } }
|
PowerShellCorpus/PoshCode/84835da8-9f4e-46f7-84f6-64197c8d0f7b.ps1
|
84835da8-9f4e-46f7-84f6-64197c8d0f7b.ps1
|
Hi,
I've tried your excellent -Append feature for export-csv and it works good. I've only have a short question.
Is it possible to make the append to new columns instead of rows? I'd like to combine two csv files as a part of an automation script and then I must get this to work.
Import-csv C:\\Visiolizer\\CI.csv | Select-Object * | Export-Csv C:\\Visiolizer\\Relation.csv -Append
The above work with your source code imported to my $profile, but I'd like to append it to columns. Do you know of any solution?
Would be very thankful for a response
Regards
Erik
|
PowerShellCorpus/PoshCode/Get-User_8.ps1
|
Get-User_8.ps1
|
$script:dse = 'LDAP://my.domain.com'
function script:User-Exists([string]$username)
{
$username = $($username).Trim()
$srch = New-Object DirectoryServices.DirectorySearcher $global:dse
$srch.Filter = "(&(objectClass=user)(sAMAccountName=$username))"
$srch.PageSize = 10000
$srch.SearchScope = "Subtree"
return ($srch.FindOne() -ne $null)
}
function script:Get-User([string]$username)
{
$username = $($username).Trim()
$srch = New-Object DirectoryServices.DirectorySearcher $global:dse
$srch.Filter = "(&(objectClass=user)(sAMAccountName=$username))"
$srch.PageSize = 10000
$srch.SearchScope = "Subtree"
return ( New-Object DirectoryServices.DirectoryEntry $srch.FindOne().Path, $adUsername, $adPassword )
}
function script:Group-Exists([string]$group)
{
$group = $($group).Trim()
$srch = New-Object DirectoryServices.DirectorySearcher $global:dse
$srch.Filter = "(&(objectClass=group)(samAccountName=$group))"
$srch.PageSize = 10000
$srch.SearchScope = "Subtree"
return ($srch.FindOne() -ne $null)
}
function script:Get-Group([string]$group)
{
$group = $($group).Trim()
$srch = New-Object DirectoryServices.DirectorySearcher $global:dse
$srch.Filter = "(&(objectClass=group)(samAccountName=$group))"
$srch.PageSize = 10000
$srch.SearchScope = "Subtree"
return ( New-Object DirectoryServices.DirectoryEntry $srch.FindOne().Path, $adUsername, $adPassword )
}
function script:AddTo-Group([System.DirectoryServices.DirectoryEntry]$object, [System.DirectoryServices.DirectoryEntry]$group)
{
if (-not (Object-IsMemberOf $object $group)) {
try {
$group.Add($object.adsPath)
$group.SetInfo()
$global:status += '<li style="color:green">The Object ' +$($object.Name)+ ' was successfully added to the Group ' +$($group.Name)+'</li>' }
catch {
$global:flagMail = $true
$global:status += '<li style="color:red">The Object ' + $($object.Name) + ' could NOT be added to the Group ' + $($group.Name)+'. Error: Security rights error!</li>' }
}
}
function Global:Object-IsMemberOf([DirectoryServices.DirectoryEntry]$object, [DirectoryServices.DirectoryEntry]$group)
{
$result = $false
foreach($dn in $object.Properties["memberOf"]) {
if ($group.distinguishedName -eq $dn) {
$result = $true }
}
return $result
}
|
PowerShellCorpus/PoshCode/Test-64BitOS.ps1
|
Test-64BitOS.ps1
|
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public static class Win32Api
{
[DllImport("Kernel32.dll", EntryPoint = "IsWow64Process")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out, MarshalAs(UnmanagedType.Bool)] out bool wow64Process
);
}
"@
<#
.SYNOPSIS
Determines whether the architecture of the local operating system is 64-bit.
.DESCRIPTION
The Test-64BitOS function uses the IsWow64Process function to determine whether the process is running under WOW64. It also checks whether the process is 64-bit in this test.
.INPUTS
None
This function does not accept any input.
.OUTPUTS
None
This function does not return any output.
.NOTES
Using this function is more reliable than other methods as the function uses a method provided by the operating system to determine whether the process is running under WOW64.
.EXAMPLE
C:\\PS> Test-64BitOS
This example shows how to use the Test-64BitOS function.
.LINK
#>
function Test-64BitOS
{
return (Test-64BitProcess) -or (Test-Wow64)
}
function Test-64BitProcess
{
return [IntPtr]::Size -eq 8
}
function Test-Wow64
{
if ([Environment]::OSVersion.Version.Major -eq 5 -and
[Environment]::OSVersion.Version.Major -ge 1 -or
[Environment]::OSVersion.Version.Major -ge 6)
{
$process = [System.Diagnostics.Process]::GetCurrentProcess()
$wow64Process = $false
if (![Win32Api]::IsWow64Process($process.Handle, [ref]$wow64Process))
{
return $false
}
return $wow64Process
}
else
{
return $false
}
}
Test-64BitOS
|
PowerShellCorpus/PoshCode/AD-GroupMembers_v1.ps1
|
AD-GroupMembers_v1.ps1
|
function AD-GroupMembers() {
param (
$Domen,
$Group,
$User
)
if ($User){$Connection = Get-Credential -Credential $user}
if($Connection){$Member = Get-QADGroupMember -Service $Domen -Identity $Group -Credential $Connection -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-Table Name,NTAccountName,Sid,AccountIsDisabled -AutoSize}
else{$Member = Get-QADGroupMember -Service $Domen -Identity $Group -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-Table Name,NTAccountName,Sid,AccountIsDisabled -AutoSize}
$Member
}
|
PowerShellCorpus/PoshCode/PowerSmug - Sync Smugmug.ps1
|
PowerSmug - Sync Smugmug.ps1
|
# PowerSmug photo sync script v1.0
# This PowerShell script will syncronize a folder of images with a users SmugMug account
# Please set the appropriate variables in the User Defined Variables region
# For more information visit
#
# Images are uploaded to a gallery with the same name as the folder they are contained in.
# All folders below the Photo Directory path and the images they contain will be uploaded to SmugMug
# Folders that end in _ are ignored, so if you don't want to sync a folder with SmugMug, just add an underscore at the end
#
# Copyright 2008 Shell Tools, LLC
#Region User Defined Variables
$ApiKey = 'uVUvCbXP3f6MgO9wIRJn21YCIgEidVly'
$EmailAddress = '[SmugMug Email]'
$Password = '[SmugMug Password]'
$PhotoDirectory = '[Path To Photos]'
$filesToInclude = @('*.jpg','*.png','*.tif','*.cr2')
$worldSearchable = 1
$smugSearchable = 1
# Professional Accounts Only
$watermark=0
$watermarkId=0
#Email Variables
$smtpServer = '[SMTP Server]'
$smtpUser = '[SMTP User]'
$smtpPassword = '[SMTP Password]'
$smtpFrom = 'PowerSmug@shelltools.net'
#EndRegion
#Region Global Variables
$baseUrl = 'http://api.smugmug.com/hack/rest/1.2.0/'
$userAgent = 'PowerSmug v1.0'
$logFile = 'PowerSmug.log'
$script:SessionId = $null
$script:startStringState = $false
$script:valueState = $false
$script:arrayState = $false
$script:saveArrayState = $false
$script:datFileDirty = $false
$script:datFile = @()
$script:albumList = $null
$script:imageList = $null
#EndRegion
#region Helper Functions
function SendEmail([string] $to, [string] $subject, [string] $msg)
{
$smtpMail = new-Object System.Net.Mail.SmtpClient $smtpServer
$smtpMail.DeliveryMethod = [System.Net.Mail.SmtpDeliveryMethod]'Network'
$smtpMail.Credentials = new-Object System.Net.NetworkCredential $smtpUser, $smtpPassword
$smtpMail.Send($smtpFrom, $to, $subject, $msg)
}
function Get-MD5([System.IO.FileInfo] $file = $(Throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
# This Get-MD5 function sourced from:
# http://blogs.msdn.com/powershell/archive/2006/04/25/583225.aspx
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null) { $stream.Close(); }
break;
}
# Convert the MD5 hash to Hex
$hashByteArray | foreach { $result += $_.ToString("X2") }
return $result
}
function SendWebRequest([string]$method, $queryParams, $ssl = $false)
{
$url = $baseUrl
if ($ssl -eq $true) {
$url = $url.Replace("http", "https")
}
$url += "?method=$method"
foreach ($key in $queryParams.Keys) {
$url += "&$key=" + $queryParams[$key]
}
$wc = New-Object Net.WebClient
$wc.Headers.Add("user-agent", $userAgent)
[xml]$webResult = $wc.DownloadString($url)
CheckResponseForError $webResult
return $webResult.rsp
}
# Adds image information to our data file
function AddFile ([System.IO.FileInfo]$file, $smugId) {
$a = 1 | Select-Object Name, SmugId, LastModifiedTime;
$a.Name = $file.Name
$a.SmugId = $smugId
$a.LastModifiedTime = $file.LastWriteTimeUtc.ToString()
$script:datFile += $a
# $script:datFileDirty = $true
#we are now saving the file after each upload to prevent duplicates when there is a failure
AppendDataFile $datFilePath $a
}
# writes the data file to the local directory
# each directory will have a data file with information for images contained in it
function SaveDataFile($filePath, $clearFile=$true)
{
if ($script:datFileDirty -eq $false) { $script:datFile = @(); return }
[System.IO.File]::Delete($filePath)
$sortedFile = $script:datFile | sort-Object -property Name
$sortedFile | Export-Csv $filePath
$script:datFileDirty = $false
# mark the file as hidden
ls $filePath | foreach { $_.Attributes = $_.Attributes -bor [System.IO.FileAttributes]::Hidden }
if ($clearFile -eq $true) {
# clear the variable
$script:datFile = @()
}
}
# appends a new row to the data file
function AppendDataFile($filePath, $record)
{
if (test-Path $datFilePath) {
$newLine = [System.String]::Format('{0},{1},"{2}"', $a.Name, $a.SmugId, $a.LastModifiedTime)
Add-Content $filePath $newLine
}
else
{
$script:datFileDirty = $true
SaveDataFile $filePath $false
}
}
# ensure our web request was successful
function CheckResponseForError($xmlResponse)
{
if ($xmlResponse.rsp.stat -eq 'fail') {
throw $webResult.rsp.err.msg
}
}
#endregion
#region Login/Logout
function Login()
{
if ($script:SessionId -ne $null) { return }
$ht = @{APIKey=$ApiKey;EmailAddress=$EmailAddress;Password=$Password}
$loginResult = SendWebRequest "smugmug.login.withPassword" $ht $true
if ($loginResult.stat -eq "ok") {
$script:SessionId = $loginResult.Login.Session.id
}
else {
Throw "Error on login: " + $loginResult.Message
}
}
function Logout()
{
if ($script:SessionId -eq $null) { return }
$ht = @{SessionID=$script:SessionId}
$logoutResult = SendWebRequest "smugmug.logout" $ht
}
#endregion
#region Images
# this method is only needed if we cannot find the PowerSmug.dat file.
# preventing us from uploading duplicate images
function GetImage($name, $album)
{
Login
$image = $script:imageList.Images | Where-Object { $_.FileName -eq $name }
if ($image -ne $null) { return $image }
# we are using heavy because we need the file name
$ht = @{SessionID=$script:SessionId;AlbumID=$album.id;Heavy=1;AlbumKey=$album.Key}
[xml]$script:imageList = SendWebRequest "smugmug.images.get" $ht
return $script:imageList.Images.Image | Where-Object { $_.FileName -eq $name }
}
function UploadFile($file, $albumName)
{
$album = GetAlbum $albumName
# $image = GetImage $file.Name $album
# if ($image -ne $null) { return $image.id }
$url = "http://upload.smugmug.com/" + $file.Name
$wc = New-Object Net.WebClient
$hash = Get-MD5 $file
$wc.Headers.Add("user-agent", $userAgent)
$wc.Headers.Add("ContentMd5", $hash)
$wc.Headers.Add("X-Smug-FileName", $file.Name)
$wc.Headers.Add("X-Smug-AlbumID", $album.id)
$wc.Headers.Add("X-Smug-SessionID", $script:SessionId)
$wc.Headers.Add("X-Smug-Version", "1.2.0")
$wc.Headers.Add("X-Smug-ResponseType", "REST")
$webResult = $wc.UploadFile($url, "PUT", $file.FullName)
[xml]$webResult = [System.Text.Encoding]::ASCII.GetString($webResult)
CheckResponseForError $webResult
return $webResult.rsp.Image.id
}
function UploadExistingFile($file, $id)
{
Login
$url = "http://upload.smugmug.com/" + $file.Name
$wc = New-Object Net.WebClient
$hash = Get-MD5 $file
$wc.Headers.Add("user-agent", $userAgent)
$wc.Headers.Add("ContentMd5", $hash)
$wc.Headers.Add("X-Smug-FileName", $file.Name)
$wc.Headers.Add("X-Smug-ImageID", $id)
$wc.Headers.Add("X-Smug-SessionID", $script:SessionId)
$wc.Headers.Add("X-Smug-Version", "1.2.0")
$wc.Headers.Add("X-Smug-ResponseType", "REST")
$webResult = $wc.UploadFile($url, "PUT", $file.FullName)
[xml]$webResult = [System.Text.Encoding]::ASCII.GetString($webResult)
CheckResponseForError $webResult
return $webResult.rsp
}
#endregion
#region Album
function GetAlbumList($forceRefresh=$false) {
Login
if ($forceRefresh -eq $false) {
if ($script:albumList -ne $null) { return }
}
$ht = @{SessionID=$script:SessionId}
$script:albumList = SendWebRequest "smugmug.albums.get" $ht
}
function GetAlbum($name)
{
#before we create an album ensure it doesn't already exist
GetAlbumList
$album = $script:albumList.Albums.Album | Where-Object { $_.Title -eq $name }
if ($album -ne $null) { return $album }
Write-Host "Creating album: $name"
$ht = @{SessionID=$script:SessionId;Title=$name;CategoryID=0;Public=0;
X2Larges=0;X3Larges=0;Originals=0;Watermarking=$watermark;
WatermarkID=$watermarkId;WorldSearchable=$worldSearchable;SmugSearchable=$smugSearchable}
$result = SendWebRequest "smugmug.albums.create" $ht
# be sure we refresh the album list after creation
GetAlbumList $true
return $result.Album
}
#endregion
#region Process File
function ProcessFile([System.IO.FileInfo]$file, $albumName)
{
$photoObject = $script:datFile | Where-Object { $_.Name -eq $file.Name }
if ($photoObject -ne $null) {
if ($photoObject.LastModifiedTime -ne $file.LastWriteTimeUtc.ToString()) {
# file has been modified, so re-upload the file
write-Host "Updating existing file: " $file.FullName
UploadExistingFile $file $photoObject.SmugId
$photoObject.LastModifiedTime = $file.LastWriteTimeUtc.ToString()
# mark the dat file as dirty so it will be saved after processing this folder
$script:datFileDirty = $true
}
}
else {
#file doesn't exist in local file, upload to SmugMug
write-Host "Uploading new file: " $file.FullName
$id = UploadFile $file $albumName
AddFile $file $id
}
}
#endregion
#region Main Script
# this section will look through all sub-directories of $PhotoDirectory and upload the images to SmugMug
Get-ChildItem -recurse $PhotoDirectory | Where-Object { $_.Attributes -band [System.IO.FileAttributes]::Directory } | foreach {
# don't process folders that end in _
if ($_.FullName.EndsWith("_") -eq $false) {
$datFilePath = $_.FullName + "\\PowerSmug.dat"
if (test-Path $datFilePath) {
# casting as array to ensure we have an array returned
[array]$script:datFile = import-Csv $datFilePath
}
$albumName = $_.FullName.Remove(0, $PhotoDirectory.Length).Trim('\\')
$path = $_.FullName + "\\*"
foreach ($file in get-ChildItem $path -include $filesToInclude) {
ProcessFile $file $albumName
}
SaveDataFile $datFilePath
$script:imageList = $null
}
}
Logout
$date = Get-Date
Write-Host "Script Completed: $date"
trap [Exception] {
$date = Get-Date
$Msg = $date.ToString() + " ; " + $_.Exception.GetType().FullName + " ; " + $_.Exception.Message
Add-Content $logFile $Msg
SendEmail $EmailAddress "PowerSmug Error" $Msg
break
}
#endregion
|
PowerShellCorpus/PoshCode/Parse HTML Tables.ps1
|
Parse HTML Tables.ps1
|
# Parse tables within HTML files and return the rows as PowerShell objects.
# The idea here is similar to (though not nearly as complete as) Perl's HTML::TableParse.
# This function should run anywhere but it's a bit slow because of the COM interface
# it uses. There seem to be a few .NET libraries out there that would make it a lot
# faster but you may not have those installed. Please improve this if you
#
# One other quirk is that this function will only return one table at a time, through
# the tableNumber parameter. If you need to extract multiiple tables you need to make
# multiple calls. This was done because PowerShell seems to make it difficult to make
# arrays of arrays, preferring one big happy array instead. Please improve if you
# know how.
#
# TODO: Make it run faster.
function get-rowInner {
param($inputObject, $unique=0, $trim=0)
$values = @()
foreach ($obj in $inputObject) {
if ($obj.nodeName -eq "TD" -or $obj.nodeName -eq "TH") {
$value = $obj.IHTMLElement_innerText
if ($trim) {
$value = $value.trim()
}
if ($unique) {
if ($values -contains $value) {
$i = 2
while ($values -contains ($value + $i)) {
$i++
}
$values += ($value + $i)
} else {
$values += $value
}
} else {
$values += $value
}
}
}
if ($values.length -gt 0) {
return $values
} else {
return $null
}
}
function get-row {
param($inputObject, $unique=0, $trim=0)
if ($inputObject.nodeName -eq "TR") {
# We are at the row level.
return get-rowInner -inputObject $inputObject.childnodes -unique $unique -trim $trim
} else {
# Rows can be nested inside other tags.
foreach ($node in $inputObject.childnodes) {
$row = get-row -inputObject $node -unique $unique -trim $trim
if ($row -ne $null) {
return $row
}
}
}
}
function get-table {
param($inputObjects)
# We treat the first row as column headings.
$headings = $null
$rows = @()
foreach ($obj in $inputObjects) {
if ($headings -eq $null) {
# The first row will be the headings.
$headings = get-row -inputObject $obj -unique 1 -trim 1
continue
}
$row = get-row -inputObject $obj
if ($row -ne $null -and $row.length -eq $headings.length) {
$rowObject = new-object psobject
for ($i = 0; $i -lt $headings.length; $i++) {
$value = $row[$i]
if ($value -eq $null) {
$value = ""
}
$rowObject | add-member -type noteproperty -name $headings[$i] -value $value
}
$rows += $rowObject
}
}
return $rows
}
function Parse-HtmlTableRecursive {
param($inputObjects)
foreach ($_ in $inputObjects) {
if ($_.nodeName -eq "TBODY") {
if (--$global:htmlParseCount -eq 0) {
return get-table -inputObjects $_.childnodes
}
}
if ($_.childnodes -ne $null) {
$table = Parse-HtmlTableRecursive -inputObjects $_.childnodes
if ($table) {
return $table
}
}
}
return $null
}
function Parse-HtmlTable {
param($url, $tableNumber=1)
$client = new-object net.webclient
$htmltext = $client.downloadstring($url)
# For testing local files
#$temp = gc $url
#$htmltext = ''
#for ($i = 0; $i -lt $temp.length; $i++) {
# $htmltext += $temp[$i]
#}
$global:htmlParseCount = $tableNumber
$h = new-object -com "HTMLFILE"
$h.IHTMLDocument2_write($htmltext)
$ret = Parse-HtmlTableRecursive -inputObject $h.body
remove-variable -scope global htmlParseCount
return $ret
}
# Example: Get the 250 most common words in the English language.
# Parse-HtmlTable -url http://esl.about.com/library/vocabulary/bl1000_list1.htm
# Parse-HtmlTable -url http://esl.about.com/library/vocabulary/bl1000_list1.htm | select Word, Word2
|
PowerShellCorpus/PoshCode/Get-EwsEmail.ps1
|
Get-EwsEmail.ps1
|
$ewsPath = "C:\\Program Files\\Microsoft\\Exchange\\Web Services\\1.1\\Microsoft.Exchange.WebServices.dll"
Add-Type -Path $ewsPath
$ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2007_SP1"
$cred = (Get-Credential).GetNetworkCredential()
$ews.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $cred.UserName, $cred.Password, $cred.Domain
$ews.AutodiscoverUrl( ( Read-Host "Enter mailbox (email address)" ) )
$results = $ews.FindItems(
"Inbox",
( New-Object Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList 10 )
)
$results.Items | ForEach-Object { $_.Subject }
|
PowerShellCorpus/PoshCode/Get-GroupMembership_3.ps1
|
Get-GroupMembership_3.ps1
|
## Get-DistinguishedName -- look up a DN from a user's (login) name
function Get-DistinguishedName {
Param($UserName)
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))"
$s = $ads.FindOne()
return $s.GetDirectoryEntry().DistinguishedName
}
## Get-GroupMembership -- Get AD group membership recursively
function Get-GroupMembership {
Param($DNName,[int]$RecurseLimit=-1)
$groups = ([adsi]"LDAP://$DNName").MemberOf
if ($groups -and $RecurseLimit) {
Foreach ($gr in $groups) {
$groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) |
? {$groups -notcontains $_})
}
}
return $groups
}
## Usage:
#################################################################################
## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul)
## # To turn recursion off:
## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0
|
PowerShellCorpus/PoshCode/Get-EnumValues.ps1
|
Get-EnumValues.ps1
|
function Get-EnumValues ( $EnumType ) {
# Code somewhat stolen from Joel here: http://huddledmasses.org/ideas-for-writing-composable-powershell-scripts/
Begin {
$listItems = @()
}
Process {
if( $_ -is [type] -and $_.IsEnum ) {
$listItems+= [Enum]::GetValues($_)
}
elseif( $_.GetType().IsEnum ) {
$listItems += [Enum]::GetValues($_.GetType())
}
else {
throw "Input object must be an enumerator type or derived from one."
}
}
End {
Write-Output $listItems
}
}
|
PowerShellCorpus/PoshCode/test_1.ps1
|
test_1.ps1
|
[CmdletBinding()]
param()
"This file is in the $PSScriptRoot folder."
# SIG # Begin signature block
# MIIPGwYJKoZIhvcNAQcCoIIPDDCCDwgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUtq5NTq7Q77yPgrtRePzRWHVn
# THugggzzMIIEBzCCAu+gAwIBAgILAQAAAAABHkZAnTYwDQYJKoZIhvcNAQEFBQAw
# YzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExFjAUBgNV
# BAsTDU9iamVjdFNpZ24gQ0ExITAfBgNVBAMTGEdsb2JhbFNpZ24gT2JqZWN0U2ln
# biBDQTAeFw0wODEyMTcxNzQ4MDJaFw0xMTEyMTcxNzQ4MDJaMGExCzAJBgNVBAYT
# AlVTMRcwFQYDVQQKEw5RdWVzdCBTb2Z0d2FyZTEXMBUGA1UEAxMOUXVlc3QgU29m
# dHdhcmUxIDAeBgkqhkiG9w0BCQEWEXN1cHBvcnRAcXVlc3QuY29tMIGfMA0GCSqG
# SIb3DQEBAQUAA4GNADCBiQKBgQDWbNraEqKKpmdoXWweG4VFLswQar21iEXsAVsl
# G9O+EJmT2zEr3a2EoEXINI7Mlq4Htm2P7UfBDOmpttT3gSxHT0k5/y8H7FAosLFo
# E/liPCGMnNXL7V3p+tVZg3WhXE9dEEwbsGcWB9GQ522yD9CfVSqfUQ1KjPKNO6Hm
# J25TLQIDAQABo4IBQDCCATwwHwYDVR0jBBgwFoAU0lvzSyZLpbDnXf1Wf/bxLjhO
# U6AwTgYIKwYBBQUHAQEEQjBAMD4GCCsGAQUFBzAChjJodHRwOi8vc2VjdXJlLmds
# b2JhbHNpZ24ubmV0L2NhY2VydC9PYmplY3RTaWduLmNydDA5BgNVHR8EMjAwMC6g
# LKAqhihodHRwOi8vY3JsLmdsb2JhbHNpZ24ubmV0L09iamVjdFNpZ24uY3JsMAkG
# A1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMEsG
# A1UdIAREMEIwQAYJKwYBBAGgMgEyMDMwMQYIKwYBBQUHAgEWJWh0dHA6Ly93d3cu
# Z2xvYmFsc2lnbi5uZXQvcmVwb3NpdG9yeS8wEQYJYIZIAYb4QgEBBAQDAgQQMA0G
# CSqGSIb3DQEBBQUAA4IBAQAb2FS5B6R10Mn+nN+qj2niHMoGR4pxWy6cR5NQw2D3
# RfOB05hEUk8IPtP6BdetOzpjbEWYsk0b/aVCyND/fZwEE33Nl1tf4TGEV8RX3/DS
# BvDcf899iQJG+n1VmVNp8i3gwkK39mmC49CCCClZp1JyDuNA3J4cSDofpzdYc7w8
# yIpwomn0u4zU8pf0GPLoXaTytt0QDIm7SYiIBycQBz8rCgoFlVPWCdPeuTCBOA2V
# fDaGpP9lx/wnLggPNsrMv6BiYMI1qO7ADOHNoDTmhlMvCEVXWx1zkxIlUmcwlUuk
# 07WOuGLmDo6joSZ7Mz+QTyfOhduZOU8mM4Cm4BO9R0WXMIIEDTCCAvWgAwIBAgIL
# BAAAAAABI54PrLMwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUxGTAXBgNV
# BAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMT
# Ekdsb2JhbFNpZ24gUm9vdCBDQTAeFw05OTAxMjgxMzAwMDBaFw0xNzAxMjcxMjAw
# MDBaMIGBMQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xvYmFsU2lnbiBudi1zYTEl
# MCMGA1UECxMcUHJpbWFyeSBPYmplY3QgUHVibGlzaGluZyBDQTEwMC4GA1UEAxMn
# R2xvYmFsU2lnbiBQcmltYXJ5IE9iamVjdCBQdWJsaXNoaW5nIENBMIIBIjANBgkq
# hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAopt1KqcTuglxJBjfoQZiKRKe3J51c+jf
# VldplhNWT/LIvAFY7SaGcgtg9RnFVQNXm7kQyaHUdED/bADo5lM3/rfaeT64Ujjp
# gSyfDjNSps1wzkpdYvTRZ168l0oHyrzdjUexzfFlW4UBsEtr3s2OLvVQ6KOcnSaY
# azZjQQNwRPBf4iV1eVB9X6EGokYMVZVHFNORRoZomecn9JTsmkFR95bUeozhRJdo
# cQPYWG+9tBBC7g1mdUaLRJbSMAASB2P3RJsBcMpWb5xYlyonF4sucVJtRqunKw9/
# FkhkyFL6BhcAB3TXRbMM9XiVc+gK7sTgcoweEaoeu17O+bQA7nO9zQIDAQABo4Gu
# MIGrMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQV
# UXkafAxZ+drN2MQ6E5rJeC1/TTAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js
# Lmdsb2JhbHNpZ24ubmV0L1Jvb3QuY3JsMBMGA1UdJQQMMAoGCCsGAQUFBwMDMB8G
# A1UdIwQYMBaAFGB7ZhpFDZfKiVAvfQTNNKj//P1LMA0GCSqGSIb3DQEBBQUAA4IB
# AQC1eKaifAS3f8l/fWq8cfopMGDC9GIe/n9DHptu4rIfcwuFdlt99U5JBi/U+reR
# QO/tb42OE4NUxSoCPQqk3JkLer13L8xAwY/zxIxOcroQfOb/ZCvHzmyn/NeafI5G
# jQGDTUI725w/nzJhV9cXsLM2ZvCz/URvgTexlE6nViWJ9YrWbRFiYnlcQpACGNOc
# I/wI6GRFuS1+gFtOr8OKKZKDeB+RQTSvhcX9B5lOLFz+x/0XuyUlMU1ytbUpS0ia
# N28TxxFOSkUefi8xnKvoUq/WZ5c0iF8OJ2pmUtFax6wwLCA43Sv/OuvOEEWConsb
# oSBzVpsqk+YEUQZsG9wviZSTMIIE0zCCA7ugAwIBAgILBAAAAAABI54PryQwDQYJ
# KoZIhvcNAQEFBQAwgYExCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWdu
# IG52LXNhMSUwIwYDVQQLExxQcmltYXJ5IE9iamVjdCBQdWJsaXNoaW5nIENBMTAw
# LgYDVQQDEydHbG9iYWxTaWduIFByaW1hcnkgT2JqZWN0IFB1Ymxpc2hpbmcgQ0Ew
# HhcNMDQwMTIyMTAwMDAwWhcNMTcwMTI3MTAwMDAwWjBjMQswCQYDVQQGEwJCRTEZ
# MBcGA1UEChMQR2xvYmFsU2lnbiBudi1zYTEWMBQGA1UECxMNT2JqZWN0U2lnbiBD
# QTEhMB8GA1UEAxMYR2xvYmFsU2lnbiBPYmplY3RTaWduIENBMIIBIjANBgkqhkiG
# 9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsLHygABwzuzDjLSX7cYJjCZvid9nWYHP3hQT
# TMKxReJTdUH6BzZvuhFwKJR8bXK9BxUlZToJ/4Xc+nteN4c45MdLCICYnorNWAkC
# wMMBSZZYiIkmWfVtxrnB+xgl7dhiTsoKbF1w787TmykLCcb27rYW1DxUjsxd4K/b
# 3SMJMnsygRZiCgbLes80IbZvNraxzsuaKTVAPp1YfP+tgpj6uNWJyjXdy81XBsub
# 5L+UqICYX3eW8Lbnq3R5QCGmY+nQB5G9hTi0rpasof8Uc9qlRbhNhs4qPO/U3ygO
# damoiBPC5Hxgk/IlzAOEl+ZOtp8t1rWLNDyr1Tg6yD3EsfmUzQIDAQABo4IBZzCC
# AWMwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYE
# FNJb80smS6Ww5139Vn/28S44TlOgMEoGA1UdIARDMEEwPwYJKwYBBAGgMgEyMDIw
# MAYIKwYBBQUHAgEWJGh0dHA6Ly93d3cuZ2xvYmFsc2lnbi5uZXQvcmVwb3NpdG9y
# eTA5BgNVHR8EMjAwMC6gLKAqhihodHRwOi8vY3JsLmdsb2JhbHNpZ24ubmV0L3By
# aW1vYmplY3QuY3JsME4GCCsGAQUFBwEBBEIwQDA+BggrBgEFBQcwAoYyaHR0cDov
# L3NlY3VyZS5nbG9iYWxzaWduLm5ldC9jYWNlcnQvUHJpbU9iamVjdC5jcnQwEQYJ
# YIZIAYb4QgEBBAQDAgABMBMGA1UdJQQMMAoGCCsGAQUFBwMDMB8GA1UdIwQYMBaA
# FBVReRp8DFn52s3YxDoTmsl4LX9NMA0GCSqGSIb3DQEBBQUAA4IBAQAeavNt9I6p
# Iv5wCGUuoV2rMzDdbHj6S+qtxY3sEHpqxViXOWuS85HiDKcoHNFddo6LB3wTb63E
# NkOzwbwxWc8YONijO87/ymdYv+DxrGE+ojsevAJbQaxEa/Um8+1eqGX2ymWmP8r1
# d+ulhipYKVb4vhYQQOnS/FcsY2E3ZiU5IC4HA6A2AyWUvXzrftOjwsV2FnUwkrn/
# dkE1IWjRDl5cjsMDYOaAQPzAXaJUbm6SZ6eBEoeioyvbt03/5NXH5QXm1fGu/M1m
# GCHzPkfJ5ZVCYSydJoCyD6g9DsmneN9udIwsRvZy6TxkayhVxEtkM8t4VBM48NVx
# BtQ+DQo1DuCzMYIBkjCCAY4CAQEwcjBjMQswCQYDVQQGEwJCRTEZMBcGA1UEChMQ
# R2xvYmFsU2lnbiBudi1zYTEWMBQGA1UECxMNT2JqZWN0U2lnbiBDQTEhMB8GA1UE
# AxMYR2xvYmFsU2lnbiBPYmplY3RTaWduIENBAgsBAAAAAAEeRkCdNjAJBgUrDgMC
# GgUAoHgwGAYKKwYBBAGCNwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYK
# KwYBBAGCNwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG
# 9w0BCQQxFgQUoCdkwMl0ES8CZsg17ivyqxTyq3AwDQYJKoZIhvcNAQEBBQAEgYDD
# fnDc8c/yFATC3FIr+g5NtOSXGZt8VNpRxdg6dQQlPnWxqZKs4mxzZpwwP1Q/dcEA
# 5A2arDbXk+gT4FTtq0hbWF1QxzCC9ThiMyE7pkcge8/v/5eHlGetUij08qyrYne+
# KQ0yFUr4uCM+FDZzLX7L6bfuDpF2mYa8+eGpwjm19w==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/new.ps1
|
new.ps1
|
$Shell = New-Object -com shell.application
$NetCons = $Shell.Namespace(0x31)
$NetCons.Items() |
where {$_.Name -like 'Local Area Connection*'} |
foreach{$AdapName=$_.Name; get-WmiObject -class Win32_NetworkAdapter |
where-Object {$_.NetConnectionID -eq $AdapName} |
foreach {$MAC=$_.MacAddress}
$_.Name=$MAC.replace(':','.')
}
|
PowerShellCorpus/PoshCode/Prevent-Screensaver_1.ps1
|
Prevent-Screensaver_1.ps1
|
#########################################################
# Prevent-Screensaver
#########################################################
# This script "presses" a keyboard key every minute
# for specified number of minutes which makes
# Windows "think" you are at your desktop
# so the screensaver does not start and the desktop
# does not get locked.
#########################################################
# Usage:
# & c:\\filepath\\Prevent-Screensaver.ps1 -Minutes 120
# Makes the script press "." for 120 minutes.
# Start notepad or another app and put focus there
# to see the dots appear and prevent beeping
########################################################
# (c) Dmitry Sotnikov
# http://dmitrysotnikov.wordpress.com
########################################################
param($minutes = 60)
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 60
$myshell.sendkeys(".")
}
|
PowerShellCorpus/PoshCode/Get-Packet.ps1
|
Get-Packet.ps1
|
#
# get-packet.ps1
#
# Receives and displays all incoming IP packets. NIC driver must support promiscuous mode.
#
# Usage: get-packet.ps1 [-LocalIP [<String>]] [-Protocol [<String>]] [[-Seconds] [<Int32>]] [-ResolveHosts] [-Statistics] [-Silent]
#
# Author: Robbie Foust (rfoust@duke.edu)
# Date: Nov 19, 2007
#
# Revised: Dec 30, 2008
# - Added Version field
# - Added support for resolving IPs (uses hashtable cache for improved performance)
# - Flags now stored in an array
# - ESC key will stop script cleanly
# - Calculates stats when sniffing is finished with -Statistics
# - Can suppress packet output using -Silent
#
# Stats logic obtained from Jeffery Hicks's analyze-packet script
# (http://blog.sapien.com/index.php/2008/08/14/analyze-packet-reloaded/)
#
param([string]$LocalIP = "NotSpecified", [string]$Protocol = "all", [int]$Seconds = 0, [switch]$ResolveHosts, [switch]$Statistics, [switch]$Silent)
$starttime = get-date
$byteIn = new-object byte[] 4
$byteOut = new-object byte[] 4
$byteData = new-object byte[] 4096 # size of data
$byteIn[0] = 1 # this enables promiscuous mode (ReceiveAll)
$byteIn[1-3] = 0
$byteOut[0-3] = 0
# TCP Control Bits
$TCPFIN = [byte]0x01
$TCPSYN = [byte]0x02
$TCPRST = [byte]0x04
$TCPPSH = [byte]0x08
$TCPACK = [byte]0x10
$TCPURG = [byte]0x20
# Takes a 2 byte array, switches it from big endian to little endian, and converts it to uint16.
function NetworkToHostUInt16 ($value)
{
[Array]::Reverse($value)
[BitConverter]::ToUInt16($value,0)
}
# Takes a 4 byte array, switches it from big endian to little endian, and converts it to uint32.
function NetworkToHostUInt32 ($value)
{
[Array]::Reverse($value)
[BitConverter]::ToUInt32($value,0)
}
# Takes a byte array, switches it from big endian to little endian, and converts it to a string.
function ByteToString ($value)
{
$AsciiEncoding = new-object system.text.asciiencoding
$AsciiEncoding.GetString($value)
}
$hostcache = @{} # hashtable to cache hostnames to speed up ResolveIP()
function ResolveIP ($ip)
{
if ($data = $hostcache."$($ip.IPAddressToString)")
{
if ($ip.IPAddressToString -eq $data)
{
[system.net.ipaddress]$ip
}
else
{
$data
}
}
else
{
$null,$null,$null,$data = nslookup $ip.IPAddressToString 2>$null
$data = $data -match "Name:"
if ($data -match "Name:")
{
$data = $data[0] -replace "Name:\\s+",""
$hostcache."$($ip.IPAddressToString)" = "$data"
$data
}
else
{
$hostcache."$($ip.IPAddressToString)" = "$($ip.IPAddressToString)"
$ip
}
}
}
# try to figure out which IP address to bind to by looking at the default route
if ($LocalIP -eq "NotSpecified") {
route print 0* | % {
if ($_ -match "\\s{2,}0\\.0\\.0\\.0") {
$null,$null,$null,$LocalIP,$null = [regex]::replace($_.trimstart(" "),"\\s{2,}",",").split(",")
}
}
}
write-host "Using IPv4 Address: $LocalIP"
write-host
# open a socket -- Type should be Raw, and ProtocolType has to be IP for promiscuous mode, otherwise iocontrol will fail below.
$socket = new-object system.net.sockets.socket([Net.Sockets.AddressFamily]::InterNetwork,[Net.Sockets.SocketType]::Raw,[Net.Sockets.ProtocolType]::IP)
# this tells the socket to include the IP header
$socket.setsocketoption("IP","HeaderIncluded",$true)
# make the buffer big or we'll drop packets.
$socket.ReceiveBufferSize = 819200
$ipendpoint = new-object system.net.ipendpoint([net.ipaddress]"$localIP",0)
$socket.bind($ipendpoint)
# this enables promiscuous mode
[void]$socket.iocontrol([net.sockets.iocontrolcode]::ReceiveAll,$byteIn,$byteOut)
write-host "Press ESC to stop the packet sniffer ..." -fore yellow
$escKey = 27
$running = $true
$packets = @() # this will hold all packets for later analysis
while ($running)
{
# check and see if ESC was pressed
if ($host.ui.RawUi.KeyAvailable)
{
$key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp,IncludeKeyDown")
if ($key.VirtualKeyCode -eq $ESCkey)
{
$running = $false
}
}
if ($Seconds -ne 0 -and ($([DateTime]::Now) -gt $starttime.addseconds($Seconds))) # if user-specified timeout has expired
{
exit
}
if (-not $socket.Available) # see if any packets are in the queue
{
start-sleep -milliseconds 500
continue
}
# receive data
$rcv = $socket.receive($byteData,0,$byteData.length,[net.sockets.socketflags]::None)
# decode the header (see RFC 791 or this will make no sense)
$MemoryStream = new-object System.IO.MemoryStream($byteData,0,$rcv)
$BinaryReader = new-object System.IO.BinaryReader($MemoryStream)
# First 8 bits of IP header contain version & header length
$VersionAndHeaderLength = $BinaryReader.ReadByte()
# Next 8 bits contain the TOS (type of service)
$TypeOfService= $BinaryReader.ReadByte()
# total length of header and payload
$TotalLength = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$Identification = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$FlagsAndOffset = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$TTL = $BinaryReader.ReadByte()
$ProtocolNumber = $BinaryReader.ReadByte()
$Checksum = [Net.IPAddress]::NetworkToHostOrder($BinaryReader.ReadInt16())
$SourceIPAddress = $BinaryReader.ReadUInt32()
$SourceIPAddress = [System.Net.IPAddress]$SourceIPAddress
$DestinationIPAddress = $BinaryReader.ReadUInt32()
$DestinationIPAddress = [System.Net.IPAddress]$DestinationIPAddress
# Get the IP version number from the "left side" of the Byte
$ipVersion = [int]"0x$(('{0:X}' -f $VersionAndHeaderLength)[0])"
# Get the header length by getting right 4 bits (usually will be 5, as in 5 32 bit words)
# multiplying by 4 converts from words to octets which is what TotalLength is measured in
$HeaderLength = [int]"0x$(('{0:X}' -f $VersionAndHeaderLength)[1])" * 4
if ($HeaderLength -gt 20) # if header includes Options (is gt 5 octets long)
{
[void]$BinaryReader.ReadBytes($HeaderLength - 20) # should probably do something with this later
}
$Data = ""
$TCPFlagsString = @() # make this an array
$TCPWindow = ""
$SequenceNumber = ""
switch ($ProtocolNumber) # see http://www.iana.org/assignments/protocol-numbers
{
1 { # ICMP
$protocolDesc = "ICMP"
$sourcePort = [uint16]0
$destPort = [uint16]0
break
}
2 { # IGMP
$protocolDesc = "IGMP"
$sourcePort = [uint16]0
$destPort = [uint16]0
$IGMPType = $BinaryReader.ReadByte()
$IGMPMaxRespTime = $BinaryReader.ReadByte()
$IGMPChecksum = [System.Net.IPAddress]::NetworkToHostOrder($BinaryReader.ReadInt16())
$Data = ByteToString $BinaryReader.ReadBytes($TotalLength - ($HeaderLength - 32))
}
6 { # TCP
$protocolDesc = "TCP"
$sourcePort = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$destPort = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$SequenceNumber = NetworkToHostUInt32 $BinaryReader.ReadBytes(4)
$AckNumber = NetworkToHostUInt32 $BinaryReader.ReadBytes(4)
$TCPHeaderLength = [int]"0x$(('{0:X}' -f $BinaryReader.ReadByte())[0])" * 4 # reads Data Offset + 4 bits of Reserve (ignored)
$TCPFlags = $BinaryReader.ReadByte() # this will also contain 2 bits of Reserve on the left, but we can just ignore them.
switch ($TCPFlags)
{
{ $_ -band $TCPFIN } { $TCPFlagsString += "FIN" }
{ $_ -band $TCPSYN } { $TCPFlagsString += "SYN" }
{ $_ -band $TCPRST } { $TCPFlagsString += "RST" }
{ $_ -band $TCPPSH } { $TCPFlagsString += "PSH" }
{ $_ -band $TCPACK } { $TCPFlagsString += "ACK" }
{ $_ -band $TCPURG } { $TCPFlagsString += "URG" }
}
$TCPWindow = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$TCPChecksum = [System.Net.IPAddress]::NetworkToHostOrder($BinaryReader.ReadInt16())
$TCPUrgentPointer = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
if ($TCPHeaderLength -gt 20) # get to start of data
{
[void]$BinaryReader.ReadBytes($TCPHeaderLength - 20)
}
# if SYN flag is set, sequence number is initial sequence number, and therefore the first
# octet of the data is ISN + 1.
if ($TCPFlags -band $TCPSYN)
{
$ISN = $SequenceNumber
#$SequenceNumber = $BinaryReader.ReadBytes(1)
[void]$BinaryReader.ReadBytes(1)
}
$Data = ByteToString $BinaryReader.ReadBytes($TotalLength - ($HeaderLength + $TCPHeaderLength))
break
}
17 { # UDP
$protocolDesc = "UDP"
$sourcePort = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$destPort = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
$UDPLength = NetworkToHostUInt16 $BinaryReader.ReadBytes(2)
[void]$BinaryReader.ReadBytes(2)
# subtract udp header length (2 octets) and convert octets to bytes.
$Data = ByteToString $BinaryReader.ReadBytes(($UDPLength - 2) * 4)
break
}
default {
$protocolDesc = "Other ($_)"
$sourcePort = 0
$destPort = 0
break
}
}
$BinaryReader.Close()
$memorystream.Close()
if ($ResolveHosts) # resolve IP addresses to hostnames
{
# GetHostEntry is horribly slow on failed lookups, so I'm not using it
# $DestinationHostName = ([System.Net.DNS]::GetHostEntry($DestinationIPAddress.IPAddressToString)).Hostname
# $SourceHostName = ([System.Net.DNS]::GetHostEntry($SourceIPAddress.IPAddressToString)).Hostname
$DestinationHostName = ResolveIP($DestinationIPAddress)
$SourceHostName = ResolveIP($SourceIPAddress)
}
# now throw the stuff we consider important into a psobject
# $ipObject = new-object psobject
if ($Protocol -eq "all" -or $Protocol -eq $protocolDesc)
{
$packet = new-object psobject
$packet | add-member noteproperty Destination $DestinationIPAddress
if ($ResolveHosts) { $packet | add-member noteproperty DestinationHostName $DestinationHostName }
$packet | add-member noteproperty Source $SourceIPAddress
if ($ResolveHosts) { $packet | add-member noteproperty SourceHostName $SourceHostName }
$packet | add-member noteproperty Version $ipVersion
$packet | add-member noteproperty Protocol $protocolDesc
$packet | add-member noteproperty Sequence $SequenceNumber
$packet | add-member noteproperty Window $TCPWindow
$packet | add-member noteproperty DestPort $destPort
$packet | add-member noteproperty SourcePort $sourcePort
$packet | add-member noteproperty Flags $TCPFlagsString
$packet | add-member noteproperty Data $Data
$packet | add-member noteproperty Time (get-date)
$packets += $packet # add this packet to the array
if (-not $Silent)
{
$packet
}
}
}
# calculate statistics
if ($Statistics)
{
$activity = "Analyzing network trace"
# calculate elapsed time
# Using this logic, the beginning time is when the first packet is received,
# not when packet capturing is started. That may or may not be ideal depending
# on what you're trying to measure.
write-progress $activity "Counting packets"
$elapsed = $packets[-1].time - $packets[0].time
#calculate packets per second
write-progress $activity "Calculating elapsed time"
$pps = $packets.count/(($packets[-1].time -$packets[0].time).totalseconds)
$pps="{0:N4}" -f $pps
# Calculating protocol distribution
write-progress $activity "Calculating protocol distribution"
$protocols = $packets | sort protocol | group protocol | sort count -descending | select Count,@{name="Protocol";Expression={$_.name}}
# Calculating source port distribution
write-progress $activity "Calculating source port distribution"
$sourceport = $packets | sort sourceport | group sourceport | sort count -descending | select Count,@{name="Port";Expression={$_.name}}
# Calculating destination distribution
write-progress $activity "Calculating destination distribution"
$destinationlist = $packets | sort Destination | select Destination
# Calculating destination port distribution
write-progress $activity "Calculating destination port distribution"
$destinationport = $packets | sort destport | group destport | sort count -descending | select Count,@{name="Port";Expression={$_.name}}
# Building source list
write-progress $activity "Building source list"
$sourcelist = $packets | sort source | select Source
# Building source IP list
write-progress $activity "Building source IP list"
$ips = $sourcelist | group source | sort count -descending | select Count,@{Name="IP";Expression={$_.Name}}
# Build destination IP list
write-progress $activity "Building destination IP list"
$ipd = $destinationlist | group destination | sort count -descending | select Count,@{Name="IP";Expression={$_.Name}}
# Presenting data
write-progress $activity "Compiling results"
$protocols = $protocols | Select Count,Protocol,@{Name="Percentage";Expression={"{0:P4}" -f ($_.count/$packets.count)}}
$destinationport = $destinationport | select Count,Port,@{Name="Percentage";Expression={"{0:P4}" -f ($_.count/$packets.count)}}
$sourceport = $sourceport | Select Count,Port,@{Name="Percentage";Expression={"{0:P4}" -f ($_.count/$packets.count)}}
if ($ResolveHosts)
{
write-progress $activity "Resolving IPs"
# add hostnames to the new object(s)
foreach ($destination in $ipd)
{
$destination | add-member noteproperty "Host" $(ResolveIP([system.net.ipaddress]$destination.IP))
}
foreach ($source in $ips)
{
$source | add-member noteproperty "Host" $(ResolveIP([system.net.ipaddress]$source.IP))
}
}
write-progress $activity "Compiling results"
$destinations = $ipd | Select Count,IP,Host,@{Name="Percentage";Expression={"{0:P4}" -f ($_.count/$packets.count)}}
$sources = $ips | Select Count,IP,Host,@{Name="Percentage";Expression={"{0:P4}" -f ($_.count/$packets.count)}}
$global:stats = new-object psobject
$stats | add-member noteproperty "TotalPackets" $packets.count
$stats | add-member noteproperty "Elapsedtime" $elapsed
$stats | add-member noteproperty "PacketsPerSec" $pps
$stats | add-member noteproperty "Protocols" $protocols
$stats | add-member noteproperty "Destinations" $destinations
$stats | add-member noteproperty "DestinationPorts" $destinationport
$stats | add-member noteproperty "Sources" $sources
$stats | add-member noteproperty "SourcePorts" $sourceport
write-host
write-host " TotalPackets: " $stats.totalpackets
write-host " ElapsedTime: " $stats.elapsedtime
write-host "PacketsPerSec: " $stats.packetspersec
write-host
write-host "More statistics can be accessed from the global `$stats variable." -fore cyan
}
|
PowerShellCorpus/PoshCode/Download-FreeReflector.p.ps1
|
Download-FreeReflector.p.ps1
|
#Thanks http://27.am/posts/how-to-download-net-reflector-6-for-free
add-type @'
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
namespace LookingGlass
{
젨젨public class RedGateDownloader
젨젨젨젨public static void Download()
젨젨젨젨{
젨젨젨젨젨젨QueryDownloadUrl("http://reflector.red-gate.com/Reflector.version");
젨젨젨젨}
젨젨젨젨static void QueryDownloadUrl(string versionUrl)
젨젨젨젨{
젨젨젨젨젨젨Console.WriteLine("Phase 1: Getting download URL...");
젨젨젨젨젨젨HttpWebRequest request = GetHttpWebRequest(versionUrl);
젨젨젨젨젨젨string downloadUrl = null;
젨젨젨젨젨젨string data;
젨젨젨젨젨젨using (WebResponse response = request.GetResponse())
젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨data = ReadResponse(response);
젨젨젨젨젨젨젨젨foreach (string line in data.Split('\\n'))
젨젨젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨젨젨if (line.StartsWith("http", StringComparison.OrdinalIgnoreCase))
젨젨젨젨젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨젨젨젨젨// If this version number stops working, search for other known .NET Reflector version numbers; Red Gates own forums mention a few
젨젨젨젨젨젨젨젨젨젨젨젨downloadUrl = line.Trim('\\r').Replace("{Client}", "Reflector").Replace("{Version}", "6.1.0.11");
젨젨젨젨젨젨젨젨젨젨젨젨break;
젨젨젨젨젨젨젨젨젨젨}
젨젨젨젨젨젨젨젨}
젨젨젨젨젨젨}
젨젨젨젨젨젨if (downloadUrl == null)
젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨Console.WriteLine("Failed to find download URL. Returned data was:");
젨젨젨젨젨젨젨젨Console.WriteLine(data);
젨젨젨젨젨젨젨젨Console.ReadLine();
젨젨젨젨젨젨}
젨젨젨젨젨젨else
젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨Console.WriteLine("Launching download process... for "+downloadUrl);
젨젨젨젨젨젨젨젨Process.Start(Process.GetCurrentProcess().MainModule.FileName, downloadUrl);
젨젨젨젨젨젨젨젨Console.WriteLine("Phase 1 complete.");
Download(downloadUrl);
젨젨젨젨젨젨}
젨젨젨젨}
젨젨젨젨static void Download(string downloadUrl)
젨젨젨젨{
젨젨젨젨젨젨Console.WriteLine("Phase 2: Downloading...");
젨젨젨젨젨젨HttpWebRequest request = GetHttpWebRequest(downloadUrl);
젨젨젨젨젨젨string path;
젨젨젨젨젨젨using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨path = GetDownloadFilename(response);
젨젨젨젨젨젨젨젨if (response.StatusCode == HttpStatusCode.OK && !string.IsNullOrEmpty(path))
젨젨젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨젨젨Console.WriteLine("Saving to {0}...", path);
젨젨젨젨젨젨젨젨젨젨SaveResponse(response, path);
젨젨젨젨젨젨젨젨젨젨Console.WriteLine("Done!");
젨젨젨젨젨젨젨젨}
젨젨젨젨젨젨젨젨else
젨젨젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨젨젨Console.WriteLine("Download failed; server returned status code {0}. Returned data was:", response.StatusCode);
젨젨젨젨젨젨젨젨젨젨Console.WriteLine(ReadResponse(response));
젨젨젨젨젨젨젨젨젨젨Console.ReadLine();
젨젨젨젨젨젨젨젨}
젨젨젨젨젨젨}
젨젨젨젨}
젨젨젨젨static HttpWebRequest GetHttpWebRequest(string url)
젨젨젨젨{
젨젨젨젨젨젨HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
젨젨젨젨젨젨request.Headers.Add("Cache-Control: no-cache, no-store, max-age=0");
젨젨젨젨젨젨// Emulate the manner in which the headers are handled
젨젨젨젨젨젨FieldInfo usesProxySemantics = typeof(ServicePoint).GetField("m_ProxyServicePoint", BindingFlags.NonPublic | BindingFlags.Instance);
젨젨젨젨젨젨usesProxySemantics.SetValue(request.ServicePoint, true);
젨젨젨젨젨젨return request;
젨젨젨젨}
젨젨젨젨static string GetDownloadFilename(HttpWebResponse response)
젨젨젨젨{
젨젨젨젨젨젨string contentDisposition = response.Headers["content-disposition"];
젨젨젨젨젨젨if (string.IsNullOrEmpty(contentDisposition))
젨젨젨젨젨젨젨젨return null;
젨젨젨젨젨젨string filenameField = "filename=";
젨젨젨젨젨젨int index = contentDisposition.IndexOf(filenameField, StringComparison.CurrentCultureIgnoreCase);
젨젨젨젨젨젨if (index < 0)
젨젨젨젨젨젨젨젨return null;
젨젨젨젨젨젨return contentDisposition.Substring(index + filenameField.Length).Trim('"');
젨젨젨젨}
젨젨젨젨static string ReadResponse(WebResponse response)
젨젨젨젨{
젨젨젨젨젨젨using (Stream netStream = response.GetResponseStream())
젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨using (StreamReader reader = new StreamReader(netStream))
젨젨젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨젨젨return reader.ReadToEnd();
젨젨젨젨젨젨젨젨}
젨젨젨젨젨젨}
젨젨젨젨}
젨젨젨젨static void SaveResponse(WebResponse response, string path)
젨젨젨젨{
젨젨젨젨젨젨byte[] buffer = new byte[4 * 1024];
젨젨젨젨젨젨int bytesRead;
젨젨젨젨젨젨using (Stream netStream = response.GetResponseStream())
젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨if (File.Exists(path))
젨젨젨젨젨젨젨젨젨젨File.Delete(path);
젨젨젨젨젨젨젨젨using (FileStream fileStream = File.Create(path))
젨젨젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨젨젨while ((bytesRead = netStream.Read(buffer, 0, buffer.Length)) > 0)
젨젨젨젨젨젨젨젨젨젨{
젨젨젨젨젨젨젨젨젨젨젨젨Console.Write(".");
젨젨젨젨젨젨젨젨젨젨젨젨fileStream.Write(buffer, 0, bytesRead);
젨젨젨젨젨젨젨젨젨젨}
젨젨젨젨젨젨젨젨}
젨젨젨젨젨젨}
젨젨젨젨젨젨Console.WriteLine();
젨젨젨젨}
젨젨}
}
'@
[LookingGlass.RedGateDownloader]::Download()
|
PowerShellCorpus/PoshCode/Balance-Datastores.ps1
|
Balance-Datastores.ps1
|
#Parameter- Name of the VMware cluster to work in
param($cluster)
Write-Output "`n$(Get-Date)- Script started`n"
# Validate parameter input
$IsClusterNameInvalid = $true
Get-Cluster | % { If ($_.Name -eq $Cluster) {$IsClusterNameInvalid = $false} }
If ($IsClusterNameInvalid) {
Write-Host "Error- Invalid Cluster Name" -Background Yellow -Foreground Red
Write-Host "Valid cluster names for this Virtual Center server."
Write-Host "---------------------------------------------------"
Get-Cluster | Sort
break
}
# Prep
$ScriptDir = "\\\\vmscripthost201\\repo"
. $ScriptDir\\mGet-DataStoreList.ps1
# Get the list of valid datastores and pick the one with the least free space.
$DSTs = mGet-DataStoreList $Cluster
$DSTInfo = $DSTs | Select-Object Name,@{n="CapacityGB";e={[math]::round(($_.CapacityMB/1024))}},@{n="FreeSpaceGB";e={[math]::round(($_.FreeSpaceMB/1024))}},@{n="FreeSpacePercent";e={[math]::round(($_.FreeSpaceMB/$_.CapacityMB*100))}} | Sort-Object FreeSpacePercent
$DSTLeastFree = $DSTInfo | Select-Object -first 1
$DSTMostFree = $DSTInfo | Select-Object -last 1
# Get all the VMs on the datastore with the least free space.
$SourceVMsInitial = Get-VM -Datastore $DSTLeastFree.Name
# Remove any VMs that are in the exclusions text file.
$SourceVMsNotExcludeded = $SourceVMsInitial | ForEach-Object {
$vmtemp = $_.Name
$match = $false
Get-Content $ScriptDir\\StaticInfo\\sVMotion_Exclude.txt | ForEach-Object {
If ($vmtemp -eq $_) { $match = $true }
}
If ($match -eq $false) { $vmtemp }
}
# Remove any VMs with more than 8GB of RAM (takes longer to svMotion, greater chance of failure).
$SourceVMs = $SourceVMsNotExcludeded | Where-Object { $_.MemoryMB -le 8192 }
# Pick the VM
$SourceVMCount = ($SourceVMs | Measure-Object).Count
$SourceVMIndex = [math]::round($SourceVMCount/2)
$SourceVMToMove = $SourceVMs[$SourceVMIndex]
# Output reference info
Get-VM $SourceVMToMove | Format-Table -AutoSize
$DSTLeastFree | Format-Table -AutoSize
$DSTMostFree | Format-Table -AutoSize
Write-Output "`n $(Get-Date)- Moving $($SourceVMToMove) from $(($DSTLeastFree).Name) to $(($DSTMostFree).Name)`n"
# svMotion the VM
Move-VM -VM $SourceVMToMove -Datastore ($DSTMostFree).Name -Confirm:$false
Write-Output "`n$(Get-Date)- Script finished`n"
|
PowerShellCorpus/PoshCode/Check Service_1.ps1
|
Check Service_1.ps1
|
####################################################################################
#PoSH script to check if a server is up and if it is check for a service.
#If the service isn't running, start it and send an email
# JK - 7/2009
#Updated: 07/22/09 by Steven Murawski (http://blog.usepowershell.com)
#Changed the ping result comparison to use the .NET Enum
####################################################################################
$erroractionpreference = "SilentlyContinue"
$i = "testserver" #Server Name
$service = "spooler" #Service to monitor
$ping = new-object System.Net.NetworkInformation.Ping
$rslt = $ping.send($i)
if ($rslt.status –eq [System.Net.NetworkInformation.IPStatus]::Success)
{
$b = get-wmiobject win32_service -computername $i -Filter "Name = '$service'"
If ($b.state -eq "stopped")
{
$b.startservice()
$emailFrom = "services@yourdomain.com"
$emailTo = "you@yourdomain.com"
$subject = "$service Service has restarted on $i"
$body = "The $service service on $i has crashed and been restarted"
$smtpServer = "xx.yourdomain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
}
}
|
PowerShellCorpus/PoshCode/GUI ProductKey.ps1
|
GUI ProductKey.ps1
|
$def = (gci $MyInvocation.MyCommand.Name).Directory
##################################################################################################
$mnuScan_Click= {
$lstView.Items.Clear()
try {
Get-AllData ("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")
Get-AllData (Expand-OfficeKey)
}
catch {}
Measure-Items
}
$mnuSave_Click= {
if ($lstView.Items.Count -ne 0) {
(New-Object Windows.Forms.SaveFileDialog) | % {
$_.FileName = "ProductKey"
$_.Filter = "CSV (*.csv)|*.csv"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$sw = New-Object IO.StreamWriter($_.FileName, [Text.Encoding]::Default)
$sw.WriteLine("ProductName, ProductID, ProductKey")
$lstView.Items | % {
$sw.WriteLine($($_.Text + ', ' + $_.SubItems[1].Text + ', ' + $_.SubItems[2].Text))
}
$sw.Flush()
$sw.Close()
}
}
}#if
}
$mnuFont_Click= {
(New-Object Windows.Forms.FontDialog) | % {
$_.Font = "Lucida Console"
$_.MinSize = 8
$_.MaxSize = 12
$_.ShowEffects = $false
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$lstView.Font = $_.Font
}
}
}
$mnuSBar_Click= {
$toggle =! $mnuSBar.Checked
$mnuSBar.Checked = $toggle
$sbPanel.Visible = $toggle
}
$frmMain_Load= {
Measure-Items
}
##################################################################################################
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$ico = [Drawing.Icon]::ExtractAssociatedIcon(($PSHome + '\\powershell.exe'))
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MenuStrip
$mnuFile = New-Object Windows.Forms.ToolStripMenuItem
$mnuScan = New-Object Windows.Forms.ToolStripMenuItem
$mnuSave = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp1 = New-Object Windows.Forms.ToolStripSeparator
$mnuExit = New-Object Windows.Forms.ToolStripMenuItem
$mnuView = New-Object Windows.Forms.ToolStripMenuItem
$mnuFont = New-Object Windows.Forms.ToolStripMenuItem
$mnuSBar = New-Object Windows.Forms.ToolStripMenuItem
$mnuHelp = New-Object Windows.Forms.ToolStripMenuItem
$mnuInfo = New-Object Windows.Forms.ToolStripMenuItem
$lstView = New-Object Windows.Forms.ListView
$imgList = New-Object Windows.Forms.ImageList
$chPName = New-Object Windows.Forms.ColumnHeader
$chProID = New-Object Windows.Forms.ColumnHeader
$chPrKey = New-Object Windows.Forms.ColumnHeader
$sbPanel = New-Object Windows.Forms.StatusBar
$sbPnl_1 = New-Object Windows.Forms.StatusBarPanel
$sbPnl_2 = New-Object Windows.Forms.StatusBarPanel
#
#mnuMain
#
$mnuMain.Dock = "Top"
$mnuMain.Items.AddRange(@($mnuFile, $mnuView, $mnuHelp))
#
#mnuFile
#
$mnuFile.DropDownItems.AddRange(@($mnuScan, $mnuSave, $mnuEmp1, $mnuExit))
$mnuFile.Text = "&File"
#
#mnuScan
#
$mnuScan.ShortcutKeys = "F5"
$mnuScan.Text = "S&can..."
$mnuScan.Add_Click($mnuScan_Click)
#
#mnuSave
#
$mnuSave.ShortcutKeys = "Control", "S"
$mnuSave.Text = "&Save log"
$mnuSave.Add_Click($mnuSave_Click)
#
#mnuExit
#
$mnuExit.ShortcutKeys = "Control", "X"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click({$frmMain.Close()})
#
#mnuView
#
$mnuView.DropDownItems.AddRange(@($mnuFont, $mnuSBar))
$mnuView.Text = "&View"
#
#mnuFont
#
$mnuFont.Text = "Font..."
$mnuFont.Add_Click($mnuFont_Click)
#
#mnuSBar
#
$mnuSBar.Checked = $true
$mnuSBar.Enabled = $false
$mnuSBar.ShortcutKeys = "Control", "B"
$mnuSbar.Text = "Status &Bar"
$mnuSbar.Add_Click($mnuSBar_Click)
#
#mnuHelp
#
$mnuHelp.DropDownItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#
#mnuInfo
#
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click({frmInfo_Show})
#
#lstView
#
$lstView.AllowColumnReorder = $true
$lstView.Columns.AddRange(@($chPName, $chProID, $chPrKey))
$lstView.Dock = "Bottom"
$lstView.FullRowSelect = $true
$lstView.GridLines = $true
$lstView.Height = 191
$lstView.MultiSelect = $false
$lstView.SmallImageList = $imgList
$lstView.Sorting = "Ascending"
$lstView.View = "Details"
#
#imgList
#
$imgList.Images.Add((Get-Image $img))
#
#chPName
#
$chPName.Text = "Product Name"
$chPName.Width = 183
#
#chProID
#
$chProID.Text = "Product ID"
$chProID.Width = 143
#
#chPrKey
#
$chPrKey.Text = "Product Key"
$chPrKey.Width = 220
#
#sbPanel
#
$sbPanel.Panels.AddRange(@($sbPnl_1, $sbPnl_2))
$sbPanel.SizingGrip = $false
$sbPanel.ShowPanels = $true
#
#sbPnl_1
#
$sbPnl_1.AutoSize = "Contents"
#
#sbPnl_2
#
$sbPnl_2.AutoSize = "Contents"
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(573, 237)
$frmMain.Controls.AddRange(@($mnuMain, $lstView, $sbPanel))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.Icon = $ico
$frmMain.MaximizeBox = $false
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "ProductKey"
$frmMain.Add_Load({Measure-Items})
[void]$frmMain.ShowDialog()
}
##################################################################################################
function frmInfo_Show {
$frmInfo = New-Object Windows.Forms.Form
$pbImage = New-Object Windows.Forms.PictureBox
$lblName = New-Object Windows.Forms.Label
$lblCopy = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#
#pbImage
#
$pbImage.Location = New-Object Drawing.Point(16, 16)
$pbImage.Size = New-Object Drawing.Size(32, 32)
$pbImage.SizeMode = "StretchImage"
#
#lblName
#
$lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 8, [Drawing.FontStyle]::Bold)
$lblName.Location = New-Object Drawing.Point(53, 19)
$lblName.Size = New-Object Drawing.Size(360, 18)
$lblName.Text = "ProductKey v1.15"
#
#lblCopy
#
$lblCopy.Location = New-Object Drawing.Point(67, 37)
$lblCopy.Size = New-Object Drawing.Size(360, 23)
$lblCopy.Text = "(C) 2010-2013 greg zakharov gregzakh@gmail.com"
#
#btnExit
#
$btnExit.Location = New-Object Drawing.Point(135, 67)
$btnExit.Text = "OK"
#
#frmInfo
#
$frmInfo.AcceptButton = $btnExit
$frmInfo.CancelButton = $btnExit
$frmInfo.ClientSize = New-Object Drawing.Size(350, 110)
$frmInfo.ControlBox = $false
$frmInfo.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit))
$frmInfo.ShowInTaskBar = $false
$frmInfo.StartPosition = "CenterScreen"
$frmInfo.Text = "About..."
$frmInfo.Add_Load({$pbImage.Image = $ico.ToBitmap()})
[void]$frmInfo.ShowDialog()
}
##################################################################################################
function Get-ProductKey($reg) {
$map = "BCDFGHJKMPQRTVWXY2346789"
$val = (gp $reg).DigitalProductId[52..66]
$key = ''
for ($i = 24; $i -ge 0; $i--) {
$k = 0
for ($j = 14; $j -ge 0; $j--) {
$k = ($k * 256) -bxor $val[$j]
$val[$j] = [Math]::Floor([double]($k / 24))
$k = $k % 24
}
$key = $map[$k] + $key
if (($i % 5) -eq 0 -and $i -ne 0) {$key = '-' + $key}
}
$key
}
function Expand-OfficeKey {
$src = 'SOFTWARE\\Microsoft\\Office'
$rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($src)
$src += '\\' + $($rk.GetSubKeyNames() -match '(\\d)+.0') + '\\Registration'
$rk.Close()
$rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($src)
$src += '\\' + $($rk.GetSubKeyNames())
$rk.Close()
return $src
}
function Get-AllData($reg) {
$rk = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($reg)
$itm = $lstView.Items.Add(($rk.GetValue("ProductName")), 0)
$itm.SubItems.Add(($rk.GetValue("ProductID")))
$rk.Close()
$itm.SubItems.Add((Get-ProductKey ('HKLM:\\' + $reg)))
}
function Measure-Items {
$sbPnl_1.Text = $lstView.Items.Count.ToString() + ' item(s)'
if ($lstView.Items.Count -eq 0) {
$sbPnl_2.Text = 'Not scaned'
}
else {
$sbPnl_2.Text = 'Scan complete'
}
}
function Get-Image($s) {
[Drawing.Image]::FromStream((New-Object IO.MemoryStream(($$ = `
[Convert]::FromBase64String($s)), 0, $$.Length)))
}
##################################################################################################
$img = "Qk02AwAAAAAAADYAAAAoAAAAEAAAABAAAAABABgAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAA/////////////" + `
"///////////6urqhoaG////////////////////////////////////////////4+PjhoaGwMDATU1NhoaGIi" + `
"Ii////////////////////////////////////////srKypKCggICAsrKyhoaGIiIi///////////////////" + `
"/kKmt8fHx////////////gICAmZmZQkJCVVVVhoaGIiIi////////////wMDAQkJCAMzMTU1N////////zMzM" + `
"wMDAmZmZhoaGwMDAhoaGIiIi////////8fHxM2ZmAP//M2ZmADMz////////////lpaWmZmZTU1N3d3dhoaGH" + `
"Bwc////zMzMAICAAMzMM2ZmADMz8Pv/////////wMDA19fXmZmZmZmZzMzM4+PjKSkp////M5mZAP//M2ZmAD" + `
"Mz8Pv/////////////////wMDApKCg19fXwMDAFhYWFhYWHBwcAP//M2ZmADMz////////////////////srK" + `
"ysrKy3d3dQkJCZpmZAP//AP//AP//M5mZAGZm////////////////////srKy19fXpKCgwMDAAMzMAP//ZszM" + `
"ZszMZszMZszMd3d3////////////////////4+Pj19fXsrKypKCgAP//AP//AICAAGZmZszMZszMd3d3/////" + `
"///////////////4+Pj19fXVVVVd3d3AP//kKmtZmZmAICAAICAZpmZsrKy////////////////////zMzMzM" + `
"zMQkJCZmZmAP//AAAAsrKyAMzMM8zMM2Zm////////////////////////6urqzMzMsrKyKSkplpaWX19fZmZ" + `
"mAMzMOTk5////////////////////////////////4+PjzMzMTU1NzMzMhoaGwMDA3d3d////////////////" + `
"////////////////////////////////////////////////////////////////////////////"
##################################################################################################
frmMain_Show
|
PowerShellCorpus/PoshCode/Enable and Configure SNM.ps1
|
Enable and Configure SNM.ps1
|
#Powershell Script To Install SNMP Services (SNMP Service, SNMP WMI Provider)
#Variables :)
$pmanagers = "ADD YOUR MANAGER(s)"
$commstring = "ADD YOUR COMM STRING"
#Import ServerManger Module
Import-Module ServerManager
#Check If SNMP Services Are Already Installed
$check = Get-WindowsFeature | Where-Object {$_.Name -eq "SNMP-Services"}
If ($check.Installed -ne "True") {
#Install/Enable SNMP Services
Add-WindowsFeature SNMP-Services | Out-Null
}
##Verify Windows Servcies Are Enabled
If ($check.Installed -eq "True"){
#Set SNMP Permitted Manager(s) ** WARNING : This will over write current settings **
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v 1 /t REG_SZ /d localhost /f | Out-Null
#Used as counter for incremting permitted managers
$i = 2
Foreach ($manager in $pmanagers){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v $i /t REG_SZ /d $manager /f | Out-Null
$i++
}
#Set SNMP Community String(s)- *Read Only*
Foreach ( $string in $commstring){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\ValidCommunities" /v $string /t REG_DWORD /d 4 /f | Out-Null
}
}
Else {Write-Host "Error: SNMP Services Not Installed"}
|
PowerShellCorpus/PoshCode/getMyModulePrefix.ps1
|
getMyModulePrefix.ps1
|
function getMyModulePrefix {
<#
.SYNOPSIS
An internal support routine for imported modules to retrieve a prefix
assigned using the Import-Module -prefix argument.
.DESCRIPTION
Functions in modules imported with the -prefix option have two command
names. The module defined name and the prefixed name. When calling one
of these functions externally the prefixed name is required, when calling
internally the defined name is required.
Functions that have output that includes the functions name will return
either the prefixed or non-prefixed depending on if it was internally or
externally called which can cause confusion for the end user.
For those times that your function needs to include the function name in
some output use getMyModulePrefix then modify the function name before
writing.
.EXAMPLE
$MyModulePrefix = "$(getMyModulePrefix)"
$MyCommandName = $MyCommandName.replace("-","-$($MyModulePrefix)")
.OUTPUT
[string]
#>
[CmdletBinding()]
param()
$MyModuleName = "$($MyInvocation.MyCommand.ModuleName)"
$MyCommandName = "$($MyInvocation.MyCommand.Name)"
$MyModuleCommandName = (Get-Command -Module $MyModuleName -Name "*$($MyCommandName)" |
where {$_.Name -ne $($MyCommandName)} | select -ExpandProperty Name )
if ( $MyModuleCommandName -eq $null ) {
$MyModulePrefix = $null
} else {
$MyModulePrefix = $MyModuleCommandName.replace("getMyModulePrefix", $null)
}
return $MyModulePrefix
}
|
PowerShellCorpus/PoshCode/FS_FindFiles_1.ps1
|
FS_FindFiles_1.ps1
|
Param (
[string[]]$Computers=$env:ComputerName,
[string[]] $Paths = @("C:\\Windows","C:\\Windows\\system32"),
[string[]] $FileNames = @("fsb.tmp","fsb.stb","notpad.exe")
)
$Global:objOut = @()
Function FindFiles ($Computer, $Filter){
try{
$Files = Gwmi -namespace "root\\CIMV2" -computername $Computer -class CIM_DataFile -filter "Name = '$Filter'"
if ($Files){
foreach ($File in $Files){
$Result = New-Object PSObject -Property @{
Host = $Computer
Path = $File.Name
FileSize = "$([math]::round($File.FileSize/1KB)) KB"
Modified = [System.Management.ManagementDateTimeconverter]::ToDateTime($File.LastModified).ToShortDateString()
InUse = ([System.Convert]::ToBoolean($File.InUseCount))
LastUsed = [System.Management.ManagementDateTimeconverter]::ToDateTime($File.LastAccessed).ToShortDateString()
}
$Global:objOut += $Result
}
}
}
catch{
$continue = $False
Write-Host $($error[0] | fl *)
}
}
foreach ($Computer in $Computers){
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet){
foreach ($Path in $Paths){
foreach ($FileName in $FileNames){
# WMI needs double quotes in a path
$Filter = "$Path\\$FileName" -replace '\\\\','\\\\'
FindFiles $Computer $Filter
}
}
}
else {
Write-Host "$Computer cannot be reached"
}
}
$Global:objOut
|
PowerShellCorpus/PoshCode/Update-vSwitchSecurity.ps1
|
Update-vSwitchSecurity.ps1
|
#requires -version 2.0
# Author: Glenn Sizemore 12/19/2009
# Source: http://get-admin.com/blog/?p=239
#
# v1.0 : It works
Cmdlet Update-vSwitchSecurity -SupportsShouldProcess {
param (
[Parameter(position=0,Mandatory=$TRUE,HelpMessage="Name of the vSwitch to modify")]
[string]
$vSwitch,
[Parameter(position=1,Mandatory=$TRUE,ValueFromPipeline=$TRUE,HelpMessage="One or more hosts for which we want to modify the vSwitch Security")]
[VMware.VimAutomation.Client20.VMHostImpl[]]
$VMhost,
[switch]
$AllowPromiscuous,
[switch]
$MacChanges,
[switch]
$ForgedTransmits
)
#.Synopsis
# Modify the security settings of a vSwitch
#.Description
# Modify the security settings of a vSwitch
#.Parameter vSwitch
# Name of the vSwitch to modify
#
# Type : String
# Mandatory : TRUE
# ParamaterSet:
# PipeLine : FALSE
#.Parameter VMHost
# One or more hosts for which we want to modify the vSwitch Security
#
# Type : VMHostImpl[]
# Mandatory : TRUE
# ParamaterSet:
# PipeLine : ByValue
#.Parameter AllowPromiscuous
# If provided then AllowPromiscuous will be enabled thus allowing all traffic
# is seen on the port. The default action is to disable AllowPromiscuous.
#
# Type : String
# Mandatory : TRUE
# ParamaterSet:
# PipeLine : FALSE
#.Parameter ForgedTransmits
# If provided then ForgedTransmits will be enabled thus allowing the virtual
# network adapter to send network traffic with a different MAC address than
# that of the virtual network adapter.
# The default action is to disable ForgedTransmits
#
# Type : Switch
# Mandatory : FALSE
# ParamaterSet:
# PipeLine : FALSE
#.Parameter MacChanges
# If provided then MacChanges will be enabled thus allowing Media Access Control
# (MAC) address to be changed. The default action is to disable MacChanges
#
# Type : Switch
# Mandatory : FALSE
# ParamaterSet:
# PipeLine : FALSE
#.Example
# # Set Promiscuous Mode, MAC Addess Changes, and Forged Transmits to reject.
# Update-vSwitchSecurity -VMHost (get-vmhost ESX1) -vSwitch 'vSwitch0'
#.Example
# # Enable Promiscuous Mode on vSwitch1 on all ESX hosts in cluster SQL
#
# Get-Cluster SQL | Get-VMHost | Update-vSwitchSecurity vswitch1 -AllowPromiscuous
#
# # If your not sure your running against the correct host/switch use -whatif/confirm
# Get-Cluster SQL | Get-VMHost | Update-vSwitchSecurity vswitch1 -AllowPromiscuous -whatif
#
# # Will output:
#
# What if: Performing operation "Updating vSwitch1 Security settings: AllowPromiscuous=TRUE,
# MacChanges=FALSE, ForgedTransmits=FALSE" on Target "ESX1".
# What if: Performing operation "Updating vSwitch1 Security settings: AllowPromiscuous=TRUE,
# MacChanges=FALSE, ForgedTransmits=FALSE" on Target "ESX2".
# What if: Performing operation "Updating vSwitch1 Security settings: AllowPromiscuous=TRUE,
# MacChanges=FALSE, ForgedTransmits=FALSE" on Target "ESX3".
#
# # Be aware that the vSwitch param will perform a wildcard search for the vswitch name!
foreach ($H in $vmhost) {
$hostid = Get-VMHost $H | get-view
$networkSystem = get-view $hostid.ConfigManager.NetworkSystem
$networkSystem.NetworkConfig.Vswitch| ?{$_.name -match $vSwitch} | % {
$switchSpec = $_.spec
$vSwitchName = $_.name
if ($AllowPromiscuous) {
$switchSpec.Policy.Security.AllowPromiscuous = $TRUE
$msg = "Updating $($vSwitchName) Security settings: AllowPromiscuous=True"
} else {
$switchSpec.Policy.Security.AllowPromiscuous = $FALSE
$msg = "Updating $($vSwitchName) Security settings: AllowPromiscuous=False"
}
if ($MacChanges) {
$switchSpec.Policy.Security.MacChanges = $TRUE
$msg += ", MacChanges=True"
} else {
$switchSpec.Policy.Security.MacChanges = $FALSE
$msg += ", MacChanges=False"
}
if ($ForgedTransmits) {
$switchSpec.Policy.Security.ForgedTransmits = $TRUE
$msg += ", ForgedTransmits=True"
} else {
$switchSpec.Policy.Security.ForgedTransmits = $FALSE
$msg += ", ForgedTransmits=False"
}
if (($pscmdlet.ShouldProcess($H.Name, $msg))) {
$hostNetworkSystemView = get-view $hostid.configManager.networkSystem
$hostNetworkSystemView.UpdateVirtualSwitch($vSwitchName, $switchSpec)
}
}
}
}
|
PowerShellCorpus/PoshCode/Audit NTFS on Shares.ps1
|
Audit NTFS on Shares.ps1
|
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$wSheet = $Excel.Worksheets.Item(1)
$wSheet.Cells.item(1,1) = "Folder Path:"
$wSheet.Cells.Item(1,2) = "Users/Groups:"
$wSheet.Cells.Item(1,3) = "Permissions:"
$wSheet.Cells.Item(1,4) = "Permissions Inherited:"
$WorkBook = $wSheet.UsedRange
$WorkBook.Interior.ColorIndex = 8
$WorkBook.Font.ColorIndex = 11
$WorkBook.Font.Bold = $True
####Change the path to the folder or share you want NTFS perms on####
$dirToAudit = Get-ChildItem -Path "c:\\inetpub" -recurse | Where {$_.psIsContainer -eq $true}
$intRow = 1
foreach ($dir in $dirToAudit)
{
$colACL = Get-Acl -Path $dir.FullName
foreach ($acl in $colACL)
{
$intRow++
$wSheet.Cells.Item($intRow,1) = $dir.FullName
foreach ($accessRight in $acl.Access)
{
$wSheet.Cells.Item($intRow,2) = "$($AccessRight.IdentityReference)"
$wSheet.Cells.Item($intRow,3) = "$($AccessRight.FileSystemRights)"
$wSheet.Cells.Item($intRow,4) = $acl.AreAccessRulesProtected
$intRow++
}
}
}
$WorkBook.EntireColumn.AutoFit()
|
PowerShellCorpus/PoshCode/Product key_5.ps1
|
Product key_5.ps1
|
from System import Array, Char, Console
from System.Collections import ArrayList
from Microsoft.Win32 import Registry
def DecodeProductKey(digitalProductID):
map = ("BCDFGHJKMPQRTVWXY2346789").ToCharArray()
key = Array.CreateInstance(Char, 29)
raw = ArrayList()
i = 52
while i < 67:
raw.Add(digitalProductID[i])
i += 1
i = 28
while i >= 0:
if (i + 1) % 6 == 0:
key[i] = '-'
else:
k = 0
j = 14
while j >= 0:
k = (k * 256) ^ raw[j]
raw[j] = (k / 24)
k %= 24
key[i] = map[k]
j -= 1
i -= 1
return key
reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")
val = reg.GetValue("DigitalProductId")
Console.WriteLine(DecodeProductKey(val))
Hmm, Mark stole my code at http://poshcode.org/3545
|
PowerShellCorpus/PoshCode/TheGameOfLife.ps1
|
TheGameOfLife.ps1
|
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$SCRIPT:hostProperties = @{};
$SCRIPT:hostState = $null;
$SCRIPT:BoardWidth = 50;
$SCRIPT:BoardHeight = 50;
Function Initialize-Host
{
Param(
[Parameter(Mandatory=$false)]
$wndTitle = "Game of Life...",
[Parameter(Mandatory=$false)]
[Int]$wndWidth=50,
[Parameter(Mandatory=$false)]
[Int]$wndHeight=50
)
$wndSize = $Host.UI.RawUI.WindowSize;
$wndSize.Width = $wndWidth;
$wndSize.Height = $wndHeight;
$wndBuffSize = $wndSize;
#Set Console
$Host.UI.RawUI.WindowTitle = $wndTitle;
$Host.UI.RawUI.WindowSize = $wndSize;
$Host.UI.RawUI.BufferSize = $wndBuffSize;
$Host.UI.RawUI.CursorSize = 0;
$Host.UI.RawUI.ForegroundColor = "Green";
$Host.UI.RawUI.BackgroundColor = "Black";
#get a clear the screen.
Clear-Host;
}
Function Push-Host
{
#Get the full buffer
$hostRect = "System.Management.Automation.Host.Rectangle"
$bufferObject = New-Object $hostRect 0, 0, $(($Host.UI.RawUI.BufferSize).Width), $(($Host.UI.RawUI.BufferSize).Height)
$SCRIPT:hostProperties= @{
"Title" = $Host.UI.RawUI.WindowTitle
"WindowSize" = $Host.UI.RawUI.WindowSize
"WindowPosition" = $Host.UI.RawUI.WindowPosition
"BufferSize" = $Host.UI.RawUI.BufferSize
"Buffer" = $Host.UI.RawUI.GetBufferContents($bufferObject)
"Background" = $Host.UI.RawUI.BackgroundColor
"Foreground" = $Host.UI.RawUI.ForegroundColor
"CursorSize" = $Host.UI.RawUI.CursorSize
"CursorPosition" = $Host.UI.RawUI.CursorPosition
}
$SCRIPT:hostState = New-Object -TypeName PSCustomObject -Property $SCRIPT:hostProperties
}
Function Pop-Host
{
#Restore buffer contents
$Host.UI.RawUI.BufferSize = $SCRIPT:hostState.BufferSize;
$initPosition = $Host.UI.RawUI.WindowPosition;
$initPosition.x = 0;
$initPosition.y = 0;
$Host.UI.RawUI.SetBufferContents($initPosition, $SCRIPT:hostState.Buffer)
#Start with the window
$Host.UI.RawUI.WindowTitle = $SCRIPT:hostState.Title;
$Host.UI.RawUI.WindowPosition = $SCRIPT:hostState.WindowPosition;
$Host.UI.RawUI.WindowSize = $SCRIPT:hostState.WindowSize;
#Set cursor
$Host.UI.RawUI.CursorSize = $SCRIPT:hostState.CursorSize;
$Host.UI.RawUI.CursorPosition = $SCRIPT:hostState.CursorPosition;
#set colors
$Host.UI.RawUI.ForegroundColor = $SCRIPT:hostState.Foreground;
$Host.UI.RawUI.BackgroundColor = $SCRIPT:hostState.Background;
}
Function Get-CursorPosition
{
$dY = ([System.Windows.Forms.Cursor]::Position.Y ) #read the Y coordinates
$dX = ([System.Windows.Forms.Cursor]::Position.X ) #read the X coordinates
return @($dX, $dY)
}
Function Draw-Pixel
{
param(
[Parameter(Mandatory=$true)]
[Int]$X,
[Parameter(Mandatory=$true)]
[Int]$Y,
[Parameter(Mandatory=$false)]
[String]$ForeColor = 'White',
[Parameter(Mandatory=$false)]
[String]$BackColor = 'Black',
[Parameter(Mandatory=$false)]
[String]$pixel = [Char]9608
)
$pos = $Host.UI.RawUI.WindowPosition
$pos.x = $x
$pos.y = $y
$row = $Host.UI.RawUI.NewBufferCellArray($pixel, $ForeColor, $BackColor)
$Host.UI.RawUI.SetBufferContents($pos,$row)
}
#Initialize a full board of dead cells.
Function Initialize-GameMatrix
{
param(
[Int32]$M,
[Int32]$N
)
$gameMatrix = New-Object "Int32[,]" $M, $N
for($i=0; $i -lt $M; $i++)
{
for($j=0; $j -lt $N; $j++)
{
$gameMatrix[$i, $j] = 0;
}
}
return ,$gameMatrix
}
#show the game board in 1's and 0's
Function Show-Matrix
{
param(
[Int[,]]$matrix
)
[Int]$m = $matrix.GetLength(0);
[Int]$n = $matrix.GetLength(1);
for($i=0; $i -lt $m; $i++)
{
for($j=0; $j -lt $n; $j++)
{
Write-Host("{0}" -f $matrix[$i,$j]) -NoNewLine;
}
Write-Host ""
}
}
#Currently Taking 10.5 Secs to generate next generation.
#consumes around 20-25% cpu.
#need to find a better way to do this.
Function Get-NextGeneration
{
param(
[Int[,]]$GameMatrix
)
BEGIN
{
$tmpGameMatrix = $GameMatrix;
#The game board for game of life is infinite. So, we simulate this by wrapping the
#width and height.
Function Get-WrappedWidth
{
param(
[Int]$x,
[Int]$xEdge
)
$x += $xEdge;
while($x -lt 0){$x += $SCRIPT:BoardWidth;}
while($x -ge $SCRIPT:BoardWidth){$x -= $SCRIPT:BoardWidth;}
return $x;
}
Function Get-WrappedHeight
{
param(
[Int]$y,
[Int]$yEdge
)
$y += $yEdge;
while($y -lt 0){$y += $SCRIPT:BoardHeight;}
while($y -ge $SCRIPT:BoardHeight){$y -= $SCRIPT:BoardHeight}
return $y;
}
Function Get-Neighbours
{
param(
[Int[,]]$ArrayMatrix,
[Int]$coordX,
[Int]$coordY
)
[Int]$nx = 0;
[Int]$ny = 0;
[Int]$count = 0;
for($nx = -1; $nx -le 1; $nx++)
{
for($ny = -1; $ny -le 1; $ny++)
{
if($nx -or $ny)
{
if($ArrayMatrix[$(Get-WrappedWidth $coordX $nx), $(Get-WrappedHeight $coordY $ny)])
{
$count += 1;
}
}
}
}
return $count;
}
}
PROCESS
{
for($x = 0; $x -lt $SCRIPT:BoardWidth; $x++)
{
for($y = 0; $y -lt $SCRIPT:BoardHeight; $y++)
{
$neighbors = Get-Neighbours $tmpGameMatrix $x $y
switch($neighbors)
{
{($neighbors -lt 2) -or ($neighbors -gt 3)}{$tmpGameMatrix[$x, $y] = 0;}
{($neighbors -eq 3)}{$tmpGameMatrix[$x, $y] = 1;}
}
}
}
}
END
{
$GameMatrix = $tmpGameMatrix;
#should we even do this? : return ,$GameMatrix
return ,$GameMatrix;
}
}
Function Draw-Board
{
param(
[Int[,]]$Board
)
for($bx = 0; $bx -lt $SCRIPT:BoardWidth; $bx++)
{
for($by = 0; $by -lt $SCRIPT:BoardHeight; $by++)
{
if($Board[$bx, $by])
{
Draw-Pixel -X $bx -Y $by -ForeColor "Green" -BackColor "Yellow"
}else{
Draw-Pixel -X $bx -Y $by -ForeColor "Black" -BackColor "Black"
}
}
}
}
Function Main
{
Push-Host;
Initialize-Host;
$gameBoard = Initialize-GameMatrix 50 50;
#Sample filler
$gameBoard[25,10] = 1
$gameBoard[25,11] = 1
$gameBoard[26,11] = 1
$gameBoard[27,11] = 1
$gameBoard[27,9] = 1
Draw-Board $gameBoard
do{
$newBoard = Get-NextGeneration $gameBoard;
#Clear-Host;
Draw-Board $newBoard;
}until($Host.UI.RawUI.KeyAvailable)
Pop-Host;
}
. Main
|
PowerShellCorpus/PoshCode/Advanced search.ps1
|
Advanced search.ps1
|
<#
Using examples:
Example 1:
Get-ItemPlace *.log -h
It will search all (including that have "Hidden" attribute) *.log files on local drives.
Example 2:
Get-ItemPlace sysinternals hkcu:\\
This command invoke search Sysinyetrnals key into HKEY_CURRENT_USER.
#>
function Get-ItemPlace {
param ([string]$wildcard, `
[array]$path = $(gdr | % {$_.Root} | ? {$_ -like '*:\\' -and $_ -ne 'A:\\'}), `
[switch]$hidden)
if ($path -match "(HKCU|HKLM)\\:\\\\") {
dir $path -r -i $wildcard -ea 0 | % {$_.Name}
}
else {
dir $path -r -i $wildcard -fo:$hidden -ea 0 | % {$_.FullName}
}
}
|
PowerShellCorpus/PoshCode/Import-ExcelToSQL_2.ps1
|
Import-ExcelToSQL_2.ps1
|
#Change these settings as needed
$filepath = 'C:\\Users\\u00\\Documents\\backupset.xlsx'
#Comment/Uncomment connection string based on version
#Connection String for Excel 2007:
$connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"
#Connection String for Excel 2003:
#$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";"
$qry = 'select * from [backupset$]'
$sqlserver = 'Z002\\SQLEXPRESS'
$dbname = 'SQLPSX'
#Create a table in destination database with the with referenced columns and table name.
$tblname = 'ExcelData_fill'
#######################
function Get-ExcelData
{
param($connString, $qry='select * from [sheet1$]')
$conn = new-object System.Data.OleDb.OleDbConnection($connString)
$conn.open()
$cmd = new-object System.Data.OleDb.OleDbCommand($qry,$conn)
$da = new-object System.Data.OleDb.OleDbDataAdapter($cmd)
$dt = new-object System.Data.dataTable
[void]$da.fill($dt)
$conn.close()
$dt
} #Get-ExcelData
#######################
function Write-DataTableToDatabase
{
param($dt,$destServer,$destDb,$destTbl)
$connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;"
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = "$destTbl"
$bulkCopy.WriteToServer($dt)
}# Write-DataTableToDatabase
#######################
$dt = Get-ExcelData $connString $qry
Write-DataTableToDatabase $dt $sqlserver $dbname $tblname
|
PowerShellCorpus/PoshCode/SharePoint Large Lists_1.ps1
|
SharePoint Large Lists_1.ps1
|
[reflection.assembly]::loadwithpartialname("Microsoft.SharePoint")
$cs = [microsoft.sharepoint.administration.spwebservice]::ContentService
$global:largeListThreshhold = 2000
function Is-Admin([Microsoft.SharePoint.SPRoleAssignment]$roleAssignment)
{
return (($roleAssignment.roledefinitionbindings | where { ($_.BasePermissions.ToString() -match "ManageLists|ManageWeb|FullMask") }) -ne $null)
}
function Write-ListDetails($list,$web,$site)
{
$fields = @()
$fields += $list.Title
$fields += $list.RootFolder
$fields += ($list.ContentTypes | select -first 1).Name
$fields += ($list.ContentTypes | select -first 1).Id.ToString()
$fields += ($list.ContentTypes | select -first 1).Id.Parent.ToString()
$fields += $list.Items.NumberOfFields
$fields += $list.Items.Count
$fields += $list.Created
$fields += $list.LastItemModifiedDate
$listAdmins = @()
$listAdmins += $list.RoleAssignments | where { Is-Admin $_ }
if ($listAdmins.Count -gt 0)
{
$fields += $listAdmins[0].Member.Name
$fields += $listAdmins[0].Member.Email
$fields += [string]::Join("; ", @($listAdmins | % { if ($_.Member -ne $null) { $_.Member.ToString() } else { "" } } ))
} else {
$fields += ""
$fields += ""
$fields += ""
}
$fields += $web.Url
$fields += $web.Title
$fields += $site.Url
[string]::Join("`t", $fields)
}
function Enumerate-LargeListsInSite($siteCollection)
{
foreach ($web in $siteCollection.AllWebs) {
$web.Lists | where { $_.Items.Count -gt $global:largeListThreshhold } | foreach { Write-ListDetails -list $_ -web $web -site $siteCollection }
$web.Dispose()
}
}
function List-FieldNames
{
$fieldNames = @()
$fieldNames += "ListTitle"
$fieldNames += "ListRootFolderURL"
$fieldNames += "ContentType1Name"
$fieldNames += "ContentType1ID"
$fieldNames += "ContentType1ParentID"
$fieldNames += "NumberOfFields"
$fieldNames += "Items"
$fieldNames += "CreatedDate"
$fieldNames += "LastItemModifiedDate"
$fieldNames += "ListAdmin1Name"
$fieldNames += "ListAdmin1Email"
$fieldNames += "AllListAdmins"
$fieldNames += "WebURL"
$fieldNames += "WebTitle"
$fieldNames += "SiteURL"
return [string]::Join("`t", $fieldNames)
}
function Enumerate-LargeLists
{
List-FieldNames
$webApplications = $cs.WebApplications | foreach { $_ }
foreach ($webApplication in $webApplications) {
$webApplication.Sites | foreach {
Enumerate-LargeListsInSite -siteCollection $_
$_.Dispose()
}
}
}
#USAGE: paste contents into PowerShell window; call "Enumerate-LargeLists > yourtextfilename.txt"
#then paste contents of text file into Excel spreadsheet. Output is
#intended to be perused and analyzed in Excel.
|
PowerShellCorpus/PoshCode/Pipeline and Parameter_1.ps1
|
Pipeline and Parameter_1.ps1
|
param(
[Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)]
[string[]]
$ComputerName
)
Process {
foreach ($cn in $ComputerName) {
Write-Host "Processing $cn"
}
}
|
PowerShellCorpus/PoshCode/Get-DNSZoneRecords_1.ps1
|
Get-DNSZoneRecords_1.ps1
|
#==========================================================================
# NAME: Get-DNSZoneRecords.ps1
# AUTHOR: Saehrig, Steven (trac3r726)
# DATE : 10/17/2008
#
# COMMENT:
# Just comment out the variable and enter the info you need for
# computername, dnszonename, and remove the credential portion if not needed.
# Otherwise on Execution you will be prompted for credentials and IP.
#==========================================================================
param(
$computer = $(Read-Host "Server IP:"),
$cred = $(Get-Credential)
)
$dnszonename = (Get-WmiObject Win32_computersystem -computerName $computer -credential $cred).domain
get-wmiobject -namespace "root\\microsoftdns" -class microsoftdns_atype -computername $computer `
-credential $cred -filter "containername='$dnszonename'" |
ft dnsservername, ownername, recorddata, ttl
|
PowerShellCorpus/PoshCode/330802b9-dd0b-41e6-8020-cd304a79d948.ps1
|
330802b9-dd0b-41e6-8020-cd304a79d948.ps1
|
function Run-Query($siteUrl, $queryText)
{
[reflection.assembly]::loadwithpartialname("microsoft.sharePOint") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server.search") | out-null
$s = [microsoft.sharepoint.spsite]$siteUrl
$q = new-object microsoft.office.server.search.query.fulltextsqlquery -arg $s
$q.querytext = $queryText
$q.RowLimit = 100
$q.ResultTypes = "RelevantResults"
$dt = $q.Execute()
$r = $dt["RelevantResults"]
$output = @()
while ($r.Read()) {
$o = new-object PSObject
0..($r.FieldCount-1) | foreach {
add-member -inputObject $o -memberType "NoteProperty" -name $r.GetName($_) -value $r.Getvalue($_)
}
$output += $o
}
return $output
}
#Sample usage:
#Run-Query -siteUrl "http://dev/" -queryText "SELECT PreferredName, WorkPhone FROM SCOPE() WHERE ""scope"" = 'People' AND PreferredName LIKE '%Peter%'"
|
PowerShellCorpus/PoshCode/Audit iPhone_Palm Users_1.ps1
|
Audit iPhone_Palm Users_1.ps1
|
#Created by P. Sukus
#Modified by D. Dill
#Name: mobile users syncing through OWA audit
#set the timeframe to audit in days
$Daysold = 1
$Date = (get-date).adddays(-$daysold)
$servers = "server1", "server2", "server3"
foreach ($s in $servers)
{
Write-host -ForegroundColor Blue "Checking server $s for files from the last $daysold day(s)"
$logfiles += gci -path \\\\$s\\c$\\inetpub\\logs\\LogFiles\\W3SVC1 | where {$_.LastWriteTime -gt $date}
}
Foreach ($l in $logfiles)
{
Write-host "Processing "$l.fullname
Copy-item $l.fullname -Destination $pwd.path
$palmusers += gc $l.name | where {$_ -match "DeviceType=Palm"}
$iphoneusers += gc $l.name | where {$_ -match "DeviceType=iPhone"}
Remove-Item $l.name
}
$iuser = @()
$puser = @()
foreach ($l in $iphoneusers | where {$_ -ne $null})
{
$u = $l.split(" ")[7]
if ($iuser -notcontains $u)
{
$iuser += "$u"
}
$u = $null
}
foreach ($l in $palmusers | where {$_ -ne $null})
{
$u = $l.split(" ")[7]
if ($puser -notcontains $u)
{
$puser += "$u"
}
$u = $null
}
$body = "<!DOCTYPE html PUBLIC `"-//W3C//DTD XHTML 1.0 Strict//EN`" `"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd`">"
$body += "<html xmlns=`"http://www.w3.org/1999/xhtml`">"
$body += "<head>"
$body += "<title>iPhone Users</title>"
$body += "</head><body>"
$body += "<table border=1>"
$body += "<colgroup>"
$body += "<col/>"
$body += "</colgroup>"
$body += "<tr><td><b>iPhone Users</b></td></tr>"
foreach ($y in $iuser)
{
$body += "<tr><td>$y</td></tr>"
}
$body += "<tr><td></td></tr>"
$body += "<br>"
$body += "<tr><td><b>Palm Users</b></td></tr>"
foreach ($y in $puser)
{
$body += "<tr><td>$y</td></tr>"
}
$body += "</table>"
$body += "<br>Audited servers: $servers <br>"
$body += "Audited for: DeviceType=Palm and DeviceType=iPhone"
$body += "</body></html>"
$smtpServer = "yourmailserver"
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$From = "dontreplyiamascript@domain.com"
$To = "youremail@yourdomain.com"
$subject = "Mobile users syncing through OWA in the last $daysold day(s)"
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)
clear-variable logfiles
clear-variable servers
clear-variable daysold
|
PowerShellCorpus/PoshCode/chkhash_29.ps1
|
chkhash_29.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
if (!($second) -or $second -eq "") {return $true}
$first=join-path $first "\\"
foreach($s in $second)
{
if ($first.tolower().startswith($s.tolower())) {return $false}
}
return $true
}
function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling
{ # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done
# before printing anything else, so that you are not printing into a long file name with extra characters from it visible.
if ($Host.Name -match 'ise')
{ write-host $writestr; return }
if ($global:lastlen -eq $null) {$global:lastlen=0}
$ctop=[console]::cursortop
[console]::cursorleft=0
$oldwritestrlen=$writestr.length
$spaces = ""
if ($global:lastlen -gt $writestr.length)
{
$spaces = " " * ($global:lastlen-$writestr.length)
}
$writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null)
$cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to.
if ($cwe -gt 0) {$ctop-=($cwe)}
write-host "$writestr" -nonewline
$global:oldctop=[console]::cursortop
if ([console]::cursorleft -ne 0) {$global:oldctop+=1}
write-host "$spaces" -nonewline
$global:lastlen = $oldwritestrlen
[console]::cursortop=$ctop
[console]::cursorleft=0
}
function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other
{ # and before printing something else
if ($Host.Name -match 'ise')
{ return }
if ($global:oldctop -ne $null)
{
[console]::cursortop=$global:oldctop
[console]::cursorleft=0
}
$global:oldctop=$null
$global:lastlen=$null
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=@($args)
$nu = 0
$errs = 0
$fc = 0
$fm = 0
$upd = $false
$create = $false
$n = $null
"ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, "
"in order to detect corrupt or hacked files."
""
".\\chkhash.ps1 -h for usage."
""
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]"
" [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml"
" or create it and store hashes there if not present]"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
" [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude "
" c:\\users\\eve\\hashes directory and subdirs]"
" PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u"
" [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to"
" existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]"
" PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml"
" [Load hashes.xml and check hashes of all files contained within.]"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*")
{
$i++ # Get hashes xml database path
if ($i -ge $args2.count)
{
write-host "-X specified but no file path of .xml database specified. Exiting."
exit
}
$hashespath=$args2[$i]
continue
}
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
while (($i+1) -lt $args2.count)
{
$i++
if ($args2[$i] -like "-*") {break}
$exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories.
}
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files, minus directories and minus files in excluded paths
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
if ($files.count -eq 0) {"No files found. Exiting."; exit}
$files = $files | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
WriteFileNameEnd
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database
if (($xfiles.count -eq 0) -or ($files.count -eq 0)) {"No files in Database or no files specified. Exiting.";Exit}
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles | %{get-item -ea 0 -literalpath $_.fullname}
}
"Loaded $($xfiles.count) file hash(es)."
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 -literalpath $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {WriteFileName "Needs to be added: `"$($f.fullname)`"";WriteFileNameEnd;continue} # if not updating, then continue
WriteFileName "SHA-512 Hashing `"$($f.fullname)`" ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$xfiles+=@($f) # then add file + hash to list
continue
}
WriteFileName "SHA-512 Hashing and checking: `"$($f.fullname)`" ..."
$fc++ # File checked increment.
if (($upd -eq $false) -and ($f.length -ne $xfiles[$n].length))
{
$errs++
WriteFileName "Size mixmatch: `"$($f.fullname)`""; WriteFileNameEnd
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
# Check SHA512 and size for mixmatch.
if ($xfiles[$n].length -eq $f.length)
{
if ($xfiles[$n].SHA512 -eq $f.SHA512)
{
$fm++;continue # if matched, increment file matches and continue loop
}
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; WriteFileName "Updated `"$($f.fullname)`""; WriteFileNameEnd;continue}
WriteFileName "SHA-512 and/or size mixmatch found: `"$($f.fullname)`""; WriteFileNameEnd
}
WriteFileNameEnd # restore cursor position after last write string
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 or size mixmatch(es) found."
"$fm file(s) SHA512 and size matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/PS FindFirstFileW.ps1
|
PS FindFirstFileW.ps1
|
param(
[string] $dirRoot = $pwd,
[string] $Spec = "*.*",
[bool] $longOnly = $false
)
# Changes:
# 23/05/2008, Wayne Martin, Added the option to only report +max_path entries, and report the short path of those directories (which makes it easier to access them)
#
#
# Description:
# Use the wide unicode versions to report a directory listing of all files, including those that exceed the MAX_PATH ANSI limitations
#
# Assumptions, this script works on the assumption that:
# There's a console to write the output from the compiled VB.Net
#
# Author:
# Wayne Martin, 15/05/2008
#
# Usage
# PowerShell . .\\FindFiles.ps1 -d c:\\temp -s *.*
#
# PowerShell . .\\FindFiles.ps1 -d c:\\temp
#
# PowerShell . .\\FindFiles.ps1 -d c: -l $true
#
# References:
# http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx
# http://blogs.msdn.com/jaredpar/archive/2008/03/14/making-pinvoke-easy.aspx
$provider = new-object Microsoft.VisualBasic.VBCodeProvider
$params = new-object System.CodeDom.Compiler.CompilerParameters
$params.GenerateInMemory = $True
$refs = "System.dll","Microsoft.VisualBasic.dll"
$params.ReferencedAssemblies.AddRange($refs)
$txtCode = @'
Imports System
Imports System.Runtime.InteropServices
Class FindFiles
Const ERROR_SUCCESS As Long = 0
Private Const MAX_PREFERRED_LENGTH As Long = -1
<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet:=System.Runtime.InteropServices.CharSet.[Unicode])> _
Public Structure WIN32_FIND_DATAW
'''DWORD->unsigned int
Public dwFileAttributes As UInteger
'''FILETIME->_FILETIME
Public ftCreationTime As FILETIME
'''FILETIME->_FILETIME
Public ftLastAccessTime As FILETIME
'''FILETIME->_FILETIME
Public ftLastWriteTime As FILETIME
'''DWORD->unsigned int
Public nFileSizeHigh As UInteger
'''DWORD->unsigned int
Public nFileSizeLow As UInteger
'''DWORD->unsigned int
Public dwReserved0 As UInteger
'''DWORD->unsigned int
Public dwReserved1 As UInteger
'''WCHAR[260]
<System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=260)> _
Public cFileName As String
'''WCHAR[14]
<System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=14)> _
Public cAlternateFileName As String
End Structure
<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)> _
Public Structure FILETIME
'''DWORD->unsigned int
Public dwLowDateTime As UInteger
'''DWORD->unsigned int
Public dwHighDateTime As UInteger
End Structure
Partial Public Class NativeMethods
'''Return Type: HANDLE->void*
'''lpFileName: LPCWSTR->WCHAR*
'''lpFindFileData: LPWIN32_FIND_DATAW->_WIN32_FIND_DATAW*
<System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="FindFirstFileW")> _
Public Shared Function FindFirstFileW(<System.Runtime.InteropServices.InAttribute(), System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal lpFileName As String, <System.Runtime.InteropServices.OutAttribute()> ByRef lpFindFileData As WIN32_FIND_DATAW) As System.IntPtr
End Function
'''Return Type: BOOL->int
'''hFindFile: HANDLE->void*
'''lpFindFileData: LPWIN32_FIND_DATAW->_WIN32_FIND_DATAW*
<System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="FindNextFileW")> _
Public Shared Function FindNextFileW(<System.Runtime.InteropServices.InAttribute()> ByVal hFindFile As System.IntPtr, <System.Runtime.InteropServices.OutAttribute()> ByRef lpFindFileData As WIN32_FIND_DATAW) As <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)> Boolean
End Function
'''Return Type: BOOL->int
'''hFindFile: HANDLE->void*
<System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="FindClose")> _
Public Shared Function FindClose(ByVal hFindFile As System.IntPtr) As <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)> Boolean
End Function
'''Return Type: DWORD->unsigned int
'''lpszLongPath: LPCWSTR->WCHAR*
'''lpszShortPath: LPWSTR->WCHAR*
'''cchBuffer: DWORD->unsigned int
<System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="GetShortPathNameW")> _
Public Shared Function GetShortPathNameW(<System.Runtime.InteropServices.InAttribute(), System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal lpszLongPath As String, <System.Runtime.InteropServices.OutAttribute(), System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal lpszShortPath As System.Text.StringBuilder, ByVal cchBuffer As UInteger) As UInteger
End Function
End Class
Private Const FILE_ATTRIBUTE_DIRECTORY As Long = &H10
Dim FFW as New NativeMethods
Function Main(ByVal dirRoot As String, ByVal sFileSpec As String, Byval longOnly As Boolean) As Long
Dim result As Long
result = FindFiles(dirRoot, sFileSpec, longOnly)
main = result ' Return the result
End Function
Function FindFiles(ByRef sDir As String, ByVal sFileSpec as String, Byval longOnly As Boolean) As Long
Const MAX_PATH As Integer = 260
Dim FindFileData as WIN32_FIND_DATAW
Dim hFile As Long
Dim sFullPath As String
Dim sFullFile As String
Dim length as UInteger
Dim sShortPath As New System.Text.StringBuilder()
sFullPath = "\\\\?\\" & sDir
'console.writeline(sFullPath & "\\" & sFileSpec)
hFile = FFW.FindFirstFileW(sFullPath & "\\" & sFileSpec, FindFileData) ' Find the first object
if hFile > 0 Then ' Has something been found?
If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) <> FILE_ATTRIBUTE_DIRECTORY Then ' Is this a file?
sFullFile = sFullPath & "\\" & FindFileData.cFileName
If (longOnly AND sFullFile.Length >= MAX_PATH) Then
length = FFW.GetShortPathNameW(sFullPath, sShortPath, sFullPath.Length) ' GEt the 8.3 path
console.writeline(sFullFile & " " & sshortpath.ToString()) ' Yes, report the full path and filename
ElseIf (NOT longOnly)
console.writeline(sFullFile)
End If
End If
While FFW.FindNextFileW(hFile, FindFileData) ' For all the items in this directory
If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) <> FILE_ATTRIBUTE_DIRECTORY Then ' Is this a file?
sFullFile = sFullPath & "\\" & FindFileData.cFileName
If (longOnly AND sFullFile.Length >= MAX_PATH) Then
length = FFW.GetShortPathNameW(sFullPath, sShortPath, sFullPath.Length) ' GEt the 8.3 path
console.writeline(sFullFile & " " & sshortpath.ToString()) ' Yes, report the full path and filename
ElseIf (NOT longOnly)
console.writeline(sFullFile)
End If
End If
End While
FFW.FindClose(hFile) ' Close the handle
FindFileData = Nothing
End If
hFile = FFW.FindFirstFileW(sFullPath & "\\" & "*.*", FindFileData) ' Repeat the process looking for sub-directories using *.*
if hFile > 0 Then
If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) AND _
(FindFileData.cFileName <> ".") AND (FindFileData.cFileName <> "..") Then
Call FindFiles(sDir & "\\" & FindFileData.cFileName, sFileSpec, longOnly) ' Recurse
End If
While FFW.FindNextFileW(hFile, FindFileData)
If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) AND _
(FindFileData.cFileName <> ".") AND (FindFileData.cFileName <> "..") Then
Call FindFiles(sDir & "\\" & FindFileData.cFileName, sFileSpec, longOnly) ' Recurse
End If
End While
FFW.FindClose(hFile) ' Close the handle
FindFileData = Nothing
End If
End Function
end class
'@
$cr = $provider.CompileAssemblyFromSource($params, $txtCode)
if ($cr.Errors.Count) {
$codeLines = $txtCode.Split("`n");
foreach ($ce in $cr.Errors)
{
write-host "Error: $($codeLines[$($ce.Line - 1)])"
write-host $ce
#$ce out-default
}
Throw "INVALID DATA: Errors encountered while compiling code"
}
$mAssembly = $cr.CompiledAssembly
$instance = $mAssembly.CreateInstance("FindFiles")
$result = $instance.main($dirRoot, $Spec, $longOnly)
|
PowerShellCorpus/PoshCode/44121121-b64f-42c2-b48d-d6b74bc5fbb6.ps1
|
44121121-b64f-42c2-b48d-d6b74bc5fbb6.ps1
|
#######################
<#
.SYNOPSIS
Execute T-SQL Statments and return messages from SQL Server (print).
.DESCRIPTION
Execute T-SQL Statments and return messages from SQL Server (print).
.INPUTS
None
You cannot pipe objects to Invoke-ExecuteTSQL
.OUTPUTS
PSObject :
Boolean Exitcode = $True or $False indicating if the query ran successfully
String ErrorMessage = The ErrorMessage if not ran successfully
String Message = Messages from SQL Server (print)
.EXAMPLE
Invoke-ExecuteTSQL -SQLInstanceName . -DatabaseName YourDB -UserName YourUserName -PassWord YourPassword -Query $Query -verbose
This command runs a T-SQL Query using UserName and Password
.EXAMPLE
Invoke-ExecuteTSQL -SQLInstanceName . -DatabaseName YourDB -Query $Query -verbose
This command runs a T-SQL Query using TrustedConnection
.LINK
Invoke-ExecuteTSQL
#>
function Invoke-ExecuteTSQL {
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$SQLInstanceName,
[Parameter(Position=1,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$DatabaseName,
[Parameter(Position=2)]
[string]$UserName,
[Parameter(Position=3)]
[string]$PassWord,
[Parameter(Position=4,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$Query
)
function Get-SQLConnectionEvent($EventID) {
write-output (Get-Event -SourceIdentifier $EventID -ErrorAction SilentlyContinue |
Select -ExpandProperty SourceEventArgs |
Select -ExpandProperty message)
Remove-Event -SourceIdentifier $EventID -ErrorAction SilentlyContinue
}
try {
if($Username -and $Password) {
Write-Verbose "Connecting to SQL Server using trusted connection"
$SqlConnection.ConnectionString = "Server=$($SQLInstanceName);Database=$($DatabaseName);Integrated Security=True"
} else {
Write-Verbose "Connecting to SQL Server using Username and Password"
$SqlConnection.ConnectionString = "Server=$($SQLInstanceName);Database=$($DatabaseName);UID=$($Username);PWD=$($Password)"
}
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhost;Database=confio;Integrated Security=True"
$eventID = "SQLConnectionEvent$(Get-date -format 'yyyyMMddhhmmss')";
write-verbose "Registering the event $eventID"
Register-ObjectEvent -inputObject $SqlConnection -eventName InfoMessage -sourceIdentifier $eventID
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandTimeout = 0
$SqlCmd.Connection.Open()
write-verbose "Running the Query"
$SqlCmd.CommandText = $Query
$SqlCmd.ExecuteNonQuery() | Out-Null
$ExitCode = $true
$Message = Get-SQLConnectionEvent $eventID
$ErroMessage = ""
} catch {
$ExitCode = $false
$Message = ""
$ErroMessage = $_.exception
}
Finally {
if ($SqlCmd.Connection.State -eq [System.Data.ConnectionState]::Open) {
write-verbose "Closing Connection"
$SqlCmd.Connection.Close()
$SqlCmd.Connection.Dispose()
}
}
Write-Output (New-Object psobject -Property @{ 'ExitCode' = $ExitCode
'Message' = $Message
'ErrorMessage' =$ErroMessage})
}
|
PowerShellCorpus/PoshCode/Server checks.ps1
|
Server checks.ps1
|
##Creates variable for filename
$date = (get-date).tostring("yyyy-MM-dd")
$filename = "H:\\dailychecks\\checks_$date.xls"
## Imports exchange modules
Import-Module "\\\\emailserver\\c$\\PS Modules\\vamail.videoarts.info.psm1"
## Start Internet Explorer to check that Video Arts website is up
Start-Process iexplore.exe
## Creates new excel object
$erroractionpreference = "SilentlyContinue"
$a = New-Object -comobject Excel.Application
$a.visible = $True
##creates workbook and three worksheets. Names three worksheets.
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$d = $b.Worksheets.Item(2)
$e = $b.Worksheets.Item(3)
$b.name = "$title"
$c.name = "Stopped Services"
$d.name = "Free Disk Space"
$e.name = "Server Connectivity"
##Populates cells with the titles
$c.Cells.Item(1,1) = "STOPPED SERVICES"
$c.Cells.Item(2,1) = "Machine Name"
$c.Cells.Item(2,2) = "Service Name"
$c.Cells.Item(2,3) = "State"
$d.Cells.Item(1,1) = "FREE DISK SPACE"
$d.Cells.Item(2,1) = "Machine Name"
$d.Cells.Item(2,2) = "Drive"
$d.Cells.Item(2,3) = "Total size (MB)"
$d.Cells.Item(2,4) = "Free Space (MB)"
$d.Cells.Item(2,5) = "Free Space (%)"
$e.Cells.Item(1,1) = "SERVER CONNECTIVITY"
$e.Cells.Item(2,1) = "Server Name"
$e.Cells.Item(2,2) = "Server Status"
##Changes colours and fonts for header sections populated above
$c = $c.UsedRange
$c.Interior.ColorIndex = 19
$c.Font.ColorIndex = 11
$c.Font.Bold = $True
$d = $d.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$e = $e.UsedRange
$e.Interior.ColorIndex = 19
$e.Font.ColorIndex = 11
$e.Font.Bold = $True
$e.EntireColumn.AutoFit()
##sets variables for the row in which data will start populating
$servRow = 3
$diskRow = 3
$pingRow = 3
###Create new variable to run connectivity check###
$colservers = Get-Content "C:\\dailychecks\\Servers.txt"
foreach ($strServer in $colservers)
##Populate computer names in first column
{
$e.Cells.Item($pingRow, 1) = $strServer.ToUpper()
## Create new object to ping computers, if they are succesful populate cells with green/success, if anything else then red/offline
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.send($strServer)
if ($Reply.status –eq “Success”)
{
$rightcolor = $e.Cells.Item($pingRow, 2)
$e.Cells.Item($pingRow, 2) = “Online”
$rightcolor.interior.colorindex = 10
}
else
{
$wrongcolor = $e.Cells.Item($pingRow, 2)
$e.Cells.Item($pingRow, 2) = "Offline"
$wrongcolor.interior.colorindex = 3
}
$Reply = ""
##Set looping variable so that one cell after another populates rather than the same cell getting overwritten
$pingRow = $pingRow + 1
##Autofit collumnn
$e.EntireColumn.AutoFit()
}
##gets each computer
$colComputers = get-content "C:\\dailychecks\\Servers.txt"
foreach ($strComputer in $colComputers)
{
##gets each service with startmode 'Auto' and state 'Stopped' for each computer
$stoppedservices = get-wmiobject Win32_service -computername $strComputer | where{$_.StartMode -eq "Auto" -and $_.State -eq "stopped"}
foreach ($objservice in $stoppedservices)
{
##Populates cells
$c.Cells.Item($servRow, 1) = $strComputer.ToUpper()
$c.Cells.Item($servRow, 2) = $objService.Name
$c.Cells.Item($servRow, 3) = $objService.State
$servRow = $servRow + 1
$c.EntireColumn.AutoFit()
}
##Gets disk information for each computer
$colDisks = get-wmiobject Win32_LogicalDisk -computername $strComputer -Filter "DriveType = 3"
foreach ($objdisk in $colDisks)
{
##Populates cells
$d.Cells.Item($diskRow, 1) = $strComputer.ToUpper()
$d.Cells.Item($diskRow, 2) = $objDisk.DeviceID
$d.Cells.Item($diskRow, 3) = "{0:N0}" -f ($objDisk.Size/1024/1024)
$d.Cells.Item($diskRow, 4) = "{0:N0}" -f ($objDisk.FreeSpace/1024/1024)
$d.Cells.Item($diskRow, 5) = "{0:P0}" -f ([double]$objDisk.FreeSpace/[double]$objDisk.Size)
$diskRow = $diskRow + 1
$d.EntireColumn.AutoFit()
}
}
##Saves file using Filename variable set at the top of the document
$b.SaveAs($filename, 1)
|
PowerShellCorpus/PoshCode/Set-FSMORoleOwner.ps1
|
Set-FSMORoleOwner.ps1
|
Function Set-FSMORoleOwner {
<#
.SYNOPSIS
Performs a transfer of a FSMO role to a specified Domain Controller.
.DESCRIPTION
Performs a transfer of a FSMO role to a specified Domain Controller.
.PARAMETER DomainController
Fully Qualified Domain Name of the Domain Controller to take a transfer role to
.PARAMETER Role
Name of the role to transfer to domain controller
.PARAMETER Transfer
Transfers the specified role and give to specified domain controller.
.PARAMETER Seize
Seize the specified role and give to specified domain controller.
.PARAMETER PassThru
Show the FSMO role owners after performing action
.NOTES
Name: Set-FSMORoleOwner
Author: Boe Prox
DateCreated: 06/9/2011
.EXAMPLE
Set-FSMORoleOwner -DomainController DC1.Rivendell.com -Role RidRole
Description
-----------
Transfers the RidRole to DC1.Rivendell.com
.EXAMPLE
Set-FSMORoleOwner -DomainController DC1.Rivendell.com -Role PdcRole -Transfer -PassThru
NamingRole : dc2.rivendell.com
Domain : rivendell.com
RidRole : dc2.rivendell.com
Forest : rivendell.com
InfrastructureRole : dc2.rivendell.com
SchemaRole : dc2.rivendell.com
PdcRole : dc1.rivendell.com
Description
-----------
Transfers the PdcRole to DC1.Rivendell.com and displays the current FSMO Role Owners.
.EXAMPLE
Set-FSMORoleOwner -DomainController DC1.Rivendell.com -Role PdcRole,RidRole,SchemaRole -Transfer -PassThru
NamingRole : dc2.rivendell.com
Domain : rivendell.com
RidRole : dc1.rivendell.com
Forest : rivendell.com
InfrastructureRole : dc2.rivendell.com
SchemaRole : dc1.rivendell.com
PdcRole : dc1.rivendell.com
Description
-----------
Transfers the PdcRole,RidRole and SchemaRole to DC1.Rivendell.com and displays the current FSMO Role Owners.
.EXAMPLE
Set-FSMORoleOwner -DomainController DC1.Rivendell.com -Role PdcRole -Seize -PassThru
WARNING: Performing this action is irreversible!
The Domain Controller that originally holds this role should be rebuilt to avoid issues on the domain!
NamingRole : dc2.rivendell.com
Domain : rivendell.com
RidRole : dc2.rivendell.com
Forest : rivendell.com
InfrastructureRole : dc2.rivendell.com
SchemaRole : dc2.rivendell.com
PdcRole : dc1.rivendell.com
Description
-----------
Seizes the PdcRole and places it on DC1.Rivendell.com and displays the current FSMO Role Owners.
#>
[cmdletbinding(
SupportsShouldProcess = 'True',
ConfirmImpact = 'High',
DefaultParameterSetName = 'Transfer'
)]
Param (
[parameter(Position=1,Mandatory = 'True',ValueFromPipeline = 'True',
HelpMessage='Enter the Fully Qualified Domain Name of the Domain Controller')]
[ValidateCount(1,1)]
[string[]]$DomainController,
[parameter(Position=2,Mandatory = 'True',
HelpMessage = "InfrastructureRole,NamingRole,PdcRole,RidRole,SchemaRole")]
[Alias('fsmo','fsmorole')]
[ValidateSet('InfrastructureRole','NamingRole','PdcRole','RidRole','SchemaRole')]
[ValidateCount(1,5)]
[string[]]$Role,
[parameter(Position=4,ParameterSetName='Transfer')]
[Switch]$Transfer,
[parameter(Position=4,ParameterSetName='Seize')]
[Switch]$Seize,
[parameter(Position=5)]
[switch]$PassThru
)
Begin {}
Process {
Try {
Write-Verbose "Connecting to Forest"
$forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest()
Write-Verbose "Locating $DomainController"
$dc = $forest.domains | ForEach {
$_.Domaincontrollers | Where {
$_.Name -eq $DomainController
}
}
}
Catch {
Write-Warning "$($Error)"
Break
}
If (-NOT [string]::IsNullOrEmpty($dc)) {
ForEach ($r in $role) {
Switch ($PScmdlet.ParameterSetName) {
"Transfer" {
Write-Verbose "Beginning transfer of $r to $DomainController"
If ($PScmdlet.ShouldProcess("$DomainController","Transfer Role: $($Role)")) {
Try {
$dc.TransferRoleOwnership($r)
}
Catch {
Write-Warning "$($Error[0])"
Break
}
}
}
"Seize" {
Write-Warning "Performing this action is irreversible!`nThe Domain Controller that originally holds this role should be rebuilt to avoid issues on the domain!"
Write-Verbose "Seizing $r and placing on $DomainController"
If ($PScmdlet.ShouldProcess("$DomainController","Seize Role: $($Role)")) {
Try {
$dc.SeizeRoleOwnership($r)
}
Catch {
Write-Warning "$($Error[0])"
Break
}
}
}
Default {
Write-Warning "You must specify either -Transfer or -Seize!"
Break
}
}
}
}
Else {
Write-Warning "Unable to locate $DomainController!"
Break
}
}
End {
If ($PSBoundParameters['PassThru']) {
$forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest()
ForEach ($domain in $forest.domains) {
$forestproperties = @{
Forest = $Forest.name
Domain = $domain.name
SchemaRole = $forest.SchemaRoleOwner
NamingRole = $forest.NamingRoleOwner
RidRole = $Domain.RidRoleOwner
PdcRole = $Domain.PdcRoleOwner
InfrastructureRole = $Domain.InfrastructureRoleOwner
}
$newobject = New-Object PSObject -Property $forestproperties
$newobject.PSTypeNames.Insert(0,"ForestRoles")
$newobject
}
}
}
}
|
PowerShellCorpus/PoshCode/pscp & spaces.ps1
|
pscp & spaces.ps1
|
Script
set-psdebug -trace 2
$sftp = "c:\\bin\\pscp.exe"
$sftpusername = "username"
$sftppassword = "password"
$sftphost = "sftp.host.com"
$sftpdestination = "`"`/Test Test`/`""
[Array]$sftpArgs = "-sftp", "-v", "-l", "$sftpusername", "-pw", "$sftppassword", "c:\\calinstall.log", "$sftphost`:$sftpdestination";
"args: $sftpArgs"
"host: $sftphost"
"destination: $sftpdestination"
"$sftp $sftpArgs"
& $sftp $sftpArgs
set-psdebug -trace 0
Output:
>.\\poshpscp.ps1
DEBUG: 2+ $sftp = <<<< "c:\\bin\\pscp.exe"
DEBUG: ! SET $sftp = 'c:\\bin\\pscp.exe'.
DEBUG: 3+ $sftpusername = <<<< "username"
DEBUG: ! SET $sftpusername = 'username'.
DEBUG: 4+ $sftppassword = <<<< "password"
DEBUG: ! SET $sftppassword = 'password'.
DEBUG: 5+ $sftphost = <<<< "sftp.host.com"
DEBUG: ! SET $sftphost = 'sftp.host.com'.
DEBUG: 6+ $sftpdestination = <<<< "`"`/Test Test`/`""
DEBUG: ! SET $sftpdestination = '"/Test Test/"'.
DEBUG: 7+ [Array]$sftpArgs = <<<< "-sftp", "-v", "-l", "$sftpusername", "-pw", "$sftppassword",
"c:\\calinstall.log", "$sftphost`:$sftpdestination";
DEBUG: ! SET $sftpArgs = '-sftp -v -l username -pw password c:\\calinstall.log ...'.
DEBUG: 8+ "args: $sftpArgs" <<<<
@@args: -sftp -v -l username -pw password c:\\calinstall.log sftp.host.com:"/Test Test/"
DEBUG: 9+ "host: $sftphost" <<<<
host: sftp.host.com
DEBUG: 10+ "destination: $sftpdestination" <<<<
destination: "/Test Test/"
DEBUG: 11+ "$sftp $sftpArgs" <<<<
@@c:\\bin\\pscp.exe -sftp -v -l username -pw password c:\\calinstall.log sftp.host.com:"/Test Test/"
DEBUG: 12+ <<<< & $sftp $sftpArgs
@@More than one remote source not supported
DEBUG: 13+ <<<< set-psdebug -trace 0
Running same command manually...
>set-psdebug -trace 2
DEBUG: 2+ $foundSuggestion = <<<< $false
DEBUG: ! SET $foundSuggestion = 'False'.
DEBUG: 4+ if <<<< ($lastError -and
DEBUG: 15+ $foundSuggestion <<<<
@@>pscp -v -sftp -l username -pw password c:\\calinstall.log sftp.host.com:"/Test Test/"
DEBUG: 1+ <<<< pscp -v -sftp -l username -pw password c:\\calinstall.log sftp.host.com:"/Test
Test/"
Looking up host "sftp.host.com"
Connecting to 216.57.210.200 port 22
[[ctrl+c]]
DEBUG: 2+ $foundSuggestion = <<<< $false
DEBUG: ! SET $foundSuggestion = 'False'.
DEBUG: 4+ if <<<< ($lastError -and
DEBUG: 15+ $foundSuggestion <<<<
>
|
PowerShellCorpus/PoshCode/Join-Objects 2.1.ps1
|
Join-Objects 2.1.ps1
|
#function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(Position=1)]
$Second
,
[Parameter(ValueFromPipeline=$true)]
$InputObject
)
BEGIN {
if($First -isnot [ScriptBlock]) {
$Out1 = $First
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
}
Process {
if($First -is [ScriptBlock]){
$Out1 = $InputObject | &$First
[string[]] $p1 = $Out1 | gm -type Properties | select -expand Name
}
$Output = $Out1 | Select $p1
if($Second -is [ScriptBlock]) {
$Out2 = $InputObject | &$Second
} elseif(!$Second) {
$Out2 = $InputObject
} else {
$Out2 = $Second
}
foreach($p in $Out2 | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Out2.($p)
}
$Output
}
#}
|
PowerShellCorpus/PoshCode/Get-HtmlHelp.ps1
|
Get-HtmlHelp.ps1
|
Google is now using business reviews to determine business ranking. A search for your business shows at least one negative review.
We can help you.
www.CrushYourCompetition.com EMAIL@CRUSHYOURCOMPETITION.COM Phone: USA (+1) 3614443559
How does posting positive reviews help in your businesses Google ranking?
1. Positive reviews increase your business rank by linking important and relevant websites to your website.
2. A constant stream of positive reviews improves your online reputation.
3. Positive reviews drive traffic to your business.
4. Positive reviews restore a tarnished reputation by pushing down negative reviews and links.
5. Helps protect against competitors or anyone else from attempting to ruin your ranking.
www.CrushYourCompetition.com EMAIL@CRUSHYOURCOMPETITION.COM Phone: USA (+1) 3614443559
Tired of review sites? Hire us to knock them off the front page of Google under your search term.
Our company has been in the business of taking over the first page of google for our clients for 8 years and knocking off complaint sites. We can do the same for your company and review sites.
We will create special websites and blogs and link them to the 15 thousand websites we already have. These websites will knock the review sites away and replace them with content you control.
I offer cheap link Posting,
forum posting and Review Posting Service
Review Posting Packages are on the website starting at 29.95
200 links/month to your website = $40/month
200+ forum posts/month = $50/month
500+ links/month = $150/month
500+ posts/month = $180/month
www.CrushYourCompetition.com EMAIL@CRUSHYOURCOMPETITION.COMPhone: USA (+1) 3614443559
|
PowerShellCorpus/PoshCode/Get-ProfilesList.ps1
|
Get-ProfilesList.ps1
|
function Get-ProfilesList {
$hive = "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList"
gci $hive | % -b {$prof = @()} -p {$dest = "" | select UserName, Sid, ProfilePath
$dest.Sid = $_.PSChildName
$dest.ProfilePath = (gp ($hive + "\\" + $_.PSChildName)).ProfileImagePath
$dest.UserName = Split-Path $dest.ProfilePath -leaf
$prof += $dest
} -end {$prof}
}
|
PowerShellCorpus/PoshCode/Is-SameSubnet.ps1
|
Is-SameSubnet.ps1
|
function Is-SameSubnet {param( [string]$IP1,
[string]$IP2,
[string]$Subnet = "255.255.255.0")
[string]$IP1Bits = ""
[string]$IP2Bits = ""
[string]$SubnetBits = ""
## get string representations of all the bits from the IP's passed in
[System.Net.IPAddress]::Parse($IP1).GetAddressBytes() |
ForEach-Object {
$Bits = [Convert]::ToString($_, 2)
## pad bit values with leading zeroes if less than 8 characters
$IP1Bits += $Bits.Insert(0, "0"*(8-$Bits.Length))
}
[System.Net.IPAddress]::Parse($IP2).GetAddressBytes() |
ForEach-Object {
$Bits = [Convert]::ToString($_, 2)
## pad bit values with leading zeroes if less than 8 characters
$IP2Bits += $Bits.Insert(0, "0"*(8-$Bits.Length))
}
[System.Net.IPAddress]::Parse($Subnet).GetAddressBytes() |
ForEach-Object {
$Bits = [Convert]::ToString($_, 2)
## pad bit values with leading zeroes if less than 8 characters
$SubnetBits += $Bits.Insert(0, "0"*(8-$Bits.Length))
}
## subnets must always begin with all bits in the first octet turned on
if ($SubnetBits.StartsWith("11111111") -eq $FALSE) {return $FALSE}
$BitPos = 0
do {
## compare the bits in the current position of the two IP's
$Compare = [Convert]::ToInt32($IP1Bits.Substring($BitPos, 1)) -eq [Convert]::ToInt32($IP2Bits.Substring($BitPos, 1))
## convert that into a string (will be either '0' or '1')
$Compare = [Convert]::ToString([Convert]::ToInt32($Compare))
[string]$SubnetBit = $SubnetBits.Substring($BitPos, 1)
if ($SubnetBit -eq "1") {
if ($Compare -eq $SubnetBit) {$BitPos++} else {return $FALSE}
} else {break}
} until ($BitPos -eq $IP1Bits.Length)
return $TRUE
}
|
PowerShellCorpus/PoshCode/Excel-LoadFile.ps1
|
Excel-LoadFile.ps1
|
# $Excel = New-Object -ComObject Excel.Application
Function Excel-LoadFile {
Param (
$SourceFile,
$ExcelObject
)
#$excel.visible = $true # Makes Excel document visible on the screen
$Workbook = $ExcelObject.Workbooks.Open($SourceFile)
$Worksheets = $Workbook.Worksheets
$Worksheet = $Workbook.Worksheets.Item(1)
return $Worksheet
}
Function Excel-RowCount {
Param ($Worksheet)
$range = $Worksheet.UsedRange
$rows = $range.Rows.Count
$rows = $rows - 2
return $rows
}
Function Excel-ColumnCount {
Param ($Worksheet)
$range = $Worksheet.UsedRange
$columns = $range.Columns.Count
return $columns
}
Function Excel-ReadHeader {
Param ($Worksheet)
$Headers =@{}
$column = 1
Do {
$Header = $Worksheet.cells.item(3,$column).text
If ($Header) {
$Headers.add($Header, $column)
$column++
}
} until (!$Header)
$Headers
}
Function Excel-CloseFile {
Param($ExcelObject)
$ExcelProcess = Get-Process Excel
$ExcelProcess | ForEach { Stop-Process ( $_.id ) }
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelObject) | Out-Null
}
|
PowerShellCorpus/PoshCode/Lead Systems Engineer_1.ps1
|
Lead Systems Engineer_1.ps1
|
<#
Author: Matt Schmitt
Date: 11/28/12
Version: 1.0
From: USA
Email: ithink2020@gmail.com
Website: http://about.me/schmittmatt
Twitter: @MatthewASchmitt
Description
A script for forwarding and unforwarding email for users in Office 365.
#>
Import-Module ActiveDirectory
Write-Host ""
Write-Host "PowerShell AD Password Tool"
Write-Host ""
Write-Host "This tool displays the Exparation Date of a user's Password and thier Lockedout"
Write-Host "Status. It will then allow you to unlock and/or reset the password."
Write-Host ""
Write-Host ""
#Counts how many locked account there are on the local DC and sets it to $count
$count = Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Measure-Object | Select-Object -expand Count
#If there are locked accounts (other than Administrator and Guest), then this will display who is locked out.
If ( $count -gt 0 ) {
Write-Host "Current Locked Out Accounts on your LOCAL Domain Controller:"
Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Select-Object SamAccountName, LastLogonDate | Format-Table -AutoSize
}else{
# Write-Host "There are no locked out accounts on your local Domain Controller."
}
Write-Host ""
#Asks for the username
$user = Read-Host "Enter username of the employee you would like to check or [ Ctrl+c ] to exit"
Write-Host ""
Write-Host ""
[datetime]$today = (get-date)
#Get pwdlastset date from AD and set it to $passdate
$searcher=New-Object DirectoryServices.DirectorySearcher
$searcher.Filter="(&(samaccountname=$user))"
$results=$searcher.findone()
$passdate = [datetime]::fromfiletime($results.properties.pwdlastset[0])
#Set password Age to $PwdAge
$PwdAge = ($today - $passdate).Days
If ($PwdAge -gt 90){
Write-Host "Password for $user is EXPIRED!"
Write-Host "Password for $user is $PwdAge days old."
}else{
Write-Host "Password for $user is $PwdAge days old."
}
Write-Host ""
Write-Host ""
Write-Host "Checking LockedOut Status on defined Domain Controllers:"
#Get Lockedout status and display
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
switch (Get-ADUser -server DC01.your.domain.com -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"DC01: Not Locked"} "True" {"DC01: LOCKED"}}
switch (Get-ADUser -server DC02.your.domain.com -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"DC02: Not Locked"} "True" {"DC02: LOCKED"}}
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
Write-Host ""
Write-Host ""
[int]$y = 0
$option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, (3) Unlock and reset user's password or (4) Exit?"
cls
While ($y -eq 0) {
switch ($option)
{
"1" {
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Write-Host "Unlocking account on DC01"
Unlock-ADAccount -Identity $user -server DC01.your.domain.com
Write-Host "Unlocking account on DC02"
Unlock-ADAccount -Identity $user -server DC02.your.domain.com
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
#Get Lockedout status and set it to $Lock
$Lock = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout)
Write-Host ""
#Depending on Status, tell user if the account is locked or not.
switch ($Lock)
{
"False" { Write-Host "$user is unlocked." }
"True" { Write-Host "$user is LOCKED Out." }
}
Write-Host ""
Write-Host "Press any key to Exit."
$y += 1
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
"2" {
$newpass = (Read-Host -AsSecureString "Enter user's New Password")
Write-Host ""
Write-Host "Resetting Password on local DC..."
Write-Host ""
Set-ADAccountPassword -Identity $user -NewPassword $newpass
Write-Host ""
Write-Host "Resetting Password on DC02"
Write-Host ""
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Set-ADAccountPassword -Server DC02.your.domain.com -Identity $user -NewPassword $newpass
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
Write-Host ""
Write-Host "Press any key to Exit."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$y += 1
}
"3" {
$newpass = (Read-Host -AsSecureString "Enter user's New Password")
Write-Host ""
Write-Host "Resetting Password on Local DC..."
Write-Host ""
Set-ADAccountPassword -Identity $user -NewPassword $newpass
Write-Host ""
Write-Host "Resetting Password on DC02"
Write-Host ""
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Set-ADAccountPassword -Server DC02.your.domain.com -Identity $user -NewPassword $newpass
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
Write-Host ""
Write-Host "Password for $user has been reset."
Write-Host ""
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Write-Host "Unlocking account on DC01"
Unlock-ADAccount -Identity $user -server DC01.your.domain.com
Write-Host "Unlocking account on DC02"
Unlock-ADAccount -Identity $user -server DC02.your.domain.com
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
#Get Lockedout status and set it to $Lock
$Lock = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout)
Write-Host ""
#Depending on Status, tell user if the account is locked or not.
switch ($Lock)
{
"False" { Write-Host "$user is unlocked." }
"True" { Write-Host "$user is LOCKED Out." }
}
Write-Host ""
Write-Host "Press any key to Exit."
$y += 1
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
"4" {
#exit code
$y += 1
}
default {
Write-Host "You have entered and incorrect number."
Write-Host ""
$option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, (3) Unlock and reset user's password or (4) Exit?"
}
}
}
|
PowerShellCorpus/PoshCode/Import-Iis-Log.ps1
|
Import-Iis-Log.ps1
|
param
(
[Parameter(
Mandatory=$true,
Position = 0,
ValueFromPipeline=$true,
HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log."
)]
[ValidateNotNullOrEmpty()]
[string]
$Path,
[Parameter(
Position = 1,
HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar."
)]
[ValidateNotNullOrEmpty()]
[string]
$Delimiter = " ",
[Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")]
[Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]
$Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8
)
begin
{
$fieldNames = @()
$output = New-Object Object
Add-Member -InputObject $output -MemberType NoteProperty -Name "DateTime" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ClientHost" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "UserName" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Service" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Machine" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerIp" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerPort" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Method" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ScriptPath" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "QueryString" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceStatus" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceSubStatus" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Win32Status" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesSent" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesRecived" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ProcessingTime" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ProtocolVersion" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Host" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "UserAgent" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Cookie" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Referer" -Value $null
}
process
{
foreach($line in Get-Content -Path $Path -Encoding $Encoding)
{
if($line.StartsWith("#Fields: "))
{
$fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter));
}
elseif(-not $line.StartsWith("#"))
{
$fieldValues = @($line.Split($Delimiter));
for($i = 0; $i -lt $fieldValues.Length; $i++)
{
$name = $fieldNames[$i]
$value = $fieldValues[$i]
switch($name)
{
"date" { $output.DateTime = [DateTime]::Parse($value) }
"time" { $output.DateTime += [TimeSpan]::Parse($value) }
"c-ip" { $output.ClientHost = [System.Net.IPAddress]::Parse($value) }
"cs-username" { $output.UserName = if($value -eq '-') { $null } else { $value } }
"s-sitename" { $output.Service = $value }
"s-computername" { $output.Machine = $value }
"s-ip" { $output.ServerIp = [System.Net.IPAddress]::Parse($value) }
"s-port" { $output.ServerPort = [int]$value }
"cs-method" { $output.Method = $value }
"cs-uri-stem" { $output.ScriptPath = [System.Web.HttpUtility]::UrlDecode($value) }
"cs-uri-query" { $output.QueryString = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } }
"sc-status" { $output.ServiceStatus = [int]$value }
"sc-substatus" { $output.ServiceSubStatus = [int]$value }
"sc-win32-status" { $output.Win32Status = [BitConverter]::ToInt32([BitConverter]::GetBytes([UInt32]($value)), 0) }
"sc-bytes" { $output.BytesSent = [UInt64]$value }
"cs-bytes" { $output.BytesRecived = [UInt64]$value }
"time-taken" { $output.ProcessingTime = [int]$value }
"cs-version" { $output.ProtocolVersion = $value }
"cs-host" { $output.Host = if($value -eq '-') { $null } else { $value } }
"cs(User-Agent)" { $output.UserAgent = if($value -eq '-') { $null } else { $value } }
"cs(Cookie)" { $output.Cookie = if($value -eq '-') { $null } else { $value } }
"cs(Referer)" { $output.Referer = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } }
}
}
Write-Output $output
}
}
}
|
PowerShellCorpus/PoshCode/Remote WSUS Settings.ps1
|
Remote WSUS Settings.ps1
|
$WSUSREGALL = @()
[String]$File = "C:\\server.txt"
$Servers = Get-Content $File
ForEach($Server In $Servers)
{
$Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Server)
$RegKey0 = $Registry.OpenSubKey("Software\\policies\\Microsoft\\Windows\\WindowsUpdate\\" )
$RegKey1 = $Registry.OpenSubKey("Software\\policies\\Microsoft\\Windows\\WindowsUpdate\\AU\\")
$WSUSREG = New-Object System.Object
$WSUSREG | Add-Member -MemberType NoteProperty -Name "Server" -Value $Server
$WSUSREG | Add-Member -MemberType NoteProperty -Name WUServer -Value $RegKey0.GetValue("WUServer")
$WSUSREG | Add-Member -MemberType NoteProperty -Name WUStatusServer -Value $RegKey0.GetValue("WUStatusServer")
$WSUSREG | Add-Member -MemberType NoteProperty -Name TargetGroupEnabled -Value $RegKey0.GetValue("TargetGroupEnabled")
$WSUSREG | Add-Member -MemberType NoteProperty -Name AcceptTrustedPublisherCerts -Value $RegKey0.GetValue("AcceptTrustedPublisherCerts")
$WSUSREG | Add-Member -MemberType NoteProperty -Name AUOptions -Value $RegKey1.GetValue("AUOptions")
$WSUSREG | Add-Member -MemberType NoteProperty -Name NoAutoUpdate -Value $RegKey1.GetValue("NoAutoUpdate")
$WSUSREG | Add-Member -MemberType NoteProperty -Name NoAUShutdownOption -Value $RegKey1.GetValue("NoAUShutdownOption")
$WSUSREG | Add-Member -MemberType NoteProperty -Name NoAUAsDefaultShutdownOption -Value $RegKey1.GetValue("NoAUAsDefaultShutdownOption")
$WSUSREG | Add-Member -MemberType NoteProperty -Name ScheduledInstallDay -Value $RegKey1.GetValue("ScheduledInstallDay")
$WSUSREG | Add-Member -MemberType NoteProperty -Name ScheduledInstallTime -Value $RegKey1.GetValue("ScheduledInstallTime")
$WSUSREG | Add-Member -MemberType NoteProperty -Name UseWUServer -Value $RegKey1.GetValue("UseWUServer")
$WSUSREG | Add-Member -MemberType NoteProperty -Name RescheduleWaitTimeEnabled -Value $RegKey1.GetValue("RescheduleWaitTimeEnabled")
$WSUSREG | Add-Member -MemberType NoteProperty -Name RescheduleWaitTime -Value $RegKey1.GetValue("RescheduleWaitTime")
$WSUSREG | Add-Member -MemberType NoteProperty -Name NoAutoRebootWithLoggedOnUsers -Value $RegKey1.GetValue("NoAutoRebootWithLoggedOnUsers")
$WSUSREG | Add-Member -MemberType NoteProperty -Name DetectionFrequencyEnabled -Value $RegKey1.GetValue("DetectionFrequencyEnabled")
$WSUSREG | Add-Member -MemberType NoteProperty -Name DetectionFrequency -Value $RegKey1.GetValue("DetectionFrequency")
$WSUSREG | Add-Member -MemberType NoteProperty -Name AutoInstallMinorUpdates -Value $RegKey1.GetValue("AutoInstallMinorUpdates")
$WSUSREG | Add-Member -MemberType NoteProperty -Name RebootWarningTimeoutEnabled -Value $RegKey1.GetValue("RebootWarningTimeoutEnabled")
$WSUSREG | Add-Member -MemberType NoteProperty -Name RebootWarningTimeout -Value $RegKey1.GetValue("RebootWarningTimeout")
$WSUSREG | Add-Member -MemberType NoteProperty -Name RebootRelaunchTimeoutEnabled -Value $RegKey1.GetValue("RebootRelaunchTimeoutEnabled")
$WSUSREG | Add-Member -MemberType NoteProperty -Name RebootRelaunchTimeout -Value $RegKey1.GetValue("RebootRelaunchTimeout")
$WSUSREG | Add-Member -MemberType NoteProperty -Name IncludeRecommendedUpdates -Value $RegKey1.GetValue("IncludeRecommendedUpdates")
$WSUSREG | Add-Member -MemberType NoteProperty -Name AUPowerManagement -Value $RegKey1.GetValue("AUPowerManagement")
$WSUSREGALL += $WSUSREG
}
$WSUSREGALL
$WSUSREGALL | Export-Csv "C:\\DataWSUS.csv" -NoTypeInformation
|
PowerShellCorpus/PoshCode/Get KB-articles of SP1.ps1
|
Get KB-articles of SP1.ps1
|
function Get-Sp1Articles()
{
$web = New-Object System.Net.WebClient
# Microsoft XLS-Datei über google herunterladen, damit kommt die XLS-Datei als in HTML konvertierte Datei
$html = $web.DownloadString(‘http://webcache.googleusercontent.com/search?q=cache:trZowCK8jvcJ:download.microsoft.com/download/8/B/3/8B37425B-AB6E-4C9C-9361-ECC15771BC5C/Hotfixes%2520and%2520Security%2520Updates%2520included%2520in%2520Windows%25207%2520and%2520Windows%2520Server%25202008%2520R2%2520Service%2520Pack%25201.xls’)
# zuerst den Google Header und das unnötige Blabla wegbekommen
$html = $html.Substring($html.IndexOf("KBTitle"))
# jetzt das nächste <tr> finden
$html = $html.Substring($html.IndexOf("<tr"))
# einzelne Zeile mit KB-Eintrag erkennen
$regex = ‘<tr([\\s\\S]*?)</tr>’
# HTML in Objektauflistung überführen
($html |Select-String -Pattern $regex -AllMatches).matches |foreach {
# durch überführen in ein XML-Objekt läßt sich die Zeile leichter verarbeiten
[xml]$tmp = $_
# neues Objekt erzeugen, dem die 4 wichtigen Eigenschaften zugeordnet werden, wenn eine KB-Nummer eingetragen ist
if ($tmp.tr.td[0].font.’#text’ -gt 0)
{
$obj = New-Object psobject
$obj |Add-Member -MemberType NoteProperty -Name KBArticle -Value $tmp.tr.td[0].font.’#text’
$obj |Add-Member -MemberType NoteProperty -Name Classification -Value $tmp.tr.td[1].font.’#text’
$obj |Add-Member -MemberType NoteProperty -Name KBTitle -Value $tmp.tr.td[2].font.’#text’
$obj |Add-Member -MemberType NoteProperty -Name Link -Value $tmp.tr.td[3].a.href
$obj
}
}
}
|
PowerShellCorpus/PoshCode/Publish-File.ps1
|
Publish-File.ps1
|
# Note that this version will not descend directories.
function Publish-File {
param (
[parameter( Mandatory = $true, HelpMessage="URL pointing to a SharePoint document library (omit the '/forms/default.aspx' portion)." )]
[System.Uri]$Url,
[parameter( Mandatory = $true, ValueFromPipeline = $true, HelpMessage="One or more files to publish. Use 'dir' to produce correct object type." )]
[System.IO.FileInfo[]]$FileName,
[system.Management.Automation.PSCredential]$Credential
)
$wc = new-object System.Net.WebClient
if ( $Credential ) { $wc.Credentials = $Credential }
else { $wc.UseDefaultCredentials = $true }
$FileName | ForEach-Object {
$DestUrl = "{0}{1}{2}" -f $Url.ToString().TrimEnd("/"), "/", $_.Name
Write-Verbose "$( get-date -f s ): Uploading file: $_"
$wc.UploadFile( $DestUrl , "PUT", $_.FullName )
Write-Verbose "$( get-date -f s ): Upload completed"
}
}
# Example:
# dir c:\\path\\files* | Publish-File -Url "https://mysharepointsite.com/personal/userID/Personal%20Documents"
|
PowerShellCorpus/PoshCode/IIS FTP Site Creation.ps1
|
IIS FTP Site Creation.ps1
|
" -------------------------------------------"
" ## FTP VIRTUAL DIRECTORY CREATION SCRIPT ##"
""
""
" ## This script will create a new username, password, local directory, and virtual directory for a client "
""
" ## Please enter the following information "
""
" -------------------------------------------"
### PowerShell Script
### Create local User Acount
$AccountName = Read-Host "Please enter user account name (i.e. krisp)"
$FullName = Read-Host "Please enter the full name (i.e. Kris)"
$Description = Read-Host "Please enter the description (i.e. Krisp FTP Login)"
$Password = Read-Host "Please enter a password"
$Computer = "FTPSERVER"
"Creating user on $Computer"
# Access to Container using the COM library
$Container = [ADSI] "WinNT://$Computer"
# Create User
$objUser = $Container.Create("user", $Accountname)
$objUser.Put("Fullname", $FullName)
$objUser.Put("Description", $Description)
# Set Password
$objUser.SetPassword($Password)
# Save Changes
$objUser.SetInfo()
# Add User Flags
# The numbers are bitwise - 65536 is Password Never Expires ; 64 is User Cannot Change Password
$objUser.userflags = 65536 -bor 64
$objUser.SetInfo()
"User $AccountName created!"
" ------------------------"
# ---Create FTP local directory---
"Creating directory D:\\FTP\\$AccountName"
New-Item D:\\FTP\\$AccountName -type directory
Start-Sleep -Seconds 5
"Directory $AccountName created!"
" ------------------------"
# ---Set Permissions on Folder
"Setting Permissions on D:\\FTP\\$AccountName"
$colRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$Inherit = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$Propagate = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$User = New-Object System.Security.Principal.NTAccount("$Computer\\$AccountName")
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($User, $colRights , $Inherit, $Propagate, $objType)
$objACL = Get-Acl "D:\\FTP\\$AccountName"
$objACL.AddAccessRule($objACE)
Set-Acl "D:\\FTP\\$AccountName" $objACL
Start-Sleep -Seconds 5
"Permissions Successfully Applied!"
" ------------------------"
# ---Add User to FTP Users Local Group
"Adding User to FTP Users Group"
$group = [ADSI]"WinNT://$computer/FTP Users"
$group.add("WinNT://$computer/$AccountName")
"User Added!"
"-------------------------"
# ---Create Temporary File with Username
$accountname | Out-File name.txt # <----IIS part won't take direct input, wants to read from file. Need to Research
# ---Create Virtual Directory in IIS---
"Creating virtual directory in IIS"
Start-Sleep -Seconds 5
foreach ($a in get-content name.txt)
{
$server = $env:computername
$service = New-Object System.DirectoryServices.DirectoryEntry("IIS://$server/MSFTPSVC")
$site = $service.psbase.children |Where-Object { $_.ServerComment -eq 'IntFTP' }
$site = New-Object System.DirectoryServices.DirectoryEntry($site.psbase.path+"/Root") for IIS 7.
$virtualdir = $site.psbase.children.Add("$a","IIsFtpVirtualDir")
$virtualdir.psbase.CommitChanges()
$virtualdir.put("Path","D:\\FTP\\$a")
$virtualdir.put("AccessRead",$true)
$virtualdir.put("AccessWrite",$true)
$virtualdir.psbase.CommitChanges()
$service.psbase.refreshCache() # OPTIONAL
}
"FTP site $AccountName created!"
" ------------------------"
|
PowerShellCorpus/PoshCode/Deploying VM with static.ps1
|
Deploying VM with static.ps1
|
$custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows -OrgName TestOrgName -FullName TestFullName -Workgroup TestWorkgroup
$custSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress 10.23.121.228 -SubnetMask 255.255.248.0 -Dns 10.23.108.1 -DefaultGateway 10.23.108.1
New-VM -Name MyDeployedVM -Template $template -VMHost $vmHost -OSCustomizationSpec $custSpec
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.