full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Set-PSObjectDefaultPrope.ps1
|
Set-PSObjectDefaultPrope.ps1
|
function Set-PSObjectDefaultProperties {
param(
[PSObject]$Object,
[string[]]$DefaultProperties
)
$name = $Object.PSObject.TypeNames[0]
$xml = "<?xml version='1.0' encoding='utf-8' ?><Types><Type>"
$xml += "<Name>$($name)</Name>"
$xml += "<Members><MemberSet><Name>PSStandardMembers</Name><Members>"
$xml += "<PropertySet><Name>DefaultDisplayPropertySet</Name><ReferencedProperties>"
foreach( $default in $DefaultProperties ) {
$xml += "<Name>$($default)</Name>"
}
$xml += "</ReferencedProperties></PropertySet></Members></MemberSet></Members>"
$xml += "</Type></Types>"
$file = "$($env:Temp)\\$name.ps1xml"
Out-File -FilePath $file -Encoding "UTF8" -InputObject $xml -Force
$typeLoaded = $host.Runspace.RunspaceConfiguration.Types | where { $_.FileName -eq $file }
if( $typeLoaded -ne $null ) {
Write-Host "Type Loaded"
Update-TypeData
}
else {
Update-TypeData $file
}
}
|
PowerShellCorpus/PoshCode/Get-Tomorrow.ps1
|
Get-Tomorrow.ps1
|
##############################################################################\n## Get-Tomorrow\n##\n## Get the date that represents tomorrow\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\nSet-StrictMode -Version Latest\n\nfunction GetDate\n{\n Get-Date\n}\n\n$tomorrow = (GetDate).AddDays(1)\n$tomorrow
|
PowerShellCorpus/PoshCode/Add-FormatTableIndexPara.ps1
|
Add-FormatTableIndexPara.ps1
|
##############################################################################\n##\n## Add-FormatTableIndexParameter\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nAdds a new -IncludeIndex switch parameter to the Format-Table command\nto help with array indexing.\n\n.NOTES\n\nThis commands builds on New-CommandWrapper, also included in the Windows\nPowerShell Cookbook.\n\n.EXAMPLE\n\nPS >$items = dir\nPS >$items | Format-Table -IncludeIndex\nPS >$items[4]\n\n#>\n\nSet-StrictMode -Version Latest\n\nNew-CommandWrapper Format-Table `\n -AddParameter @{\n @{\n Name = 'IncludeIndex';\n Attributes = "[Switch]"\n } = {\n\n function Add-IndexParameter {\n begin\n {\n $psIndex = 0\n }\n process\n {\n ## If this is the Format-Table header\n if($_.GetType().FullName -eq `\n "Microsoft.PowerShell.Commands.Internal." +\n "Format.FormatStartData")\n {\n ## Take the first column and create a copy of it\n $formatStartType =\n $_.shapeInfo.tableColumnInfoList[0].GetType()\n $clone =\n $formatStartType.GetConstructors()[0].Invoke($null)\n\n ## Add a PSIndex property\n $clone.PropertyName = "PSIndex"\n $clone.Width = $clone.PropertyName.Length\n\n ## And add its information to the header information\n $_.shapeInfo.tableColumnInfoList.Insert(0, $clone)\n }\n\n ## If this is a Format-Table entry\n if($_.GetType().FullName -eq `\n "Microsoft.PowerShell.Commands.Internal." +\n "Format.FormatEntryData")\n {\n ## Take the first property and create a copy of it\n $firstField =\n $_.formatEntryInfo.formatPropertyFieldList[0]\n $formatFieldType = $firstField.GetType()\n $clone =\n $formatFieldType.GetConstructors()[0].Invoke($null)\n\n ## Set the PSIndex property value\n $clone.PropertyValue = $psIndex\n $psIndex++\n\n ## And add its information to the entry information\n $_.formatEntryInfo.formatPropertyFieldList.Insert(\n 0, $clone)\n }\n\n $_\n }\n }\n\n $newPipeline = { __ORIGINAL_COMMAND__ | Add-IndexParameter }\n }\n}
|
PowerShellCorpus/PoshCode/NTFS Streams 1.0.ps1
|
NTFS Streams 1.0.ps1
|
#requires -version 2.0
## Version 1.0 - First release outside of the PoshCode module.
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
function Set-DownloadFlag {
<#
.Synopsis
Sets the ZoneTransfer flag which marks a file as being downloaded from the internet.
.Description
Creates a Zone.Identifier alternate data stream (on NTFS file systems) and writes the ZoneTransfer marker
.Parameter Path
The file you wish to block
.Parameter Passthru
If set, outputs the FileInfo object
.Parameter ZoneId
THe Zone you want to mark the file with. Defaults to 4
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$false)]
[ZoneIdentifier]$Zone = "Untrusted"
,
[Switch]$Passthru
)
PROCESS {
$FS = new-object NTFS.FileStreams($Path)
$null = $fs.add('Zone.Identifier')
$stream = $fs.Item('Zone.Identifier').open()
$sw = [System.IO.streamwriter]$stream
$Sw.writeline('[ZoneTransfer]')
$sw.writeline("ZoneID=$([Int]$zone)")
$sw.close()
$stream.close()
if($Passthru){ Get-ChildItem $Path }
}
}
function Remove-DownloadFlag {
<#
.Synopsis
Removes the ZoneTransfer flag which marks a file as being downloaded from the internet.
.Description
Deletes the Zone.Identifier alternate data stream (on NTFS file systems)
.Parameter Path
The file you wish to block
.Parameter Passthru
If set, outputs the FileInfo object
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Switch]$Passthru
)
PROCESS {
Remove-Stream -Path $Path -Name 'Zone.Identifier'
if($Passthru){ Get-ChildItem $Path }
}
}
function Get-DownloadFlag {
<#
.Synopsis
Verify whether the ZoneTransfer flag is set (marking this file as one downloaded from the internet).
.Description
Reads the Zone.Identifier alternate data stream (on NTFS file systems)
.Parameter Path
The file you wish to check the ZoneTransfer flag on
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
)
Process {
$FS = new-object NTFS.FileStreams($Path)
if(!$fs.Item('Zone.Identifier') ) {
Write-Warning "Zone.Identifier not set on $Path (no Download Flag). This is the equivalent of a 'Trusted' flag."
return
}
$reader = [System.IO.streamreader]$fs.Item('Zone.Identifier').open()
try {
do {
$line = $reader.ReadLine()
} until (!$line -OR $line -eq '[ZoneTransfer]')
$out = new-object PSObject
while($zone = $reader.ReadLine()) {
$zone = $zone -split "="
if($zone.Count -lt 2) { break }
Add-Member -in $out -Type NoteProperty -Name $zone[0] -value ([ZoneIdentifier]$zone[1])
}
$out
} finally {
$reader.close()
}
}
}
function Test-DownloadFlag {
<#
.Synopsis
Verify whether the ZoneTransfer flag is set (marking this file as one downloaded from the internet).
.Description
Reads the Zone.Identifier alternate data stream (on NTFS file systems)
.Parameter Path
The file you wish to check the ZoneTransfer flag on
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
)
Process {
Get-ChildItem $Path | Select Name, @{N="Downloaded";E={ [bool]((new-object NTFS.FileStreams($_)).Item('Zone.Identifier')) } }, FullName, Length
}
}
function Normalize-StreamName {
PARAM($Path,$StreamName)
if(!$StreamName -and !(Test-Path $Path -EA 0)) {
$Path, $Segment, $StreamName = $Path -split ":"
if($StreamName -or (Test-Path ($Path,$Segment -join ":") -EA 0)) {
$Path = $Path,$Segment -join ":"
} else {
$StreamName = $Segment
}
}
return $Path,$StreamName
}
function Get-Stream {
<#
.Synopsis
Get the list of alternate NTFS Streams
.Description
Reads the named alternate data stream on NTFS file systems.
.Parameter Path
The file you wish to read from. You may include the stream name in the format:
C:\\Path\\File.extension:stream name
.Parameter Stream
The name of the stream you wish to read from. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1,Mandatory=$false)]
[Alias("Name")][string]$StreamName
,
[Parameter()]
[Switch]$Force
)
Process {
$Path,$Stream = Normalize-StreamName $Path $StreamName
Write-Verbose "Path: $Path"
Write-Verbose "Stream: $Stream"
ForEach($file in Get-ChildItem $Path) {
$FS = new-object NTFS.FileStreams($file)
Write-Verbose "File: $File"
if(!$Stream) {
$FS
} else {
$FS | Where { $_.StreamName -like $Stream } | Tee -Var Output
if($Force -and -not $Output) {
$FS.add($Stream) > $null
$FS.Item($Stream)
}
}
}
}
}
function Get-StreamContent {
<#
.Synopsis
Get the contents of a named NTFS Stream
.Description
Reads the named alternate data stream (on NTFS file systems)
.Parameter StreamInfo
A StreamInfo object for the stream you want to get the content of.
.Parameter Path
The file to read from. You may include the stream name in the format:
C:\\Path\\File.extension:stream name
.Parameter StreamName
The name of the stream you wish to read from. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding(DefaultParameterSetName="ByStream")]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="ByName")]
[Alias("FullName")][string]$Path
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByStream")]
[NTFS.StreamInfo]$StreamInfo
,
[Parameter(Position=1, Mandatory=$false, ParameterSetName="ByName")]
[Alias("Name")][string]$StreamName
)
Process {
switch($PSCmdlet.ParameterSetName) {
"ByName" {
Get-Stream $Path $StreamName | Get-StreamContent
}
"ByStream" {
$fileStream = $StreamInfo.open()
$reader = [System.IO.StreamReader]$fileStream
$reader.ReadToEnd()
$fileStream.close()
}
}
}
}
function Remove-Stream {
<#
.Synopsis
Remove a stream from a file (or, delete the file).
.Description
Deletes the named alternate data stream (on NTFS file systems)
.Parameter StreamInfo
A StreamInfo object for the stream you want to get the content of.
.Parameter Path
The file to delete from. You may include the stream name in the format:
"C:\\Path\\File.extension:stream name"
.Parameter StreamName
The name of the stream you wish to remove. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding(DefaultParameterSetName="ByStream")]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="ByName")]
[Alias("FullName")][string]$Path
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByStream")]
[NTFS.StreamInfo]$StreamInfo
,
[Parameter(Position=1, Mandatory=$false, ParameterSetName="ByName")]
[Alias("Name")][string]$StreamName
)
Process {
switch($PSCmdlet.ParameterSetName) {
"ByName" {
foreach($StreamInfo in Get-Stream $Path $StreamName) {
Write-Verbose $($StreamInfo |Out-String)
$StreamInfo.Delete() > $null
}
}
"ByStream" {
$StreamInfo.Delete() > $null
}
}
}
}
function Set-StreamContent {
<#
.Synopsis
Set the contents of a named NTFS Stream
.Description
Sets the content of the named alternate data stream (on NTFS file systems)
.Parameter StreamInfo
A StreamInfo object for the stream you want to set the content of.
.Parameter Path
The file to set content on. You may include the stream name in the format:
"C:\\Path\\File.extension:stream name"
.Parameter StreamName
The name of the stream you wish to set. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding(DefaultParameterSetName="ByStream")]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="ByName")]
[Alias("FullName")][string]$Path
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByStream")]
[NTFS.StreamInfo]$StreamInfo
,
[Parameter(Position=1, Mandatory=$false, ParameterSetName="ByName")]
[Alias("Name")][string]$StreamName
,
[Parameter(Position=2, Mandatory=$true)]
[String]$Value
)
Process {
switch($PSCmdlet.ParameterSetName) {
"ByName" {
Write-Verbose "Path: $Path"
Get-Stream $Path $StreamName -Force | Set-StreamContent -Value $Value
}
"ByStream" {
$writer =[System.IO.streamwriter] $StreamInfo.Open()
$writer.Write($value)
$writer.close()
}
}
}
}
Add-Type -TypeDefinition @'
public enum ZoneIdentifier {
Trusted = 1,
Intranet = 2,
Internet = 3,
Untrusted = 4
}
'@
Add-Type -TypeDefinition @'
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
///<summary>
///Encapsulates access to alternative data streams of an NTFS file.
///Adapted from a C++ sample by Dino Esposito,
///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/ntfs5.asp
///</summary>
namespace NTFS {
/// <summary>
/// Wraps the API functions, structures and constants.
/// </summary>
internal class Kernel32
{
public const char STREAM_SEP = ':';
public const int INVALID_HANDLE_VALUE = -1;
public const int MAX_PATH = 256;
[Flags()] public enum FileFlags : uint
{
WriteThrough = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x8000000,
DeleteOnClose = 0x4000000,
BackupSemantics = 0x2000000,
PosixSemantics = 0x1000000,
OpenReparsePoint = 0x200000,
OpenNoRecall = 0x100000
}
[Flags()] public enum FileAccessAPI : uint
{
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000
}
/// <summary>
/// Provides a mapping between a System.IO.FileAccess value and a FileAccessAPI value.
/// </summary>
/// <param name="Access">The <see cref="System.IO.FileAccess"/> value to map.</param>
/// <returns>The <see cref="FileAccessAPI"/> value.</returns>
public static FileAccessAPI Access2API(FileAccess Access)
{
FileAccessAPI lRet = 0;
if ((Access & FileAccess.Read)==FileAccess.Read) lRet |= FileAccessAPI.GENERIC_READ;
if ((Access & FileAccess.Write)==FileAccess.Write) lRet |= FileAccessAPI.GENERIC_WRITE;
return lRet;
}
[StructLayout(LayoutKind.Sequential)] public struct LARGE_INTEGER
{
public int Low;
public int High;
public long ToInt64()
{
return (long)High * 4294967296 + (long)Low;
}
}
[StructLayout(LayoutKind.Sequential)] public struct WIN32_STREAM_ID
{
public int dwStreamID;
public int dwStreamAttributes;
public LARGE_INTEGER Length;
public int dwStreamNameLength;
}
[DllImport("kernel32")] public static extern SafeFileHandle CreateFile(string Name, FileAccessAPI Access, FileShare Share, int Security, FileMode Creation, FileFlags Flags, int Template);
[DllImport("kernel32")] public static extern bool DeleteFile(string Name);
[DllImport("kernel32")] public static extern bool CloseHandle(SafeFileHandle hObject);
[DllImport("kernel32")] public static extern bool BackupRead(SafeFileHandle hFile, IntPtr pBuffer, int lBytes, ref int lRead, bool bAbort, bool bSecurity, ref int Context);
[DllImport("kernel32")] public static extern bool BackupRead(SafeFileHandle hFile, ref WIN32_STREAM_ID pBuffer, int lBytes, ref int lRead, bool bAbort, bool bSecurity, ref int Context);
[DllImport("kernel32")] public static extern bool BackupSeek(SafeFileHandle hFile, int dwLowBytesToSeek, int dwHighBytesToSeek, ref int dwLow, ref int dwHigh, ref int Context);
}
/// <summary>
/// Encapsulates a single alternative data stream for a file.
/// </summary>
public class StreamInfo
{
private FileStreams _parent;
private string _name;
private long _length;
internal StreamInfo(FileStreams Parent, string Name, long Length)
{
_parent = Parent;
_name = Name;
_length = Length;
}
/// <summary>
/// The name of the file.
/// </summary>
public string FileName
{
get { return System.IO.Path.GetFileName(_parent.FileName); }
}
/// <summary>
/// The name of the stream.
/// </summary>
public string StreamName
{
get { return _name; }
}
/// <summary>
/// The length (in bytes) of the stream.
/// </summary>
public long Length
{
get { return _length; }
}
public override string ToString()
{
if(String.IsNullOrEmpty(_name)) {
return _parent.FileName;
} else {
return String.Format("{1}{0}{2}", Kernel32.STREAM_SEP, _parent.FileName, _name);
}
}
public override bool Equals(Object o)
{
if (o is StreamInfo)
{
StreamInfo f = (StreamInfo)o;
return (f._name.Equals(_name) && f._parent.Equals(_parent));
}
else if (o is string)
{
return ((string)o).Equals(ToString());
}
else
return base.Equals(o);
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
#region Open
/// <summary>
/// Opens or creates the stream in read-write mode, with no sharing.
/// </summary>
/// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns>
public FileStream Open()
{
return Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
/// <summary>
/// Opens or creates the stream in read-write mode with no sharing.
/// </summary>
/// <param name="Mode">The <see cref="System.IO.FileMode"/> action for the stream.</param>
/// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns>
public FileStream Open(FileMode Mode)
{
return Open(Mode, FileAccess.ReadWrite, FileShare.None);
}
/// <summary>
/// Opens or creates the stream with no sharing.
/// </summary>
/// <param name="Mode">The <see cref="System.IO.FileMode"/> action for the stream.</param>
/// <param name="Access">The <see cref="System.IO.FileAccess"/> level for the stream.</param>
/// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns>
public FileStream Open(FileMode Mode, FileAccess Access)
{
return Open(Mode, Access, FileShare.None);
}
/// <summary>
/// Opens or creates the stream.
/// </summary>
/// <param name="Mode">The <see cref="System.IO.FileMode"/> action for the stream.</param>
/// <param name="Access">The <see cref="System.IO.FileAccess"/> level for the stream.</param>
/// <param name="Share">The <see cref="System.IO.FileShare"/> level for the stream.</param>
/// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns>
public FileStream Open(FileMode Mode, FileAccess Access, FileShare Share)
{
try
{
if(String.IsNullOrEmpty(_name)) {
return new FileStream(ToString(), Mode, Access, Share);
} else {
SafeFileHandle hFile = Kernel32.CreateFile(ToString() + Kernel32.STREAM_SEP + "$DATA", Kernel32.Access2API(Access), Share, 0, Mode, 0, 0);
return new FileStream(hFile, Access);
}
}
catch
{
return null;
}
}
#endregion
#region Delete
/// <summary>
/// Deletes the stream from the file.
/// </summary>
/// <returns>A <see cref="System.Boolean"/> value: true if the stream was deleted, false if there was an error.</returns>
public bool Delete()
{
return Kernel32.DeleteFile(ToString());
}
#endregion
}
/// <summary>
/// Encapsulates the collection of alternative data streams for a file.
/// A collection of <see cref="StreamInfo"/> objects.
/// </summary>
public class FileStreams : CollectionBase
{
private FileInfo _file;
#region Constructors
public FileStreams(string File)
{
_file = new FileInfo(File);
initStreams();
}
public FileStreams(FileInfo file)
{
_file = file;
initStreams();
}
/// <summary>
/// Reads the streams from the file.
/// </summary>
private void initStreams()
{
base.List.Add(new StreamInfo(this,String.Empty,_file.Length));
//Open the file with backup semantics
SafeFileHandle hFile = Kernel32.CreateFile(_file.FullName, Kernel32.FileAccessAPI.GENERIC_READ, FileShare.Read, 0, FileMode.Open, Kernel32.FileFlags.BackupSemantics, 0);
if (hFile.IsInvalid) return;
try
{
Kernel32.WIN32_STREAM_ID sid = new Kernel32.WIN32_STREAM_ID();
int dwStreamHeaderLength = Marshal.SizeOf(sid);
int Context = 0;
bool Continue = true;
while (Continue)
{
//Read the next stream header
int lRead = 0;
Continue = Kernel32.BackupRead(hFile, ref sid, dwStreamHeaderLength, ref lRead, false, false, ref Context);
if (Continue && lRead == dwStreamHeaderLength)
{
if (sid.dwStreamNameLength>0)
{
//Read the stream name
lRead = 0;
IntPtr pName = Marshal.AllocHGlobal(sid.dwStreamNameLength);
try
{
Continue = Kernel32.BackupRead(hFile, pName, sid.dwStreamNameLength, ref lRead, false, false, ref Context);
char[] bName = new char[sid.dwStreamNameLength];
Marshal.Copy(pName,bName,0,sid.dwStreamNameLength);
//Name is of the format ":NAME:$DATA\\0"
string sName = new string(bName);
int i = sName.IndexOf(Kernel32.STREAM_SEP, 1);
if (i>-1) sName = sName.Substring(1, i-1);
else
{
//This should never happen.
//Truncate the name at the first null char.
i = sName.IndexOf('\\0');
if (i>-1) sName = sName.Substring(1, i-1);
}
//Add the stream to the collection
base.List.Add(new StreamInfo(this,sName,sid.Length.ToInt64()));
}
finally
{
Marshal.FreeHGlobal(pName);
}
}
//Skip the stream contents
int l = 0; int h = 0;
Continue = Kernel32.BackupSeek(hFile, sid.Length.Low, sid.Length.High, ref l, ref h, ref Context);
}
else break;
}
}
finally
{
Kernel32.CloseHandle(hFile);
}
}
#endregion
#region File
/// <summary>
/// Returns the <see cref="System.IO.FileInfo"/> object for the wrapped file.
/// </summary>
public FileInfo FileInfo
{
get { return _file; }
}
/// <summary>
/// Returns the full path to the wrapped file.
/// </summary>
public string FileName
{
get { return _file.FullName; }
}
/// <summary>
/// Returns the length of the main data stream, in bytes.
/// </summary>
public long Length {
get {return _file.Length;}
}
/// <summary>
/// Returns the length of all streams for the file, in bytes.
/// </summary>
public long FullLength
{
get
{ // don't initialize with "this.Length" anymore, because we include the default stream now
long length = 0;
foreach (StreamInfo s in this) length += s.Length;
return length;
}
}
#endregion
#region Open
/// <summary>
/// Opens or creates the default file stream.
/// </summary>
/// <returns><see cref="System.IO.FileStream"/></returns>
public FileStream Open()
{
return new FileStream(_file.FullName, FileMode.OpenOrCreate);
}
/// <summary>
/// Opens or creates the default file stream.
/// </summary>
/// <param name="Mode">The <see cref="System.IO.FileMode"/> for the stream.</param>
/// <returns><see cref="System.IO.FileStream"/></returns>
public FileStream Open(FileMode Mode)
{
return new FileStream(_file.FullName, Mode);
}
/// <summary>
/// Opens or creates the default file stream.
/// </summary>
/// <param name="Mode">The <see cref="System.IO.FileMode"/> for the stream.</param>
/// <param name="Access">The <see cref="System.IO.FileAccess"/> for the stream.</param>
/// <returns><see cref="System.IO.FileStream"/></returns>
public FileStream Open(FileMode Mode, FileAccess Access)
{
return new FileStream(_file.FullName, Mode, Access);
}
/// <summary>
/// Opens or creates the default file stream.
/// </summary>
/// <param name="Mode">The <see cref="System.IO.FileMode"/> for the stream.</param>
/// <param name="Access">The <see cref="System.IO.FileAccess"/> for the stream.</param>
/// <param name="Share">The <see cref="System.IO.FileShare"/> for the stream.</param>
/// <returns><see cref="System.IO.FileStream"/></returns>
public FileStream Open(FileMode Mode, FileAccess Access, FileShare Share)
{
return new FileStream(_file.FullName, Mode, Access, Share);
}
#endregion
#region Delete
/// <summary>
/// Deletes the file, and all alternative streams.
/// </summary>
public void Delete()
{
for (int i=base.List.Count;i>0;i--)
{
base.List.RemoveAt(i);
}
_file.Delete();
}
#endregion
#region Collection operations
/// <summary>
/// Add an alternative data stream to this file.
/// </summary>
/// <param name="Name">The name for the stream.</param>
/// <returns>The index of the new item.</returns>
public int Add(string Name)
{
StreamInfo FSI = new StreamInfo(this, Name, 0);
int i = base.List.IndexOf(FSI);
if (i==-1) i = base.List.Add(FSI);
return i;
}
/// <summary>
/// Removes the alternative data stream with the specified name.
/// </summary>
/// <param name="Name">The name of the string to remove.</param>
public void Remove(string Name)
{
StreamInfo FSI = new StreamInfo(this, Name, 0);
int i = base.List.IndexOf(FSI);
if (i>-1) base.List.RemoveAt(i);
}
/// <summary>
/// Returns the index of the specified <see cref="StreamInfo"/> object in the collection.
/// </summary>
/// <param name="FSI">The object to find.</param>
/// <returns>The index of the object, or -1.</returns>
public int IndexOf(StreamInfo FSI)
{
return base.List.IndexOf(FSI);
}
/// <summary>
/// Returns the index of the <see cref="StreamInfo"/> object with the specified name in the collection.
/// </summary>
/// <param name="Name">The name of the stream to find.</param>
/// <returns>The index of the stream, or -1.</returns>
public int IndexOf(string Name)
{
return base.List.IndexOf(new StreamInfo(this, Name, 0));
}
public StreamInfo this[int Index]
{
get { return (StreamInfo)base.List[Index]; }
}
public StreamInfo this[string Name]
{
get
{
int i = IndexOf(Name);
if (i==-1) return null;
else return (StreamInfo)base.List[i];
}
}
#endregion
#region Overrides
/// <summary>
/// Throws an exception if you try to add anything other than a StreamInfo object to the collection.
/// </summary>
protected override void OnInsert(int index, object value)
{
if (!(value is StreamInfo)) throw new InvalidCastException();
}
/// <summary>
/// Throws an exception if you try to add anything other than a StreamInfo object to the collection.
/// </summary>
protected override void OnSet(int index, object oldValue, object newValue)
{
if (!(newValue is StreamInfo)) throw new InvalidCastException();
}
/// <summary>
/// Deletes the stream from the file when you remove it from the list.
/// </summary>
protected override void OnRemoveComplete(int index, object value)
{
try
{
StreamInfo FSI = (StreamInfo)value;
if (FSI != null) FSI.Delete();
}
catch {}
}
public new StreamEnumerator GetEnumerator()
{
return new StreamEnumerator(this);
}
#endregion
#region StreamEnumerator
public class StreamEnumerator : object, IEnumerator
{
private IEnumerator baseEnumerator;
public StreamEnumerator(FileStreams mappings)
{
this.baseEnumerator = ((IEnumerable)(mappings)).GetEnumerator();
}
public StreamInfo Current
{
get
{
return ((StreamInfo)(baseEnumerator.Current));
}
}
object IEnumerator.Current
{
get
{
return baseEnumerator.Current;
}
}
public bool MoveNext()
{
return baseEnumerator.MoveNext();
}
bool IEnumerator.MoveNext()
{
return baseEnumerator.MoveNext();
}
public void Reset()
{
baseEnumerator.Reset();
}
void IEnumerator.Reset()
{
baseEnumerator.Reset();
}
}
#endregion
}
}
'@
Set-Alias block Set-DownloadFlag
Set-Alias unblock Remove-DownloadFlag
Export-ModuleMember -Function Remove-DownloadFlag, Set-DownloadFlag, Get-DownloadFlag, Test-DownloadFlag,
Get-Stream, Get-StreamContent, Remove-Stream, Set-StreamContent -alias block, unblock
|
PowerShellCorpus/PoshCode/Start-Encryption_1.ps1
|
Start-Encryption_1.ps1
|
## Start-Encryption
##################################################################################################
## Rijndael symmetric key encryption ... with no passes on the key. Very lazy.
## USAGE:
## $encrypted = Encrypt-String "Oisin Grehan is a genius" "P@ssw0rd"
## Decrypt-String $encrypted "P@ssw0rd"
##
## You can choose to return an array by passing -arrayOutput to Encrypt-String
## I chose to use Base64 encoded strings because they're easier to save ...
[Reflection.Assembly]::Load("System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
function Encrypt-String($String, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key", [switch]$arrayOutput)
{
$r = new-Object System.Security.Cryptography.RijndaelManaged
$pass = [Text.Encoding]::UTF8.GetBytes($Passphrase)
$salt = [Text.Encoding]::UTF8.GetBytes($salt)
$r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
$r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]
$c = $r.CreateEncryptor()
$ms = new-Object IO.MemoryStream
$cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write"
$sw = new-Object IO.StreamWriter $cs
$sw.Write($String)
$sw.Close()
$cs.Close()
$ms.Close()
$r.Clear()
[byte[]]$result = $ms.ToArray()
if($arrayOutput) {
return $result
} else {
return [Convert]::ToBase64String($result)
}
}
function Decrypt-String($Encrypted, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key")
{
if($Encrypted -is [string]){
$Encrypted = [Convert]::FromBase64String($Encrypted)
}
$r = new-Object System.Security.Cryptography.RijndaelManaged
$pass = [System.Text.Encoding]::UTF8.GetBytes($Passphrase)
$salt = [System.Text.Encoding]::UTF8.GetBytes($salt)
$r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
$r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]
$d = $r.CreateDecryptor()
$ms = new-Object IO.MemoryStream @(,$Encrypted)
$cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read"
$sr = new-Object IO.StreamReader $cs
Write-Output $sr.ReadToEnd()
$sr.Close()
$cs.Close()
$ms.Close()
$r.Clear()
}
|
PowerShellCorpus/PoshCode/Stop service and wait_1....ps1
|
Stop service and wait_1....ps1
|
<#
This script stops the service, then waits for the service to stop before continuing with the reboot/shutdown
The scritp can be pushed to a server/Pc using Group Policy or Registry or run manually.
The shutdown script Registry key is:
HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine\\Scripts\\Shutdown\\
#>
# type the name of the service in the quotes here
$ServiceName = 'Service Name'
Stop-Service $ServiceName
write-host $ServiceName'...' -NoNewLine
$TestService = Get-Service $Service | Select-Object 'Status'
While($TestService | where {$_.Status -eq 'Running'}){
Write-Host '.'-NoNewLine
Sleep 2
}
# If you want to shutdown the computer add the command "Shutdown /t 0" (without quoutes)onto the bottom line.
# If you want to Reboot the computer then add the command "Restart-computer" (without quotes) on the line below.
|
PowerShellCorpus/PoshCode/64d622dd-3de1-4904-8512-d2f40cde9914.ps1
|
64d622dd-3de1-4904-8512-d2f40cde9914.ps1
|
#This scripts compares the agents that are installed in two zones and
#gives the agents that are not common.
#Usage:
#Compare-Agents.ps1 -server1 RMSServer1.contoso.com -server2 RMSServer2.contoso.com -output c:\\Temp.txt
#RMSServer1 is the one whose agents are to be moved.
param([string] $Server1,$Server2,$output)
Function Mainone
{
write-host $Server1
write-host $Server2
$Temp1 = $Server1
$Temp2 = $Server2
$outfilepath = $output
New-Managementgroupconnection $Temp1
set-location monitoring:\\$Temp1
$AllServer1Agents = get-agent
$RMSServer1 = get-RootManagementServer
write-host "Got all the agents for the first group"
$RMS1name = $RMSServer1.Computername
$data1 = "All the agents on " + $RMS1name
New-Managementgroupconnection $Temp2
set-location monitoring:\\$Temp2
$AllServer2Agents = get-agent
$RMSServer2 = get-RootManagementServer
write-host "Got all the agents for the second group"
#Write-data $RMSServer.ManagementGroup.name
$RMS2name = $RMSServer2.Computername
$data2 = "All the agents on " + $RMS2name
#write-data $data2
#foreach($Agent in $AllServer2Agents) { write-data $Agent.computername}
write-host "Calling the function to compare Agents"
CheckAgent $AllServer1Agents $AllServer2Agents $RMS1name $RMS2name
}
Function CheckAgent($AllServer1Agents,$AllServer2Agents,$RMS1name,$RMS2name)
{
write-host "Calling function to get all agents in an array"
Get-Agentnames $AllServer1Agents $AllServer2Agents $RMS1name $RMS2name
}
Function Get-Agentnames($AllServer1Agents,$AllServer2Agents,$RMS1name,$RMS2name)
{
$Server1Agent = @()
$Server2Agent = @()
foreach($A in $AllServer1Agents)
{
$Server1Agent = $Server1Agent + $A.Computername
}
foreach($B in $AllServer2Agents)
{
$Server2Agent = $Server2Agent + $B.Computername
}
Compare-theAgents $Server1Agent $Server2Agent
}
function Compare-theAgents($Server1Agent,$Server2Agent)
{
$FoundAgent = @()
$NotFoundAgent = @()
for($i=0; $i -lt $Server1Agent.count; $i++)
{
$Temp1 = $Server1Agent[$i]
$Data = "Comparing element " + $Server1Agent[$i]
write-host $Data
for($j=0; $j -lt $Server2Agent.count; $j++)
{
$Temp2 = $Server2Agent[$j]
#write-host $Temp2
if($Temp1 -match $Temp2)
{
$FoundAgent = $FoundAgent + $Temp1
$Server1Agent[$i] = "Present"
}
}
}
for($k=0; $k -lt $Server1Agent.count; $k++)
{
if($Server1Agent[$k] -notmatch "Present")
{
$NotfoundAgent = $NotFoundAgent + $Server1Agent[$k]
}
}
write-data "These are the agents that are found common"
for($k=0;$k -lt $FoundAgent.count;$k++){write-data $FoundAgent[$k]}
write-data "These are the agents that are not found"
for($l=0;$l -lt $NotFoundAgent.count;$l++){write-data $NotFoundAgent[$l]}
}
function write-data($Writedata)
{
out-file -filepath $outfilepath -inputobject $Writedata -append -encoding ASCII
}
Mainone
|
PowerShellCorpus/PoshCode/Create random strings_1.ps1
|
Create random strings_1.ps1
|
# ===============================================================
# / Author: Marcus L. Farmer
# / Script: createRandomStrings.ps1
# / Date: 2-04-2009
# / Purpose: generate pseudorandomly generated strings for passwords or other uses
# / Usage: ./createRandomStrings.ps1
# / Reqs.: none
# / Output: text file containing output
# / Comments: none
# ===============================================================
function createRandomString($charset)
{
$lblResults.text = "Hello now!"
[string]$outputString = ""
for ($i=1; $i -lt ([int]$txtGenerateThisManyNumbers.text + 1); $i++)
{
$lblResults.text = "in the first loop enumerating i"
for ($x=1; $x -lt ([int]$txtLengthOfEachNumber.text + 1); $x++)
{
$lblResults.text = "in the second loop enumerating x"
$outputString = $outputString + $charset.substring((get-random $charset.length), 1)
}
# $lblResults.text = $outputString
Add-Content -Path $txtFileName.text -Value $outputString
$outputString = ""
}
$lblResults.text = "Your really cool and super randomly generated strings can be found in " + $txtFileName.text
}
$btnGenerateNumbers_OnClick=
{
#TODO: Place custom script here
createRandomString($txtCreateCharacterSet.Text)
}
$btnResetCharacterSet_OnClick=
{
#TODO: Place custom script here
$txtCreateCharacterSet.Text = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
}
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms v1.0.1.0
# Generated On: 2/3/2009 4:55 PM
# Generated By: Marcus L. Farmer
########################################################################
#region Import the Assembles
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$frmMain = New-Object System.Windows.Forms.Form
$btnGenerateNumbers = New-Object System.Windows.Forms.Button
$txtFileName = New-Object System.Windows.Forms.TextBox
$lblSaveAsFile = New-Object System.Windows.Forms.Label
$txtGenerateThisManyNumbers = New-Object System.Windows.Forms.TextBox
$lblGenerateThisManyNumbers = New-Object System.Windows.Forms.Label
$txtLengthOfEachNumber = New-Object System.Windows.Forms.TextBox
$lblLengthOfEachNumber = New-Object System.Windows.Forms.Label
$btnResetCharacterSet = New-Object System.Windows.Forms.Button
$txtCreateCharacterSet = New-Object System.Windows.Forms.TextBox
$lblCreateCharacterSet = New-Object System.Windows.Forms.Label
$lblResults = New-Object System.Windows.Forms.Label
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
#----------------------------------------------
#region Generated Form Code
$frmMain.BackColor = [System.Drawing.Color]::FromArgb(255,40,46,34)
$frmMain.Text = 'Random Number Generator'
$frmMain.Name = 'frmMain'
$frmMain.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 326
$System_Drawing_Size.Height = 299
$frmMain.ClientSize = $System_Drawing_Size
$btnGenerateNumbers.TabIndex = 10
$btnGenerateNumbers.BackColor = [System.Drawing.Color]::FromArgb(255,212,208,200)
$btnGenerateNumbers.Name = 'btnGenerateNumbers'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 142
$System_Drawing_Size.Height = 23
$btnGenerateNumbers.Size = $System_Drawing_Size
$btnGenerateNumbers.UseVisualStyleBackColor = $False
$btnGenerateNumbers.Text = 'Generate Numbers'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 169
$System_Drawing_Point.Y = 191
$btnGenerateNumbers.Location = $System_Drawing_Point
$btnGenerateNumbers.DataBindings.DefaultDataSourceUpdateMode = 0
$btnGenerateNumbers.add_Click($btnGenerateNumbers_OnClick)
$frmMain.Controls.Add($btnGenerateNumbers)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 142
$System_Drawing_Size.Height = 20
$txtFileName.Size = $System_Drawing_Size
$txtFileName.DataBindings.DefaultDataSourceUpdateMode = 0
$txtFileName.Text = 'randomStrings.txt'
$txtFileName.Name = 'textBox4'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 169
$System_Drawing_Point.Y = 164
$txtFileName.Location = $System_Drawing_Point
$txtFileName.TabIndex = 9
$frmMain.Controls.Add($txtFileName)
$lblSaveAsFile.TabIndex = 8
$lblSaveAsFile.TextAlign = 64
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$lblSaveAsFile.Size = $System_Drawing_Size
$lblSaveAsFile.Text = 'Save as file'
$lblSaveAsFile.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 61
$System_Drawing_Point.Y = 162
$lblSaveAsFile.Location = $System_Drawing_Point
$lblSaveAsFile.DataBindings.DefaultDataSourceUpdateMode = 0
$lblSaveAsFile.Name = 'lblSaveAsFile'
$frmMain.Controls.Add($lblSaveAsFile)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 142
$System_Drawing_Size.Height = 20
$txtGenerateThisManyNumbers.Size = $System_Drawing_Size
$txtGenerateThisManyNumbers.DataBindings.DefaultDataSourceUpdateMode = 0
$txtGenerateThisManyNumbers.Text = '10'
$txtGenerateThisManyNumbers.Name = 'txtGenerateThisManyNumbers'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 169
$System_Drawing_Point.Y = 137
$txtGenerateThisManyNumbers.Location = $System_Drawing_Point
$txtGenerateThisManyNumbers.TabIndex = 7
$frmMain.Controls.Add($txtGenerateThisManyNumbers)
$lblGenerateThisManyNumbers.TabIndex = 6
$lblGenerateThisManyNumbers.TextAlign = 64
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 154
$System_Drawing_Size.Height = 23
$lblGenerateThisManyNumbers.Size = $System_Drawing_Size
$lblGenerateThisManyNumbers.Text = 'Generate this many numbers'
$lblGenerateThisManyNumbers.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 135
$lblGenerateThisManyNumbers.Location = $System_Drawing_Point
$lblGenerateThisManyNumbers.DataBindings.DefaultDataSourceUpdateMode = 0
$lblGenerateThisManyNumbers.Name = 'lblGenerateThisManyNumbers'
$frmMain.Controls.Add($lblGenerateThisManyNumbers)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 141
$System_Drawing_Size.Height = 20
$txtLengthOfEachNumber.Size = $System_Drawing_Size
$txtLengthOfEachNumber.DataBindings.DefaultDataSourceUpdateMode = 0
$txtLengthOfEachNumber.Text = '9'
$txtLengthOfEachNumber.Name = 'txtLengthOfEachNumber'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 108
$txtLengthOfEachNumber.Location = $System_Drawing_Point
$txtLengthOfEachNumber.TabIndex = 5
$frmMain.Controls.Add($txtLengthOfEachNumber)
$lblLengthOfEachNumber.TabIndex = 4
$lblLengthOfEachNumber.BackColor = [System.Drawing.Color]::FromArgb(255,40,46,34)
$lblLengthOfEachNumber.TextAlign = 64
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 155
$System_Drawing_Size.Height = 23
$lblLengthOfEachNumber.Size = $System_Drawing_Size
$lblLengthOfEachNumber.Text = 'Length of each number'
$lblLengthOfEachNumber.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 108
$lblLengthOfEachNumber.Location = $System_Drawing_Point
$lblLengthOfEachNumber.DataBindings.DefaultDataSourceUpdateMode = 0
$lblLengthOfEachNumber.Name = 'lblLengthOfEachNumber'
$frmMain.Controls.Add($lblLengthOfEachNumber)
$btnResetCharacterSet.TabIndex = 3
$btnResetCharacterSet.BackColor = [System.Drawing.Color]::FromArgb(255,212,208,200)
$btnResetCharacterSet.Name = 'btnResetCharacterSet'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 141
$System_Drawing_Size.Height = 23
$btnResetCharacterSet.Size = $System_Drawing_Size
$btnResetCharacterSet.UseVisualStyleBackColor = $False
$btnResetCharacterSet.Text = 'Reset Character Set'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 66
$btnResetCharacterSet.Location = $System_Drawing_Point
$btnResetCharacterSet.DataBindings.DefaultDataSourceUpdateMode = 0
$btnResetCharacterSet.add_Click($btnResetCharacterSet_OnClick)
$frmMain.Controls.Add($btnResetCharacterSet)
$txtCreateCharacterSet.Multiline = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 141
$System_Drawing_Size.Height = 44
$txtCreateCharacterSet.Size = $System_Drawing_Size
$txtCreateCharacterSet.DataBindings.DefaultDataSourceUpdateMode = 0
$txtCreateCharacterSet.Text = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
$txtCreateCharacterSet.Name = 'txtCreateCharacterSet'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 15
$txtCreateCharacterSet.Location = $System_Drawing_Point
$txtCreateCharacterSet.TabIndex = 2
$frmMain.Controls.Add($txtCreateCharacterSet)
$lblCreateCharacterSet.TabIndex = 1
$lblCreateCharacterSet.TextAlign = 64
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 156
$System_Drawing_Size.Height = 23
$lblCreateCharacterSet.Size = $System_Drawing_Size
$lblCreateCharacterSet.Text = 'Create Character Set'
$lblCreateCharacterSet.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 15
$lblCreateCharacterSet.Location = $System_Drawing_Point
$lblCreateCharacterSet.DataBindings.DefaultDataSourceUpdateMode = 0
$lblCreateCharacterSet.Name = 'lblCreateCharacterSet'
$lblCreateCharacterSet.add_Click($handler_label2_Click)
$lblCreateCharacterSet.add_MouseHover($CreateCharacterSet_onhover)
$frmMain.Controls.Add($lblCreateCharacterSet)
$lblResults.TabIndex = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 327
$System_Drawing_Size.Height = 51
$lblResults.Size = $System_Drawing_Size
$lblResults.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = -1
$System_Drawing_Point.Y = 249
$lblResults.Location = $System_Drawing_Point
$lblResults.DataBindings.DefaultDataSourceUpdateMode = 0
$lblResults.Name = 'lblResults'
$frmMain.Controls.Add($lblResults)
#endregion Generated Form Code
#Show the Form
$frmMain.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Set-Prompt.ps1
|
Set-Prompt.ps1
|
# This should go OUTSIDE the prompt function, it doesn't need re-evaluation\n# We're going to calculate a prefix for the window title \n# Our basic title is "PoSh - C:\\Your\\Path\\Here" showing the current path\nif(!$global:WindowTitlePrefix) {\n # But if you're running "elevated" on vista, we want to show that ...\n if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista and ...\n new-object Security.Principal.WindowsPrincipal (\n [Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin\n ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) )\n {\n $global:WindowTitlePrefix = "PoSh (ADMIN)"\n } else {\n $global:WindowTitlePrefix = "PoSh"\n }\n}\n\nfunction prompt {\n # FIRST, make a note if there was an error in the previous command\n $err = !$?\n\n # Make sure Windows and .Net know where we are (they can only handle the FileSystem)\n [Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath\n # Also, put the path in the title ... (don't restrict this to the FileSystem\n $Host.UI.RawUI.WindowTitle = "{0} - {1} ({2})" -f $global:WindowTitlePrefix,$pwd.Path,$pwd.Provider.Name\n \n # Determine what nesting level we are at (if any)\n $Nesting = "$([char]0xB7)" * $NestedPromptLevel\n\n # Generate PUSHD(push-location) Stack level string\n $Stack = "+" * (Get-Location -Stack).count\n \n # my New-Script and Get-PerformanceHistory functions use history IDs\n # So, put the ID of the command in, so we can get/invoke-history easier\n # eg: "r 4" will re-run the command that has [4]: in the prompt\n $global:lastCommandId = (Get-History -count 1).Id\n $global:nextCommandId = $global:lastCommandId + 1\n # Output prompt string\n # If there's an error, set the prompt foreground to "Red", otherwise, "Yellow"\n if($err) { $fg = "Red" } else { $fg = "Yellow" }\n # Notice: no angle brackets, makes it easy to paste my buffer to the web\n Write-Host "[${Nesting}${nextCommandId}${Stack}]:" -NoNewLine -Fore $fg \n return " "\n}\n# SIG # Begin signature block\n# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB\n# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR\n# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUEBrAGqg9LWArXQEDCZQGec1A\n# e5aggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG\n# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp\n# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy\n# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw\n# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp\n# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV\n# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0\n# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J\n# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj\n# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR\n# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU\n# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC\n# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV\n# uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD\n# VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk\n# QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0\n# YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl\n# IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y\n# aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo\n# dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg\n# KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG\n# IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3\n# BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv\n# bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj\n# b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG\n# SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl\n# IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA\n# UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF\n# pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q\n# qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h\n# fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B\n# UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5\n# 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1\n# pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4\n# npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV\n# 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki\n# 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp\n# 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR\n# MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD\n# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln\n# bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk\n# aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB\n# qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0\n# IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh\n# dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW\n# GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP\n# ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC\n# rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD\n# dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0\n# U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2\n# R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU\n# Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC\n# MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE\n# AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ\n# yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq\n# t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw\n# KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD\n# VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud\n# IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw\n# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw\n# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC\n# AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg\n# c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g\n# Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw\n# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG\n# JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0\n# dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB\n# BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j\n# bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j\n# b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw\n# Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A\n# 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb\n# E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27\n# zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n\n# FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j\n# RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D\n# dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT\n# DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj\n# YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ\n# bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3\n# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG\n# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBSmV2E5YX+V\n# qydJ/ryGk/Ebemx1SjANBgkqhkiG9w0BAQEFAASCAQBZRaRaBXCuNx1DaUFrs0xU\n# SoKgF/l2THb/fzFys9L6bp7Ye33OSh7CxntqbCDW/MomOoUuQS/FBg/ilB8V0qs1\n# /vktC2ROttW+JzEGy1LRhy6vbh8vxW0Hjb6ndT8eIbuHJxBHZcB8w6dMVtLCUMJW\n# UdiFRBR73fAHKZYqMsjOhT4hBozWGLXETJvnD45umXTmjvCN2w7br1HIhnp80AA8\n# JPeAMDzG604hEqrw6mWBZv36dw70JbHeEuucInaD+qH8E3dA6WSLbM7tBp4xjQL5\n# ftweGUsLxdYIsHKh89GJCIF1ToMF91W0R2rAvy+NUx+TZge0RZvCb8MK2oLcdD0g\n# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-XamlControlTemplate.ps1
|
Get-XamlControlTemplate.ps1
|
## Get-XamlControlTemplate\n## Dump a WPF control's default XAML template\n########################################################################################################################\n## Usage:\n## Get-XamlControlTemplate System.Windows.Navigation.NavigationWindow\n## Get-XamlControlTemplate MenuItem\n## Get-XamlControlTemplate Grid\n########################################################################################################################\n## History:\n## v 1.0 First working version\n########################################################################################################################\nParam ( [string]$control )\n\nif( !$control.Contains(".") ) {\n $control = "System.Windows.Controls.$control"\n}\n\nAdd-Type -AssemblyName PresentationFramework\n\n\n$ctrl = new $control\n$win = new Windows.Window\n\ntry {\n $win.Content = $ctrl\n} catch {\n $win = new $control\n}\n\n$win.Show()\n\n$win.Dispatcher.Invoke( "Render", [Windows.Input.InputEventHandler]{ $win.UpdateLayout() }, $null, $null)\n\n$settings = new-object Xml.XmlWriterSettings\n$settings.Indent = $true\n$settings.IndentChars = " "*4\n$settings.NewLineOnAttributes = $true\n$builder = new Text.StringBuilder\n$xmlWriter = [Xml.XmlWriter]::Create($builder, $settings)\n[WIndows.Markup.XamlWriter]::Save($ctrl.Template, $xmlWriter)\n\n$builder.ToString()\n\n$win.Close()
|
PowerShellCorpus/PoshCode/Show-ConsoleMenu.ps1
|
Show-ConsoleMenu.ps1
|
function Show-ConsoleMenu {
#.Synopsis
# Displays a menu in the console and returns the selection
#.Description
# Displays a numbered list in the console, accepts a typed number from the user, and returns it.
#.Example
# ls | Show-ConsoleMenu -Title "Please pick a file to delete:" -Passthru | rm -whatif
#
# Description
# -----------
# Creates a menu showing a line for every file, and outputs the selected file.
#.Example
# if(Test-Path $Profile) {
# switch(Show-ConsoleMenu "Profile exists:" "Delete it!","Rename it with 01","Abort" -Debug) {
# 0 { rm $Profile -whatif }
# 1 { mv $Profile [IO.Path]::ChangeExtension($Profile,"01.ps1") }
# 2 { return }
# }
# }
#
# Description
# -----------
# Shows how to use the return value without the Passthru switch.
# This example would check if you have a profile, and if you do, would offer you the choice of removing or renaming it.
param(
# The items to be chosen from
[Parameter(ValueFromPipeline=$true,Position=2)]
[Alias("InputObject")]
[PSObject[]]$Choices,
# A caption to display before the choices
[Parameter(Position=1)]
[Alias("Title")]
[string]$Caption,
# A scriptblock expression for formatting the Choices.
[Parameter(Position=3)]
[ScriptBlock]$Expression=({$_}),
# A prompt to display after the choices
[Alias("Footer")]
[string]$Prompt,
# How much to indent the "center" of the selection menu (Defaults to 8)
[int]$indentLeft=8,
# If set, Show-ConsoleMenu returns the selected value from $choices, otherwise it returns the index (which is usually easier to use in a switch statement)
[Switch]$Passthru,
# If set, this function works with my New-BufferBox script by using Out-Buffer ( http://poshcode.org/2899 )
[Switch]$UseBufferBox,
# If set, allows multiple selection (Press Enter to stop selecting more)
[Switch]$MultiSelect
)
begin {
$allchoices = New-Object System.Collections.Generic.List[PSObject]
}
process {
if($choices) {
$allchoices.AddRange($choices)
}
}
end {
$Format = "{0:D1}"; $Digits = 1
if($allchoices.Count -gt 10) {
$Digits = $allchoices.Count.ToString().Length
$Format = "{0:D${Digits}}"
}
# Make a hashtable with keys
for($i=0; $i -lt $allchoices.Count; $i++) {
$allchoices[$i] = Add-Member -Input $allchoices[$i] -Type NoteProperty -Name ConsoleMenuKey -Value $($format -f $i) -Passthru
}
Write-Debug "There are $($allChoices.Count) choices, so we'll use $Digits digits"
# output the menu to the screen
$menu = $allchoices | Format-Table -HideTableHeader @{E="ConsoleMenuKey";A="Right";W=$indentLeft}, @{E=$Expression;A="Left"} -Force | Out-String
$menu = $menu.TrimEnd() + "`n"
if($UseBufferBox) {
Out-Buffer ("`n" + (" " * ($indentLeft/2)) + $Caption + "`n") -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor
Out-Buffer $menu
} else {
Write-Host ("`n" + (" " * ($indentLeft/2)) + $Caption + "`n") -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor
Write-Host $menu
}
do {
if($Prompt) {
if($UseBufferBox) {
Out-Buffer $Prompt -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor
} else {
Write-Host $Prompt -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor
}
}
# get a choice from the user
[string]$PreviousKeys=""
do {
$Key = $Host.UI.RawUI.ReadKey("IncludeKeyDown,NoEcho").Character
try {
[int][string]$choice = "${PreviousKeys}${Key}"
$PreviousKeys = "${PreviousKeys}${Key}"
} catch {
## The "?" causes us to re-show the menu. Useful for long multi-selects, which might scroll off.
if(63 -eq [int][char]$Key) {
if($UseBufferBox) {
Out-Buffer $menu
} else {
Write-Host $menu
}
} elseif(13,27,0 -notcontains [int][char]$Key) {
$warning = "You must type only numeric characters (hit Esc to exit)"
if($UseBufferBox) {
Out-Buffer $warning -ForegroundColor $Host.PrivateData.WarningForegroundColor -BackgroundColor $Host.PrivateData.WarningBackgroundColor
} else {
Write-Warning $warning
}
}
}
} while( $PreviousKeys.Length -lt $Digits -and (13,27 -notcontains [int][char]$Key))
if($PreviousKeys.Length -and $allchoices.Count -gt ([int]$PreviousKeys)) {
if($Passthru) {
$allchoices[([int]$PreviousKeys)]
} else {
$choice
}
}
} while($key -ne [char]13 -and $MultiSelect)
}}
|
PowerShellCorpus/PoshCode/Local Software Inventory.ps1
|
Local Software Inventory.ps1
|
# Create a new Excel object using COM
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False
# Counter variable for rows
$intRow = 1
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)
#Create column headers
$Sheet.Cells.Item($intRow,1) = "Software Vendor"
$Sheet.Cells.Item($intRow,1).Font.Bold = $True
$Sheet.Cells.Item($intRow,2) = "Software Name"
$Sheet.Cells.Item($intRow,2).Font.Bold = $True
$Sheet.Cells.Item($intRow,3) = "Version"
$Sheet.Cells.Item($intRow,3).Font.Bold = $True
$Sheet.Cells.Item($intRow,4) = "Estimated Size (KB)"
$Sheet.Cells.Item($intRow,4).Font.Bold = $True
$Sheet.Cells.Item($intRow,5) = "Installation Date"
$Sheet.Cells.Item($intRow,5).Font.Bold = $True
$Results = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*
foreach ($objResult in $Results)
{
$intRow++
$Name = $objResult.DisplayName
$SizeKB = $objResult.EstimatedSize
$Version = $objResult.DisplayVersion
$InstDate = $objResult.InstallDate
$Vendor = $objResult.Publisher
$Sheet.Cells.Item($intRow,1) = $Vendor
$Sheet.Cells.Item($intRow,2) = $Name
$Sheet.Cells.Item($intRow,3) = $Version
$Sheet.Cells.Item($intRow,4) = $SizeKB
$Sheet.Cells.Item($intRow,5) = $InstDate
}
$Sheet.UsedRange.EntireColumn.AutoFit()
$i = 1
$xlCellTypeLastCell = 11
$used = $Sheet.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$row = $lastCell.row
for ($i = 1; $i -le $row; $i++)
{
If ($Sheet.Cells.Item($i, 1).Value() -eq $Null)
{
$Range = $Sheet.Cells.Item($i, 1).EntireRow
$Range.Delete()
}
}
|
PowerShellCorpus/PoshCode/Thin provisioning with P.ps1
|
Thin provisioning with P.ps1
|
function ConvertVMDiskToThin($vm, $datastore) {
$vmView = Get-View $vm
$dsView = Get-View $datastore
$relocateSpec = New-Object VMware.Vim.VirtualMachineRelocateSpec
$relocateSpec.Datastore = $dsView.MoRef
$relocateSpec.Transform = "sparse"
$vmView.RelocateVM($relocateSpec, $null)
}
|
PowerShellCorpus/PoshCode/Get-Dirty Extended.ps1
|
Get-Dirty Extended.ps1
|
## NAME: Get-Dirty.ps1
## AUTHOR: Barry Morrison
## LASTEDIT: 07/05/2011 16:18:33
<#
.Synopsis
Get's files from today's date. Will also return narrowed results based on keyword
.Description
Get's files from today's date. Will also return narrowed results based on keyword
.Parameter Path
Will run in current directory. Path argument will allow you to define a path not in current working directory
.Parameter Keyword
Keyword argument will allow you to define a keyword to search on to narrow results.
.Example
PS C:\\scripts> .\\dirtoday.ps1
Directory: C:\\scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/5/2011 3:25 PM 114 cat
-a--- 7/5/2011 4:11 PM 2252 dirtoday.ps1
-a--- 7/5/2011 3:46 PM 848 dirtoday2.ps1
-a--- 7/5/2011 2:55 PM 110 info.txt
-a--- 7/5/2011 1:52 PM 37 test.foo
.Example
PS C:\\scripts> .\\dirtoday.ps1 -path "c:\\Users\\John Doe\\Pictures"
Directory: C:\\Users\\John Doe\\Pictures
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/5/2011 11:05 AM 49888 weinerdog.jpg
.Example
PS C:\\scripts> .\\dirtoday.ps1 -keyword foo
cat:2:test.foo:1:blah, blah, foo, ice cream,
test.foo:1:blah, blah, foo, ice cream,
#>
param(
[string]$Path = "",
[string]$keyword = ""
)
## Checking to see if the Keyword argument is passed -- If it is, search for $keyword
if ($keyword) {
$files = dir -Path $path | Where-Object { $_.lastwritetime -ge (get-date).date } | Select-String $keyword
## If there are not results returned, tell me!
if (!$files) {
Write-Output "Nothing Here"
}else{
## If Results exist, give them to me!
$files
}
} else {
## If not keyword argument is passed, do a simple search
$files = dir -Path $path | Where-Object { $_.lastwritetime -ge (get-date).date }
## Like above, checking to see if no results are found for the query
if (!$files) {
## Tell me if nothing exists
Write-Output "Nothing Here"
}else{
## Write results if something exists
$files
}
}
|
PowerShellCorpus/PoshCode/8c6c6bed-3b96-4711-a7b1-2bce64494698.ps1
|
8c6c6bed-3b96-4711-a7b1-2bce64494698.ps1
|
Function Test-Server{
[cmdletBinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$ComputerName,
[parameter(Mandatory=$false)]
[switch]$CredSSP,
[Management.Automation.PSCredential] $Credential)
begin{
$total = Get-Date
$results = @()
if($credssp){if(!($credential)){Write-Host "must supply Credentials with CredSSP test";break}}
}
process{
foreach($name in $computername)
{
$dt = $cdt= Get-Date
Write-verbose "Testing: $Name"
$failed = 0
try{
$DNSEntity = [Net.Dns]::GetHostEntry($name)
$domain = ($DNSEntity.hostname).replace("$name.","")
$ips = $DNSEntity.AddressList | %{$_.IPAddressToString}
}
catch
{
$rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP
$rst.name = $name
$results += $rst
$failed = 1
}
Write-verbose "DNS: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($failed -eq 0){
foreach($ip in $ips)
{
$rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP
$rst.name = $name
$rst.ip = $ip
$rst.domain = $domain
####RDP Check (firewall may block rest so do before ping
try{
$socket = New-Object Net.Sockets.TcpClient($name, 3389)
if($socket -eq $null)
{
$rst.RDP = $false
}
else
{
$rst.RDP = $true
$socket.close()
}
}
catch
{
$rst.RDP = $false
}
Write-verbose "RDP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
#########ping
if(test-connection $ip -count 1 -Quiet)
{
Write-verbose "PING: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
$rst.ping = $true
try{############wsman
Test-WSMan $ip | Out-Null
$rst.WSMAN = $true
}
catch
{$rst.WSMAN = $false}
Write-verbose "WSMAN: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($rst.WSMAN -and $credssp) ########### credssp
{
try{
Test-WSMan $ip -Authentication Credssp -Credential $cred
$rst.CredSSP = $true
}
catch
{$rst.CredSSP = $false}
Write-verbose "CredSSP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
try ########remote reg
{
[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $ip) | Out-Null
$rst.remotereg = $true
}
catch
{$rst.remotereg = $false}
Write-verbose "remote reg: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
try ######### wmi
{
$w = [wmi] ''
$w.psbase.options.timeout = 15000000
$w.path = "\\\\$Name\\root\\cimv2:Win32_ComputerSystem.Name='$Name'"
$w | select none | Out-Null
$rst.RPC = $true
}
catch
{$rst.rpc = $false}
Write-verbose "WMI: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
else
{
$rst.ping = $false
$rst.wsman = $false
$rst.credssp = $false
$rst.remotereg = $false
$rst.rpc = $false
}
$results += $rst
}}
Write-Verbose "Time for $($Name): $((New-TimeSpan $cdt ($dt)).totalseconds)"
Write-Verbose "----------------------------"
}
}
end{
Write-Verbose "Time for all: $((New-TimeSpan $total ($dt)).totalseconds)"
Write-Verbose "----------------------------"
return $results
}
}
|
PowerShellCorpus/PoshCode/CommandTranscript.ps1
|
CommandTranscript.ps1
|
if(!$global:CommandTranscriptPrompt) {
## Record the original prompt so we can put it back if they change their minds...
$global:CommandTranscriptPrompt = ${Function:Prompt}
}
function Start-CommandTranscript {
#.Synopsis
# Start a transcript recording the commands you enter, and optionally, the success and duration of them
#.Description
# Each time your prompt is displayed, the previous command is logged to the transcript.
# If you specify plain (or ps1) output, the result is basically a PowerShell script containing the commands you enter.
# If you specify Full (or csv) output, the result is a csv file with start and end times, success, etc.
# If you specify Annotated (the default) the duration and success of the command are appended as a comment
#.Parameter Output
# What output format you prefer
#
# If you specify plain (or ps1) output, the result is basically a PowerShell script containing the commands you enter.
# If you specify Full (or csv) output, the result is a csv file with start and end times, success, etc.
# If you specify Annotated (the default) the duration and success of the command are appended as a comment
#.Parameter Append
# Whether to overwrite the file or append to it.
#.Parameter Path
# The path to the file to log to
#.Example
# Start-CommandTranscript "$(Split-Path $Profile)\\Session-$(Get-Date -f 'yyyy-mm-dd').ps1" -Output Plain
#
# Description
# -----------
# Logs commands as a script to the profile directory with and output file something like: Session-2010-07-04.ps1
#.Example
# Start-CommandTranscript "~\\Documents\\Logs\\Session $(Get-Date -f 'yyyy-mm-dd').csv" -Output Full
#
# Description
# -----------
# Logs commands in CSV format to the specified file. Note that you must have a Documents\\Logs folder in your $home directory.
param(
[Parameter(Position=0, Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("PSPath","Name")]
[string]$Path = "CommandTranscript"
,
[Parameter(Position=1,Mandatory=$false)]
[ValidateSet("Annotated","Plain","Ps1","Csv","Full")]
[string]$Output = "Annotated"
,
[switch]$Append
)
end {
switch -regex ($Output) {
"Csv|Full" { $extension = $Output = "csv" }
"Plain|Ps1" { $extension = $Output = "ps1" }
"Annotated" { $extension = "ps1" }
}
$global:CommandTranscriptOutput = $Output
if( test-path $path -PathType Container ) {
$path = Join-Path $path "CommandTranscript.$extension"
}
# else ## You can uncomment this block to FORCE the csv/ps1 extension.
# {
# $path = [System.Io.Path]::ChangeExtension($path,$extension)
# }
$global:CommandTranscriptPath = $path
$Start = "# Command Transcript Started $(Get-Date)"
if(!$Append) {
switch($CommandTranscriptOutput) {
"Csv" {
$Type, $Header, $Value = Get-History -count 1 | Add-Member -MemberType NoteProperty -Name Success -Value $? -Passthru | ConvertTo-CSV
Set-Content -LiteralPath $global:CommandTranscriptPath -Value $Type, $Start, $Header
}
default {
Set-Content -LiteralPath $global:CommandTranscriptPath -Value "$Start`n`n"
}
}
} else {
Add-Content -LiteralPath $global:CommandTranscriptPath -Value "`n`n$Start`n`n"
}
$global:CommandTranscriptPath = Resolve-Path $global:CommandTranscriptPath
## Insert our transcript prompt
Function Global:Prompt {
$last = Get-History -count 1 | Add-Member -MemberType NoteProperty -Name Success -Value $? -Passthru
switch($CommandTranscriptOutput) {
"ps1" {
$Value = $last.CommandLine.Trim()
}
"csv" {
$null, $Value = ConvertTo-CSV -Input $last -NoTypeInformation
}
"annotated" {
$Value = "{0,-75} ## Success: {1}, Execution Time: {2} " -f $last.CommandLine.Trim(), $last.Success, ($last.EndExecutionTime - $last.StartExecutionTime)
}
}
Add-Content -LiteralPath $global:CommandTranscriptPath -Value $Value
return &$global:CommandTranscriptPrompt @args
}
Write-Host $Start -Foreground Yellow -Background Black
Write-Host "Logging commands to $global:CommandTranscriptPath" -Foreground Yellow -Background Black
}
}
function Stop-CommandTranscript {
#.Synopsis
# End a transcript session
#.Description
# Terminates transcription and writes out the file item where logging occurred.
end {
$End = "# Command Transcript Ended $(Get-Date)"
Add-Content -LiteralPath $global:CommandTranscriptPath -Value "`n`n$End"
${Function:Prompt} = $Global:CommandTranscriptPrompt
Write-Host $End -Foreground Yellow -Background Black
Write-Host "Transcript is at $global:CommandTranscriptPath" -Foreground Yellow -Background Black
Get-Item $global:CommandTranscriptPath
}
}
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUDdMb/v/9BfEnzKwp6TIIyISK
# cmygggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId
# KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P
# n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl
# 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC
# mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD
# /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX
# +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee
# zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4
# rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7
# bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb
# 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA
# T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUNZLFo6r7
# 7CXUN+MEwwPtHMHYkMcwDQYJKoZIhvcNAQEBBQAEggEAsPgQe5TRWt3x0vxW86jT
# OXc6fNQo1Li4rtkt8ukxt0fgQlanKbWBDZb1Rjt4MqqZhm/ukrsbv/kKatMsJDpS
# YHb2m5LTt6gvzxZl8n/uSxz1cHwnXTX/T1U96Htv+951HqrOky1z/nSKc9dqpLMC
# LLbjvoNLgVM1Q6VQRN0eF1sTxJrLxoVwf3W/Cla3P3hXA83mngYbp7EZUrJcdNGD
# JEzBJK/5RgUpnSqGv2lO6sHByJEpVEpJTJE9HsrM4Z5Utg30hhPcTRq2ksIPzKBv
# FGvAz1lsnHA0gKhdWSh6iG7yvtlXdh/TkiI+9xunWe31mpAitBLGX3PJ+xIgyt98
# LA==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Transcript sessions.ps1
|
Transcript sessions.ps1
|
# Create the transcript file and start the transcript
new-item -path ([Environment]::GetFolderPath('MyDocuments')) -name "PowerShell_Transcripts" -type directory -ea "silentlycontinue"
$transcriptFolder = [Environment]::GetFolderPath('MyDocuments') + "\\PowerShell_Transcripts\\"
$filedate = get-date -format yyyyMMdd.hhmmss
$transcriptfile = $transcriptFolder + $filedate + ".log"
start-transcript $transcriptfile -noClobber -append
|
PowerShellCorpus/PoshCode/Update web.config.ps1
|
Update web.config.ps1
|
Function Update-WCContents($File,$SearchString,$NewValue){
$Contents = Get-Content -Path $File
$Contents | %{$_.Replace($SearchString,$NewValue)} | Set-Content $File
} # End Update-WCContents Function
|
PowerShellCorpus/PoshCode/ConvertFrom-Property_3.ps1
|
ConvertFrom-Property_3.ps1
|
function ConvertFrom-PropertyString {
<#
.SYNOPSIS
Converts data from flat or single-level property files into PSObjects
.DESCRIPTION
Converts delimited string data such as .ini files, or the format-list output of PowerShell, into objects
.EXAMPLE
netsh http show sslcert | join-string "`n" |
ConvertFrom-PropertyString -ValueSeparator " +: " -AutomaticRecords |
Format-Table Application*, IP*, Certificate*
Converts the output of netsh show into pseudo-objects, and then uses Format-Table to display them
.EXAMPLE
ConvertFrom-PropertyString config.ini
Reads in an ini file (which has key=value pairs), using the default settings
.EXAMPLE
@"
ID:3468
Type:Developer
StartDate:1998-02-01
Code:SWENG3
Name:Baraka
ID:11234
Type:Management
StartDate:2005-05-21
Code:MGR1
Name:Jax
"@ |ConvertFrom-PropertyString -sep ":" -RecordSeparator "\\r\\n\\s*\\r\\n" | Format-Table
Code StartDate Name ID Type
---- --------- ---- -- ----
SWENG3 1998-02-01 Baraka 3468 Developer
MGR1 2005-05-21 Jax 11234 Management
Reads records from a key:value string with records separated by blank lines.
NOTE that in this example you could also have used -AutomaticRecords or -Count 5 instead of specifying a RecordSeparator
.EXAMPLE
@"
Name=Fred
Address=Street1
Number=123
Name=Janet
Address=Street2
Number=345
"@ | ConvertFrom-PropertyString -RecordSeparator "`n(?=Name=)"
Reads records from a key=value string and uses a look-ahead record separator to start a new record whenever "Name=" is encountered
NOTE that in this example you could have used -AutomaticRecords or -Count 3 instead of specifying a RecordSeparator
.EXAMPLE
ConvertFrom-PropertyString data.txt -ValueSeparator ":"
Reads in a property file which has key:value pairs
.EXAMPLE
Get-Content data.txt -RecordSeparator "`r`n`r`n" | ConvertFrom-PropertyString -ValueSeparator ";"
Reads in a property file with key;value pairs, and records separated by blank lines, and converts it to objects
.EXAMPLE
ls *.data | ConvertFrom-PropertyString
Reads in a set of *.data files which have an object per file defined with key:value pairs of properties, one-per line.
.EXAMPLE
ConvertFrom-PropertyString data.txt -RecordSeparator "^;(.*?)\\r*\\n" -ValueSeparator ";"
Reads in a property file with key:value pairs, and sections with a header that starts with the comment character ';'
.NOTES
3.5 2012 July 26
- Changed defaults so that lines which don't have a -ValueSeparator in them don't get output
- Changed pipelining so that it works more the way I expect it to, nowadays
- Fixed some problems with -RecordSeparator getting truncated to a single character when you use a capture group and add it as a PSName property
Clearly I need to write some test cases around this to make sure that I'm not breaking functionality, because these changes felt like things that should have already worked...
3.0 2010 Aug 4
- Renamed most of the parameters because I couldn't tell which did what from the Syntax help
- Added a -AutomaticRecords switch which creates new output objects whenevr it encounters a duplicated property
- Added a -SimpleOutput swicth which prevents the output of the PSChildName property
- Added a -CountOfPropertiesPerRecord parameter which allows splitting input by count instead of regex or automatic
2.0 2010 July 9 http://poshcode.org/get/1956
- changes the output so that if there are multiple instances of the same key, we collect the values in an array
1.0 2010 June 15 http://poshcode.org/get/1915
- Initial release
#>
[CmdletBinding(DefaultParameterSetName="Data")]
param(
# The text to be parsed
[Parameter(Position=99, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Data")]
[Alias("Data","Content","IO")]
[AllowEmptyString()]
[string]$InputObject,
# A file containing text to be parsed (so you can pipeline files to be processed)
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PSPath")]
[string]$FilePath,
# The value separator string used between name=value pairs. Allows regular expressions.
# Typical values are "=" or ":"
# Defaults to "="
[Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)]
[Alias("VS","Separator")]
[String]$ValueSeparator="\\s*(?:=|:)\\s*",
# The property separator string used between sets of name=value pairs. Allows regular expressions.
# Typical values are "\\n" or "\\n\\n" or "\\n\\s*\\n"
# Defaults to "\\n\\s*\\n?"
[Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)]
[Alias("PS","Delimiter")]
[String]$PropertySeparator='(?:\\s*\\n+\\s*)+',
# The record separator string is used between records or sections in a text file.
# Typical values are "\\n\\s*\\n" or "\\n\\[(.*)\\]\\s*\\n"
# Defaults to "(?:\\n|^)\\[([^\\]]+)\\]\\s*\\n" (the correct value for ini files).
# To support named sections or records, make sure to use a regular expression here that has a capture group defined.
[Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)]
[Alias("RS")]
[String]$RecordSeparator='(?:\\n|^)\\[([^\\]]+)\\]\\s*\\n',
# Supports guessing when a new record starts based on the repetition of a property name. You can use this whenever your input has multiple records and the properties are always in the same order.
[Parameter(ParameterSetName="Data")]
[Alias("MultiRecords","MR","MultipleRecords","AR","AutoRecords")]
[Switch]$AutomaticRecords,
# Separate the input into groups of a certain number of properties.
# If your input file has no specific record separator, you can usually match the first property by using a look-ahead expression *(See Example 2)*
# However, if the properties aren't in the same order each time or regular expressions make you queasy, and each of your records have the same number of properties on each record, you can use this to separate them by count.
[Parameter()]
[int]$CountOfPropertiesPerRecord,
# Prevent outputting the PSName parameter which indicates the source of the object when pipelineing file names
[Parameter()]
[Switch]$SimpleOutput,
# Discard the first record, assuming that it is merely some lines of header introductory text
[Parameter()]
[Switch]$HasHeader,
# Discard the last record, assuming that it is merely some lines of footer summary text
[Parameter()]
[Switch]$HasFooter
)
begin {
function new-output {
[CmdletBinding()]
param(
[Switch]$SimpleOutput
,
[AllowNull()][AllowEmptyString()]
[String]$Key
,
[AllowNull()][AllowEmptyString()]
$FilePath
)
end {
if(!$SimpleOutput -and ("" -ne $Key)) { @{"PSName"=$key} }
elseif(!$SimpleOutput -and $FilePath) { @{"PSName"=((get-item $FilePath).PSChildName)} }
else { @{} }
}
}
function out-output {
[CmdletBinding()]
param([Hashtable]$output)
end {
## If we made arrays out of single values, unwrap those
foreach($k in $Output.Keys | Where { @($Output.$_).Count -eq 1 } ) {
$Output.$k = @($Output.$k)[0]
}
if($output.Count) {
New-Object PSObject -Property $output
}
}
}
$OutputCount = 0
[String]$InputString = [String]::Empty
Write-Verbose "Setting up the regular expressions: `n`tRecord: '$RecordSeparator' `n`tProperty: '$PropertySeparator' `n`tValue: '$ValueSeparator'"
[Regex]$ReRecordSeparator = New-Object Regex ([System.String]"\\s*$RecordSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
[Regex]$RePropertySeparator = New-Object Regex ([System.String]"\\s*$PropertySeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
[Regex]$ReValueSeparator = New-Object Regex ([System.String]"\\s*$ValueSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
process {
if($PSCmdlet.ParameterSetName -eq "File") {
$AutomaticRecords = $true
$InputString += $(Get-Content $FilePath -Delimiter ([char]0)) + "`n`n"
} else {
$InputString += "$InputObject`n"
}
}
end {
## some kind of PowerShell bug when expecting pipeline input:
if(!"$ReRecordSeparator"){
Write-Verbose "Setting up the record regex in the PROCESS block: '$RecordSeparator'"
[Regex]$ReRecordSeparator = New-Object Regex ([System.String]"\\s*$RecordSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
if(!"$RePropertySeparator"){
Write-Verbose "Setting up the property regex in the PROCESS block: '$PropertySeparator'"
[Regex]$RePropertySeparator = New-Object Regex ([System.String]"\\s*$PropertySeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
if(!"$ReValueSeparator") {
Write-Verbose "Setting up the value regex in the PROCESS block: '$ValueSeparator'"
[Regex]$ReValueSeparator = New-Object Regex ([System.String]"\\s*$ValueSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
Write-Verbose "ParameterSet: $($PSCmdlet.ParameterSetName)"
Write-Verbose "ValueSeparator: $($ReValueSeparator)"
$InputData = @{}
if($PSCmdlet.ParameterSetName -eq "File") {
$AutomaticRecords = $true
$InputString = Get-Content $FilePath -Delimiter ([char]0)
}
## Separate RecordText with the RecordSeparator if the user asked us to:
if($PsBoundParameters.ContainsKey('RecordSeparator') -or $AutomaticRecords ) {
$Records = $ReRecordSeparator.Split( $InputString ) # | Where-Object { $_ }
## Instead of using WhereObject and removing all the empty rows, allow empties AFTER record separators, but not before...
if(!@($Records)[0]) {
$Records = $Records[1..$($Records.Count-1)]
}
Write-Verbose "There are $($ReRecordSeparator.GetGroupNumbers().Count) groups and $(@($Records).Count) records!"
if($ReRecordSeparator.GetGroupNumbers().Count -gt 1 -and @($Records).Count -gt 1) {
if($HasHeader) {
$Records = $Records[2..$($Records.Count -1)]
}
if($HasFooter) {
$Records = $Records[0..$($Records.Count -3)]
}
while($Records) {
$Key,$Value,$Records = @($Records)
Write-Verbose "RecordSeparator with grouping: $Key = $Value"
$InputData.$Key += @($Value)
}
} elseif(@($Records).Count -gt 1) {
$InputData."" = @($Records)
$InputString = $Records
} else {
$InputString = $Records
}
}
## Separate RecordText into properties and group them together by count if we were told a count
if($PsBoundParameters.ContainsKey('CountOfPropertiesPerRecord')) {
$Properties = $RePropertySeparator.Split($InputString)
Write-Verbose "Separating Records by Property count = $CountOfPropertiesPerRecord of $($Properties.Count)"
for($Index = 0; $Index -lt $Properties.Count; $Index += $CountOfPropertiesPerRecord) {
$InputData."" += @($Properties[($Index..($Index+$CountOfPropertiesPerRecord-1))] -Join ([char]0))
Write-Verbose "Record ($Index..) $($Index/$CountOfPropertiesPerRecord) = $(@($Properties[($Index..($Index+$CountOfPropertiesPerRecord-1))] -Join ([char]0)))"
}
## We have to manually set the PropertySeparator because we can't generate text from your regex pattern to match your regex pattern
$SetPropertySeparator = $RePropertySeparator
[Regex]$RePropertySeparator = New-Object Regex ([System.String][char]0), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
if($InputData.Keys.Count -eq 0){
Write-Verbose "Keyless entry enabled!"
$InputData."" = @($InputString)
}
Write-Verbose "InputData: $($InputData.GetEnumerator() | ft -auto -wrap| out-string)"
## Process each Record
foreach($key in $InputData.Keys) { foreach($record in $InputData.$Key) {
Write-Verbose "Record($Key): $record"
$output = new-output -SimpleOutput:$SimpleOutput -Key:$Key -FilePath:$FilePath
foreach($Property in $RePropertySeparator.Split("$record") | ? {$_}) {
if($ReValueSeparator.IsMatch($Property)) {
[string[]]$data = $ReValueSeparator.split($Property,2) | foreach { $_.Trim() } | where { $_ }
Write-Verbose "Property: $Property --> $($data -join ': ')"
if($AutomaticRecords -and $Output.ContainsKey($Data[0])) {
out-output $output
$output = new-output -SimpleOutput:$SimpleOutput -Key:$Key -FilePath:$FilePath
}
switch($data.Count) {
1 { $output.($Data[0]) += @($null) }
2 { $output.($Data[0]) += @($Data[1]) }
}
}
}
out-output $output
} }
## Put this back in case there's more input
$RePropertySeparator = $SetPropertySeparator
}
}
|
PowerShellCorpus/PoshCode/Findup.ps1
|
Findup.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
namespace ConsoleApplication1
{
public class FileInfoExt
{
public FileInfoExt(FileInfo fi)
{
FI = fi;
Checked = false; // Set if the file has already been checked.
string SHA512_1st1K; // SHA512 hash of first 1K bytes.
string SHA512_All; // SHA512 hash of complete file.
}
public FileInfo FI { get; private set; }
public bool Checked { get; set; }
public string SHA512_1st1K { get; set; }
public string SHA512_All { get; set; }
}
class Recurse // Return FileInfoExt list of files matching filenames, file specifications (IE: *.*), and in directories in pathRec
{
public List<FileInfoExt> Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag)
{
List<FileInfoExt> returnList = new List<FileInfoExt>();
foreach (string d in pathRec)
{
returnList.AddRange(Recursive(d, searchPattern, recursiveFlag));
}
return(returnList);
}
public List<FileInfoExt> Recursive(string pathRec, string searchPattern, Boolean recursiveFlag)
{
List<FileInfoExt> returnList = new List<FileInfoExt>();
if (File.Exists(pathRec))
{
try
{
returnList.Add(new FileInfoExt(new FileInfo(pathRec)));
}
catch (Exception e)
{
Console.WriteLine("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
returnList.AddRange(Dir.GetFiles(searchPattern).Select(s => new FileInfoExt(s)));
}
catch (Exception e)
{
Console.WriteLine("Add files from Directory error: " +e.Message);
}
if (recursiveFlag == true)
{
try
{
foreach (string d in (Directory.GetDirectories(pathRec)))
{
returnList.AddRange(Recursive(d, searchPattern, recursiveFlag));
}
}
catch (Exception e)
{
Console.WriteLine("Add Directory error: " + e.Message);
}
}
}
else
{
string filePart = Path.GetFileName(pathRec);
string dirPart = Path.GetDirectoryName(pathRec);
if (filePart.IndexOfAny(new char[] { '?', '*' }) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
returnList.AddRange(Recursive(dirPart, filePart, recursiveFlag));
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
return (returnList);
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile.");
Console.WriteLine(" ");
string[] paths = new string[0];
System.Boolean recurse = false;
System.Boolean delete = false;
System.Boolean noprompt = false;
List<FileInfoExt> fs = new List<FileInfoExt>();
long numOfDupes = 0;
long bytesRec = 0; // number of bytes recovered.
long delFiles = 0; // number of files deleted.
int c = 0;
int i = 0;
string deleteConfirm;
for (i = 0; i < args.Length; i++)
{
if ((args[i] == "-help") || (args[i] == "-h"))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help infomration.");
Console.WriteLine(" -recurse - recurses through subdirectories.");
Console.WriteLine(" -delete - deletes duplicates with confirmation prompt.");
Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
Console.WriteLine(" ");
Environment.Exit(0);
}
if (args[i] == "-recurse")
{
recurse = true;
continue;
}
if (args[i] == "-delete")
{
delete = true;
continue;
}
if (args[i] == "-noprompt")
{
noprompt = true;
continue;
}
Array.Resize(ref paths, paths.Length + 1);
paths[c] = args[i];
c++;
}
if (paths.Length == 0)
{
Console.WriteLine("No files specified, try findup.exe -help");
Environment.Exit(0);
}
Recurse recurseMe = new Recurse();
fs.AddRange(recurseMe.Recursive(paths, "*.*", recurse));
if (fs.Count < 2)
{
Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help");
Environment.Exit(0);
}
for (i = 0; i < fs.Count; i++)
{
if (fs[i].Checked == true)
continue;
fs[i].Checked = true;
for (c = 0; c < fs.Count; c++)
{
if (fs[c].Checked == true)
continue;
if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash.
continue;
if (fs[i].FI.FullName == fs[c].FI.FullName) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1K == null) // check/hash first 1K first.
fs[i].SHA512_1st1K = ComputeInitialHash(fs[i].FI.FullName);
if (fs[c].SHA512_1st1K == null)
fs[c].SHA512_1st1K = ComputeInitialHash(fs[c].FI.FullName);
if (fs[i].SHA512_1st1K != fs[c].SHA512_1st1K) // if the 1st 1K has the same hash..
continue;
if (fs[i].SHA512_1st1K == null) // if hash error, then skip to next file.
continue;
if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_All == null) // check/hash the rest of the files.
fs[i].SHA512_All = ComputeFullHash(fs[i].FI.FullName);
if (fs[c].SHA512_All == null)
fs[c].SHA512_All = ComputeFullHash(fs[c].FI.FullName);
if (fs[i].SHA512_All != fs[c].SHA512_All)
continue;
if (fs[i].SHA512_All == null) // check for hash fail before declairing a duplicate.
continue;
}
Console.WriteLine(" Match: " + fs[i].FI.FullName);
Console.WriteLine(" with: " + fs[c].FI.FullName);
fs[c].Checked = true; // do not check or match against this file again.
numOfDupes++; // increase count of matches.
if (delete != true)
continue;
if (noprompt == false)
{
Console.Write("Delete the duplicate file <Y/n>?");
deleteConfirm = Console.ReadLine();
if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y'))
continue;
}
try
{
File.Delete(fs[c].FI.FullName);
Console.WriteLine("Deleted: " + fs[c].FI.FullName);
bytesRec += fs[c].FI.Length;
delFiles++;
}
catch (Exception e)
{
Console.WriteLine("File delete error: " + e.Message);
}
}
}
Console.WriteLine(" ");
Console.WriteLine("File checked: " + fs.Count);
Console.WriteLine("Duplicates: " + numOfDupes);
Console.WriteLine("Duplicates deleted: " + delFiles);
Console.WriteLine("Bytes recovered: " + bytesRec);
Environment.Exit(0);
}
private static string ComputeInitialHash(string path)
{
byte[] readBuf = new byte[1024];
try
{
using (var stream = File.OpenRead(path))
{
var length = stream.Read(readBuf, 0, readBuf.Length);
var hash = SHA512.Create().ComputeHash(readBuf, 0, length);
return BitConverter.ToString(hash);
}
}
catch (Exception e)
{
Console.WriteLine("Hash Error: " + e.Message);
return (null);
}
}
private static string ComputeFullHash(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
return BitConverter.ToString(SHA512.Create().ComputeHash(stream));
}
}
catch (Exception e)
{
Console.WriteLine("Hash error: " + e.Message);
return (null);
}
}
}
}
|
PowerShellCorpus/PoshCode/New-XVM_13.ps1
|
New-XVM_13.ps1
|
#EXAMPLES
<#
New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR01" -SwitchName "External(192.168.1.0/24)" -VhdType NoVHD
New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR02" -SwitchName "External(192.168.1.0/24)" -VhdType ExistingVHD -VhdPath D:\\vhds\\WS2012-TESTSVR02.vhdx
New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR03" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD
New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR04" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -DiskType Dynamic
New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR05" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB
New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR06" -SwitchName "External(192.168.1.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx'
New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR07" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB}
#>
Function New-XVM
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$false,Position=1)]
[string]$ComputerName=$env:COMPUTERNAME,
[Parameter(Mandatory=$true,Position=2)]
[string]$Name,
[Parameter(Mandatory=$true,Position=3)]
[string]$SwitchName,
[Parameter(Mandatory=$true,Position=4)]
[ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")]
[string]$VhdType,
[Parameter(Mandatory=$false,Position=5)]
[hashtable]$Configuration
)
DynamicParam
{
Switch ($VhdType) {
"ExistingVHD" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "ByParam"
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("VhdPath",$vhdPath)
return $paramDictionary
}
"NewVHD" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "ByParam"
$attributes.Mandatory = $false
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("DiskType",$diskType)
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "ByParam"
$attributes.Mandatory = $false
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection)
$paramDictionary.Add("DiskSize",$diskSize)
return $paramDictionary
}
"Differencing" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "ByParam"
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("ParentVhdPath",$parentVhdPath)
return $paramDictionary
}
}
}
Begin
{
Try
{
$vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop
}
Catch
{
$PSCmdlet.ThrowTerminatingError($Error[0])
}
$defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath
}
Process
{
$validConfigNames = "MemoryStartupBytes","BootDevice"
$configParams = @()
Switch ($VhdType) {
"NoVHD" {
$vhdFilePath = $null
}
"ExistingVHD" {
$vhdFilePath = $vhdPath.Value
}
"NewVhd" {
if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"}
if (-not $diskSize.IsSet) {$diskSize.Value = 127GB}
$newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx"
Switch ($diskType.Value) {
"Fixed" {
$vhdFile = New-VHD -ComputerName $ComputerName -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop
}
"Dynamic" {
$vhdFile = New-VHD -ComputerName $ComputerName -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop
}
}
$vhdFilePath = $vhdFile.Path
}
"Differencing" {
$newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx"
$vhdFile = New-VHD -ComputerName $ComputerName -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop
$vhdFilePath = $vhdFile.Path
}
}
if ($vhdFilePath -ne $null) {
$command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$vhdFilePath'"
} else {
$command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD"
}
if ($Configuration -ne $null) {
foreach ($configName in $Configuration.Keys.GetEnumerator()) {
if ($validConfigNames -contains $configName) {
$configParams += "-$configName" + " " + $Configuration[$configName]
}
}
$configParams = $configParams -join " "
}
if ($configParams.Count -eq 0) {
$command += " -ErrorAction Stop"
} else {
$command += " $configParams -ErrorAction Stop"
}
Try
{
Invoke-Expression -Command $command
}
Catch
{
$PSCmdlet.WriteError($Error[0])
Remove-Item -Path $vhdFile.Path
}
}
End {}
}
|
PowerShellCorpus/PoshCode/Set account password_1.ps1
|
Set account password_1.ps1
|
Function Set-Password {
#requires -version 2.0
<#
.Synopsis
Allows the changing of the local account password on a local or remote machine.
.Description
Allows the changing of the local account password on a local or remote machine.
.Parameter computer
Computer that the password will be changed on. Supports a single computer or collection of computers and can be processed
through the pipeline.
.Parameter user
Account that will have the password changed.
.Example
Set-Password -computer 'server' -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server'
.Example
Set-Password -computer @('server','server2') -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server' and 'server2'
.Example
@('server','server2') | Set-Password -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server' and 'server2'
.Example
Set-Password -computer (Get-Content hosts.txt) -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server' and 'server2'
.Inputs
None
.Outputs
None
.Link
http://boeprox.wordpress.com
.Notes
NAME: Set-Password
VERSION: 1.0
AUTHOR: Boe Prox
Date: 26 August 2010
#>
[CmdletBinding(
SupportsShouldProcess = $True,
ConfirmImpact = 'low',
DefaultParameterSetName = 'server'
)]
Param (
[Parameter(
ValueFromPipeline=$True,
Position=0,
Mandatory=$True,
HelpMessage="List of servers")]
[ValidateNotNullOrEmpty()]
[array]$computer,
[Parameter(
ValueFromPipeline=$False,
Position=1,
Mandatory=$True,
HelpMessage="Account to change password")]
[ValidateNotNullOrEmpty()]
[string]$user
)
Begin {
Write-Verbose "Building container for report"
$arrlist = @()
Write-Verbose "Prompting for password"
$password = Read-Host "Type password -- VERIFY BEFORE CLICKING RETURN!!!"
Write-Verbose "Checking for existence of error log and clearing contents"
$errorlog = "passwordchangeerrors.txt"
If ([system.io.file]::exists($errorlog)) {
Clear-content $errorlog
}
}
Process {
#Iterate through computer list
ForEach ($c in $computer) {
$temp = New-Object PSobject
Try {
Write-Verbose "Testing Connection to $($c)"
Test-Connection -comp $c -count 1 -ea stop | out-null
#Verify account exists before attempting password change
Write-Verbose "Verifying that $($user) exists on $($computer)"
$colusers = ([ADSI]("WinNT://$c,computer")).children | ? {$_.psbase.schemaClassName -eq "User"} | Select -expand Name
If ($colusers -contains $user) {
Write-Host -foregroundcolor Green "Changing password on $c..."
$ErrorActionPreference = 'stop'
Try {
#Make connection to remote/local computer and user account
$account = [adsi]("WinNT://"+$c+"/$user, user")
#Change password on user account
If ($pscmdlet.ShouldProcess($($user))) {
$account.psbase.invoke("SetPassword", $password)
$account.psbase.CommitChanges()
}
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Password Changed"
$temp | Add-Member NoteProperty Notes ""
}
Catch {
$errorflag = $True
Write-Verbose "Writing errors to $($errorlog)"
"$(get-date) :: Server:$($c) :: $($error[0].exception)" | Out-File -append $errorlog
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Error Changing Password"
$temp | Add-Member NoteProperty Notes $error[0]
}
}
Else {
$errorflag = $True
Write-Verbose "Writing errors to $($errorlog)"
"$(get-date) :: Server:$($c) :: $($user) does not exist!)" | Out-File -append $errorlog
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Unable to change password"
$temp | Add-Member NoteProperty Notes "Username does not exist"
}
}
Catch {
$errorflag = $True
Write-Verbose "Writing errors to $($errorlog)"
"$(get-date) :: Server:$($c) :: $($error[0].exception)" | Out-File -append $errorlog
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Error Connecting to computer"
$temp | Add-Member NoteProperty Notes $error[0]
}
Finally {
#Merge temp report with main report
Write-Verbose "Merging report"
$arrlist += $temp
}
}
}
End {
#Generate report to screen
Write-Verbose "Generating report"
$arrlist
If ($errorflag) {
Write-Host -fore Yellow "Errors were reported during run, please look at $($pwd)\\$($errorlog) for more details."
}
Write-Verbose "Removing password from variable `$password"
$password = $Null
}
}
|
PowerShellCorpus/PoshCode/My $Profile.ps1
|
My $Profile.ps1
|
<#
Set some Variables and start transcript.
$MaximumHistoryCount is used to set the number of commands that are stored in History. Defaults to 64. Maximum 32767.
$Transcript is used to set the path for Start-Transcript. I am logging everthing to my SkyDrive folder, using a file name like: username_computername-date.txt
$env:PSModulePath is used to add custom location for modules.
$cert is a variable I use to store my CodeSigningCert to sign scripts.
#>
New-Variable -Name Transcript -Scope Global
$MaximumHistoryCount = 1024
$Transcript = ${env:userprofile}+"\\SkyDrive\\powershell\\"+${env:username}+"_"+${env:computername}+"-"+(get-date).toshortdatestring()+".txt" -replace "/","."
Start-Transcript -Append
$env:PSModulePath = $env:PSModulePath + ";\\\\fileserver\\Scripts\\PSMoules;C:\\Users\\thomas\\SkyDrive\\scripts\\Modules"
$cert = Get-ChildItem Cert:\\CurrentUser\\my -CodeSigningCert | Where-Object {$_.subject -like "*thomas*"}
# If running PowerShell v3 set default parameter values
if ((Get-Host | Select-Object -ExpandProperty Version).Major -ge 3) {
$PSDefaultParameterValues = @{
"Send-MailMessage:From" = "thomas.torggler@ntsystems.it"
"Send-MailMessage:SmtpServer" = "mymailserver.ntsystems.local"
}
# If current session has admin privileges, update powershell help files
if(([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
Write-Host -ForegroundColor Yellow "You are Admin! Updating help..."
Update-Help -UICulture en-us
}
}
# Just a little tool to sign a file and update my module
function Update-TAK {
# sign module file with CodeSigning certificate from cert:\\currentuser\\my
Set-AuthenticodeSignature -FilePath 'C:\\Users\\thomas\\SkyDrive\\scripts\\Modules\\TAK\\tak.psm1' -Certificate $Cert
# update the module files on a network share
copy-item c:\\users\\thomas\\skydrive\\scripts\\tak\\* \\\\fileserver\\Scripts\\PSMoules\\tak
}
# Just a reminder, in case I forget the name of my Module :)
Write-Host -ForegroundColor Yellow .
Write-Host -ForegroundColor Yellow "Type: 'Import-Module TAK' to load Toms Admin toolKit"
Write-Host -ForegroundColor Yellow .
# Create a new PSDrive where all my scripts are located. And change location to that drive...
New-PSDrive -name X -PSProvider FileSystem -root ${env:userprofile}"\\SkyDrive\\scripts" | Out-Null
Set-Location X:
|
PowerShellCorpus/PoshCode/Add CounterPaths 2 Mongo.ps1
|
Add CounterPaths 2 Mongo.ps1
|
<#
.NOTES
AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com)
WEBSITE: http://tekout.wordpress.com
CREATED: 8/20/2012
Requires:
a) PowerShell v2 or better
b) Requires Mongo Official C# driver
https://github.com/mongodb/mongo-csharp-driver/downloads
Tested using 1.5.0.X
.DESCRIPTION
Similar in vein to Add-EventLogs to MongoDB. http://poshcode.org/3586
The script takes about 100 counter paths, and pushes the raw value to a mongo database.
Script can be modified to add CookedValue instead of Raw Value.
TimeStamps are in UTC -4 (EDT)
You can watch the events using MongoVue
http://www.mongovue.com/
Script needs some clean-up to accept input from pipeline for computername, counter names etc.
.STATUS
Alpha - FASTPUBLISH
.TODO
a) Check if script can accept -continious
#>
$mongoDriverPath = 'C:\\Program Files (x86)\\MongoDB\\CSharpDriver 1.5'
Add-Type -Path "$($mongoDriverPath)\\MongoDB.Bson.dll";
Add-Type -Path "$($mongoDriverPath)\\MongoDB.Driver.dll";
$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://localhost/eventsX');
$collection = $db['counters'];
$counters= "memory", "processor", "logicaldisk", "physicaldisk"
$paths = (get-counter -List $counters).paths
#About 100 counter paths covering all memory, processor, logicaldisk and physical disk
$samples = (get-counter -Counter $paths).CounterSamples
foreach ($i in $samples) {
[MongoDB.Bson.BsonDocument] $doc = @{
"_id"= [MongoDB.Bson.ObjectId]::GenerateNewId();
"Time"= $i.TimeBase;
"Counters"= [MongoDB.Bson.BsonDocument] [ordered] @{
"Path"= $i.Path;
"RawValue"= $i.RawValue;
#EDT compensate UTC -4 hrs in minutes (-240)
"TimeStamp"= ($i.Timestamp).AddMinutes(-240);
"TimeStamp100nsec"= $i.Timestamp100NSec;
}; #End of Counters
}; #End of $doc
$collection.Insert($doc);
} #End of ForEach
|
PowerShellCorpus/PoshCode/chkhash_32.ps1
|
chkhash_32.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
}
# functions to print overwriting multi-line messages. Test script will accept a file/filespec/dir and iterate through all files in all subdirs printing a test message + file name to demostrate.
# e.g. PS>.\\writefilename.ps1 c:\\
# call WriteFileName [string]
# after done writing series of overwriting messages, call WriteFileNameEnd
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:wfnlastlen -eq $null) {$global:wfnlastlen=0}
$ctop=[console]::cursortop
$cleft=[console]::cursorleft
$oldwritestrlen=$writestr.length
$rem=$null
$writelines = [math]::divrem($writestr.length+$cleft, [console]::bufferwidth, [ref]$rem)
#if ($rem -ne 0) {$writelines+=1}
$cwe = ($writelines-(([console]::bufferheight-1)-$ctop)) # calculate where text has scroll back to.
if ($cwe -gt 0) {$ctop-=($cwe)}
write-host "$writestr" -nonewline
$global:wfnoldctop=[console]::cursortop
$global:wfnoldcleft=[console]::cursorleft
if ($global:wfnlastlen -gt $writestr.length)
{
write-host (" " * ($global:wfnlastlen-$writestr.length)) -nonewline # this only overwrites previously written text if needed, so no need to compute buffer movement on this
}
$global:wfnlastlen = $oldwritestrlen
if ($ctop -lt 0) {$ctop=$cleft=0}
[console]::cursortop=$ctop
[console]::cursorleft=$cleft
}
function WriteFileNameEnd ( $switch=$true) # call this function when you are done overwriting messages on top of each other
{ # and before printing something else. Default switch=$true, which prints a newline, $false restores cursor position same line.
if ($Host.Name -match 'ise')
{ return }
if ($global:wfnoldctop -ne $null -and $global:wfnoldcleft -ne $null)
{
[console]::cursortop=$global:wfnoldctop
[console]::cursorleft=$wfnoldcleft
if ($global:wfnoldcleft -ne 0 -and $switch)
{
write-host ""
}
}
$global:wfnoldctop=$null
$global:wfnlastlen=$null
$global:wfnoldcleft=$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 Database: $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/Add-SVNFile.ps1
|
Add-SVNFile.ps1
|
None
|
PowerShellCorpus/PoshCode/Invoke-SqlCmdExe.ps1
|
Invoke-SqlCmdExe.ps1
|
<#
.SYNOPSIS
Runs a T-SQL Query and optional outputs results to a file.
.DESCRIPTION
Invoke-SqlCmdExes.ps1 script is a wrapper around sqlcmd.exe to run a T-SQL query or stored procedure and optionally outputs to a file.
.EXAMPLE
PowerShell.exe -File "C:\\Scripts\\Invoke-SqlCmdExe.ps1" -ServerInstance "Z001\\sql1" -Database accounting -Query "EXEC usp_accounts '12445678'"
This example connects to Z001\\sql1.accounting and executes a stored procedure which does not return a result set
.EXAMPLE
PowerShell.exe -File "C:\\Scripts\\Invoke-SqlCmdExe.ps1" -ServerInstance "Z001\\sql1" -Database accounting -Query "SET NOCOUNT ON; SELECT * FROM dbo.vw_accounts" -FilePath "C:\\Scripts\\accounts.txt" -SqlCmdOptions '-h-1 -s"|" -w 8000'
This example connects to Z001\\sql1.accounting and selects the records from the vw_accounts view, the data is outputed to a pipe delimited file with additional options
.EXAMPLE
PowerShell.exe -File "C:\\Scripts\\Invoke-SqlCmdExe.ps1" -ServerInstance "Z001\\sql1" -Database accounting -Query "EXEC usp_accounts '12445678'" -FilePath "C:\\Scripts\\accounts.txt" -SqlCmdOptions '-h-1 -s","'
This example connects to Z001\\sql1.accounting and selects the records from the vw_accounts view, the data is outputed to a CSV file
.NOTES
Version History
v1.0 - Chad Miller - 5/3/2012 - Initial release
#>
param(
[Parameter(Position=0, Mandatory=$true)]
[string]
$ServerInstance,
[Parameter(Position=1, Mandatory=$true)]
[string]
$Database,
[Parameter(Position=2, Mandatory=$true)]
[string]
$Query,
[Parameter(Position=3, Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[string]
$Application="Invoke-SqlCmdExe.ps1",
[Parameter(Position=4, Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path $([system.io.path]::GetDirectoryName("$_"))})]
[string]
$FilePath,
[Parameter(Position=5, Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[string]
#Additional Command-line Options for sqlcmd
$SqlCmdOptions
)
#This must be run as administrator on Windows 2008 and higher!
New-EventLog -LogName Application -Source $Application -EA SilentlyContinue
$Error.Clear()
$events = @{"ApplicationStartEvent" = "31101"; "ApplicationStopEvent" = "31104"; "DatabaseException" = "31725"; "ConfigurationException" = "31705";"BadDataException" = "31760"}
$msg =$null
$MaxErrorMsgLen = 3000
#######################
function Write-Message{
Param([string]$Severity,[string]$Category,[string]$Eventid,[string]$ShortMessage=$null,[string]$Context=$null)
$msg = @"
Severity: $Severity
Category: $Category
EventID: $Eventid
Short Message: $ShortMessage
Context: $Context
"@
$msg = $msg -replace "'"
Write-EventLog -LogName Application -Source $Application -EntryType $Severity -EventId $Eventid -Category $Category -Message $msg
} #Write-Message
#######################
# MAIN #
#######################
$Options = @"
-S"$ServerInstance" -d "$Database" -Q "$Query"
"@
if ($FilePath) {
$Options += @"
-o "$FilePath"
"@
}
if ($SqlCmdOptions) {
$Options += " $SqlCmdOptions"
}
Write-Verbose "sqlcmd.exe $Options"
$Context = "ServerInstance\\Database = $ServerInstance\\$Database`nQuery = $Query"
$msg = "ApplicationStartEvent"
Write-Message -Severity Information -Category $events.ApplicationStartEvent -Eventid 1 -ShortMessage $msg -Context $Context
try {
if ($FilePath) {
$exitCode = (Start-Process -FilePath "sqlcmd.exe" -ArgumentList @"
$Options
"@ -Wait -NoNewWindow -Passthru).ExitCode
}
else {
$tempFile = [io.path]::GetTempFileName()
$exitCode = (Start-Process -FilePath "sqlcmd.exe" -ArgumentList @"
$Options
"@ -Wait -NoNewWindow -RedirectStandardOutput $tempFile -Passthru).ExitCode
}
if ($ExitCode -eq 0) {
$msg = "ApplicationStopEvent"
Write-Message -Severity Information -Category $events.ApplicationStopEvent -Eventid 99 -ShortMessage $msg -Context $Context
}
else {
throw
}
}
#Start-Process Exception
catch [InvalidOperationException] {
$Exception = "{0}, {1}" -f $_.Exception.GetType().FullName,$( $_.Exception.Message -replace "'" )
Write-Verbose "InvalidOperationException"
Write-Message -Severity Error -Category $events.ConfigurationException -Eventid 99 -ShortMessage "ConfigurationException: $Exception" -Context $Context
throw $_
}
#SqlcmdException
catch {
if ($FilePath) {
$Exception = [System.IO.File]::ReadAllText("$FilePath")
}
elseif ($tempFile) {
$Exception = [System.IO.File]::ReadAllText("$tempfile")
}
if ($Exception -and $Exception.Length -gt $MaxErrorMsgLen) {
$Exception = $Exception.SubString($Exception.Length - $MaxErrorMsgLen)
}
Write-Verbose "SqlcmdException"
Write-Message -Severity Error -Category $events.DatabaseException -Eventid 99 -ShortMessage "DatabaseException: $Exception" -Context $Context
throw $Exception
}
finally {
if ($tempFile) {
remove-item $tempFile
}
}
|
PowerShellCorpus/PoshCode/Remove-DeadITunesTracks.ps1
|
Remove-DeadITunesTracks.ps1
|
Clear
$ITunes = New-Object -ComObject iTunes.Application
1..$ITunes.LibraryPlaylist.Tracks.Count | % {
$CurrentTrack = $ITunes.LibraryPlaylist.Tracks.Item($_)
# File Track ??
if ( $CurrentTrack.Kind -eq 1 )
{
if ( ! ([System.IO.File]::Exists($CurrentTrack.Location)) )
{
Write-Host "$($CurrentTrack.Artist) - $($CurrentTrack.Name) has been deleted."
$CurrentTrack.Delete()
}
}
Write-Progress -activity "Removing Dead Tracks" -status "$($CurrentTrack.Artist) - $($CurrentTrack.Name)" -percentComplete ( $_/$ITunes.LibraryPlaylist.Tracks.Count*100)
}
|
PowerShellCorpus/PoshCode/Work-in-progressSPdeploy.ps1
|
Work-in-progressSPdeploy.ps1
|
[System.Reflection.Assembly]::Load('Microsoft.Build.Utilities.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') | out-null
[System.Reflection.Assembly]::Load('Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') | out-null
$msbuild = [Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToDotNetFrameworkFile("msbuild.exe", "VersionLatest")
$global:basepath = (resolve-path ..).path
$stsadm = Join-Path ([Microsoft.SharePoint.Utilities.SPUtility]::GetGenericSetupPath("BIN")) "stsadm.exe"
function Run-MSBuild($msBuildArgs)
{
& $msbuild $msBuildArgs
}
function Get-FirstDirectoryUnderneathSrc
{
dir (Get-FullPath "src") | where { $_.PSIsContainer -eq $true } | select -first 1
}
function Get-FullPath($subdirectory)
{
return join-path -path $basepath -childPath $subdirectory
}
$wspbuilder = Get-FullPath("tools\\WSPBuilder.exe")
function Run-WspBuilder($rootDirectory)
{
pushd
cd $rootDirectory
& $WSPBuilder -BuildWSP true -OutputPath (Get-FullPath 'deployment')
popd
}
function Clean-Path($dir)
{
#I don't like the SilentlyContinue option, but we need to ignore the case
#where there is no directory to delete (in this situation, an error is thrown)
del $dir -recurse -force -erroraction SilentlyContinue
mkdir $dir -erroraction SilentlyContinue | out-null
}
function Create-DeploymentBatchFile($filename, $featureName, $solutionName, $url)
{
$contents = @"
ECHO OFF
SET STSADM="%PROGRAMFILES%\\Common Files\\Microsoft Shared\\web server extensions\\12\\BIN\\stsadm.exe"
%STSADM% -o deactivatefeature -name $featureName -url $url
%STSADM% -o retractsolution -allcontenturls -immediate -name $solutionName
%STSADM% -o execadmsvcjobs
%STSADM% -o deletesolution -name $solutionName -override
%STSADM% -o addsolution -filename $solutionName
%STSADM% -o deploysolution -allcontenturls -immediate -allowgacdeployment -name $solutionName
%STSADM% -o execadmsvcjobs
REM second call to execadmsvcjobs allows for a little more delay. Shouldn't be necessary, but is.
%STSADM% -o execadmsvcjobs
%STSADM% -o activatefeature -url $url -name $featureName
"@
Out-File -inputObject $contents -filePath $filename -encoding ASCII
}
#Do-Deployment - regardless of current status, will install the Solution
function Do-Deployment($featureName, $solutionName, $rootDirectory)
{
echo $featureName, $solutionName, $rootDirectory
if (-not (Is-Installed $solutionName)) {
Install-Solution -solutionName $solutionName -filename (join-path $rootDirectory $solutionName)
}
Exec-AdmSvcJobs
if (-not (Is-Deployed $solutionName)) {
Deploy-Solution -solutionName $solutionName -featureName $featureName -filename (join-path $rootDirectory $solutionName)
} else {
Upgrade-Solution -solutionName $solutionName -featureName $featureName -filename (join-path $rootDirectory $solutionName)
}
}
function Is-Installed($solutionName)
{
#is Solution in the Solution store at all?
return [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName] -ne $null
}
function Is-Deployed($solutionName)
{
#Is Solution successfully deployed everywhere? Partial/failed deployments don't count as deployed
$solution = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName]
if ($solution -eq $null) { return false; }
return $solution.Deployed
}
function Install-Solution($solutionName, $filename)
{
#Assumes solution is NOT already installed. For "unsure installation", use Do-Deployment
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions.psbase.Add($filename) | out-null
}
function Deploy-Solution($featureName, $solutionName, $filename)
{
#Assumes solution is already installed. For "unsure installation", use Do-Deployment
$dateToGuaranteeInstantDeployment = [datetime]::Now.AddDays(-2)
#method signature requires typed Collection, so we're unrolling
#the IEnumerable<SPWebApplication> into an array.
$webApplications = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.WebApplications | % { $_ }
$webApplicationsCollection = new-object Microsoft.SharePoint.Administration.SPWebApplication[] -arg ($webApplications.Count)
0..($webApplications.Count-1) | % { $webApplicationsCollection[$_] = $webApplications[$_] }
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].Deploy($dateToGuaranteeInstantDeployment, $true, $webApplicationsCollection, $false)
}
function Upgrade-Solution($featureName, $solutionName, $filename)
{
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].Upgrade($filename)
}
function Exec-AdmSvcJobs
{
& $stsadm -o execadmsvcjobs
#sleep for a few more seconds to account for concurrency bugs/timing issues
sleep -seconds 2
}
|
PowerShellCorpus/PoshCode/Twitter Module v0.2.1b.ps1
|
Twitter Module v0.2.1b.ps1
|
<#
<#
Name: Social Media Scripting Framework
Module: Twitter
Version: 0.2 BETA
Date: 2013/02/03
Author: Carlos Veira Lorenzo
RoughRevision: chriskenis
e-mail: cveira [at] thinkinbig [dot] org
blog: thinkinbig.org
twitter: @cveira
facebook: www.facebook.com/cveira
Google+: gplus.to/cveira
LinkedIn: es.linkedin.com/in/cveira/
Support:
http://thinkinbig.org/oms/
Forums & Communities:
facebook.com/ThinkInBig
gplus.to/ThinkInBig
http://bit.ly/SMSF-Forum
Code Mirror Sites:
https://smsf.codeplex.com/
https://github.com/cveira/social-media-scripting-framework
https://code.google.com/p/social-media-scripting-framework/
http://sourceforge.net/projects/smsf/
Social Media Scripting Framework.
Copyright (C) 2013 Carlos Veira Lorenzo.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#>
[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("System.Net") | Out-Null
[string] $script:TweetContentPattern = '((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>.*?' + `
'<li[^>]*js-stat-count js-stat-retweets stat-count[^>]*>(?<ReTweetStats>.*?)</li>.*?' + `
'<li[^>]*js-stat-count js-stat-favorites stat-count[^>]*>(?<FavoritesStats>.*?)</li>)|' + `
'((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>.*?' + `
'<li[^>]*js-stat-count js-stat-retweets stat-count[^>]*>(?<ReTweetStats>.*?)</li>)|' + `
'((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>.*?' + `
'<li[^>]*js-stat-count js-stat-favorites stat-count[^>]*>(?<FavoritesStats>.*?)</li>)|' + `
'((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>)'
$script:TwitterTimeOut = 3 * 60 * 1000 # seconds
[string] $script:TwitterUserAgent = "PowerShell" + (Get-Host).Version.Major
[string] $script:ApiRoot = "http://api.twitter.com/1.1/"
Function Get-TweetRetweetsFromPage([ref] $PageSourceCode){
[string] $RetweetsCountPattern = '<strong[^>]*[^>]*>(?<RetweetsCount>.*?)</strong>'
if ($PageSourceCode.Value -match $script:TweetContentPattern){
if ($Matches.ReTweetStats -match $RetweetsCountPattern){$Matches.RetweetsCount}
else {0}
}
else {0}
}
Function Get-TweetFavoritesFromPage([ref] $PageSourceCode){
[string] $FavoritesCountPattern = '<strong[^>]*[^>]*>(?<FavoritesCount>.*?)</strong>'
if ($PageSourceCode.Value -match $script:TweetContentPattern){
if ($Matches.FavoritesStats -match $FavoritesCountPattern){$Matches.FavoritesCount}
else {0}
}
else {0}
}
Function Get-TweetContentFromPage([ref] $PageSourceCode){
if ($PageSourceCode.Value -match $script:TweetContentPattern){$Matches.TweetContent}
else {"N/D"}
}
Function Get-TweetLinksFromPage([ref] $PageSourceCode){
[RegEx] $LinksPattern = '(data-expanded-url="(.*?)")+'
[string[]] $TweetLinks = @()
if ($PageSourceCode.Value -match $script:TweetContentPattern){
$CurrentMatch = $LinksPattern.match($Matches.TweetContent)
if (-not $CurrentMatch.Success){$TweetLinks += "N/D"}
while ($CurrentMatch.Success){
$TweetLinks += $CurrentMatch.Value.Split('"')[1]
$CurrentMatch = $CurrentMatch.NextMatch()
}
}
else {$TweetLinks += "N/D"}
return $TweetLinks
}
Function Get-TweetHashTagsFromPage([ref] $PageSourceCode){
[string] $HashTagNamePattern = "%23(?<HashTag>.*?)&"
[RegEx] $LinksPattern = '(href="(.*?)")+'
[string[]] $TweetLinks = @()
if ($PageSourceCode.Value -match $script:TweetContentPattern){
$CurrentMatch = $LinksPattern.match($Matches.TweetContent)
if (-not $CurrentMatch.Success){$TweetLinks += "N/D"}
while ($CurrentMatch.Success){
if ($CurrentMatch.Value -match $HashTagNamePattern){$TweetLinks += $Matches.HashTag }
$CurrentMatch = $CurrentMatch.NextMatch()
}
}
else {$TweetLinks += "N/D"}
return $TweetLinks
}
Function EscapeDataStringRfc3986([string]$text){
[string[]] $Rfc3986CharsToEscape = @("!", "*", "'", "(", ")")
[string] $EscapedText = [System.Uri]::EscapeDataString($text)
for ($i = 0; $i -lt $Rfc3986CharsToEscape.Length; $i++){
$EscapedText = $EscapedText.Replace($Rfc3986CharsToEscape[$i], [System.Uri]::HexEscape($Rfc3986CharsToEscape[$i]))
}
return $EscapedText
}
Function Set-OAuthSignature{
param(
[string] $HttpRequestType,
[string] $HttpEndpoint,
[string] $HttpQueryString,
[string] $OAuthNonce,
[string] $OAuthTimeStamp,
[string] $OAuthConsumerKey,
[string] $OAuthConsumerSecret,
[string] $OAuthToken,
[string] $OAuthTokenSecret
)
[string[]] $HttpQueryStringParameters
$ParameterString = @{}
if ($HttpQueryString.Length -gt 0){
$HttpQueryStringParameters = $HttpQueryString.Split("&")
$HttpQueryStringParameters | ForEach-Object {$ParameterString.Add($_.Split("=")[0], $_.Split("=")[1]) }
}
$ParameterString.Add("oauth_consumer_key", $OAuthConsumerKey)
$ParameterString.Add("oauth_nonce", $OAuthNonce)
$ParameterString.Add("oauth_signature_method", "HMAC-SHA1")
$ParameterString.Add("oauth_timestamp", $OAuthTimeStamp)
$ParameterString.Add("oauth_token", $OAuthToken)
$ParameterString.Add("oauth_version", "1.0")
$signature = $HttpRequestType + "&"
# 1. The URL in the signature string HAS NO QUERY_STRING PARAMETERS
$signature += [System.Uri]::EscapeDataString($HttpEndpoint) + "&"
# 2. All the parameters included in the QUERY_STRING {when calling [System.Net.WebRequest]::Create()} have to be included in the signature
# 3. When building the signature string, parameters must be in alphabetical order.
$ParameterString.Keys | Sort-Object | ForEach-Object {
# [System.Uri]::EscapeDataString($_ + "=" + $ParameterString.$_ + "&") is not RFC3986 compliant in .NET < 4.x!
# RFC3986 compliancy is documented in OAuth 1.0A, not in Twitter documentation!
$signature += EscapeDataStringRfc3986 $($_ + "=" + $ParameterString.$_ + "&")
}
$signature = $signature.Substring(0, $signature.Length - 3)
$SignatureKey = [System.Uri]::EscapeDataString($OAuthConsumerSecret) + "&" + [System.Uri]::EscapeDataString($OAuthTokenSecret)
$Hasher = New-Object System.Security.Cryptography.HMACSHA1
$Hasher.Key = [System.Text.Encoding]::ASCII.GetBytes($SignatureKey)
$OAuthSignature = [System.Convert]::ToBase64String($Hasher.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature)))
return $OAuthSignature
}
Function Set-OAuthHeader{
param(
[string] $OAuthConsumerKey,
[string] $OAuthNonce,
[string] $OAuthSignature,
[string] $OAuthTimeStamp,
[string] $OAuthToken
)
$OAuthHeader = 'OAuth '
$OAuthHeader += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($OAuthConsumerKey) + '", '
$OAuthHeader += 'oauth_nonce="' + [System.Uri]::EscapeDataString($OAuthNonce) + '", '
$OAuthHeader += 'oauth_signature="' + [System.Uri]::EscapeDataString($OAuthSignature) + '", '
$OAuthHeader += 'oauth_signature_method="HMAC-SHA1", '
$OAuthHeader += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($OAuthTimeStamp) + '", '
$OAuthHeader += 'oauth_token="' + [System.Uri]::EscapeDataString($OAuthToken) + '", '
$OAuthHeader += 'oauth_version="1.0"'
return $OAuthHeader
}
Function Get-RawTweetRetweetedBy([string]$TweetPermaLink, [string]$Output = 'raw'){
[string] $HttpRequestType = "GET"
[string] $TwitterRawResponse = ""
[string] $ApiURL = $script:ApiRoot + "/statuses/" + $TweetPermaLink.Split("/")[5] + "/retweeted_by.xml"
# [string] $ApiURL = "http://api.twitter.com/1/statuses/" + $TweetPermaLink.Split("/")[5] + "/retweeted_by.xml" --> = typo or version 1 iso 1.1 ???
[string] $HttpQueryString = ""
$OAuthConsumerKey = $TwitterConsumerKey
$OAuthConsumerSecret = $TwitterConsumerSecret
$OAuthToken = $TwitterAccessToken
$OAuthTokenSecret = $TwitterAccessTokenSecret
$OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()))
$OAuthTimeStamp = [int64](New-TimeSpan "01 January 1970 00:00:00" $(Get-Date)).TotalSeconds
$OAuthSignature = Set-OAuthSignature $HttpRequestType $ApiURL $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret
$OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken
[System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL)
$request.Method = $HttpRequestType
$request.UserAgent = $script:TwitterUserAgent
$request.Timeout = $script:TwitterTimeOut
$request.ContentType = "application/x-www-form-urlencoded"
$request.Headers.Add("Authorization", $OAuthHeader)
try {
[System.Net.HttpWebResponse] $response = $request.GetResponse()
if ($response -ne $null){
$ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream())
$ResponseStream.ReadToEnd().Trim() | Select-String -NotMatch "api.twitter.com" | ForEach-Object {$TwitterRawResponse += $_ } | Out-Null
}
switch ($Output){
'raw'{return $TwitterRawResponse}
'xml'{
$TwitterXMLResponse = @()
[xml]$TwitterRawResponse | ForEach-Object {$_.users.user } | ForEach-Object {
$TwitterXMLResponse += New-Object PSObject -Property @{
Name = $_.name
ScreenName = $_.screen_name
Description = $_.description
URL = $_.url
Friends = $_.friends_count
Followers = $_.followers_count
Tweets = $_.statuses_count
Listed = $_.listed_count
}
}
return $TwitterXMLResponse
}
}
$response.Close()
}
catch {$_.Exception.Message}
}
Function Get-RawTweetRetweetedByAsXml([string] $TweetPermaLink){
Get-RawTweetRetweetedBy -TweetPermaLink $TweetPermaLink -Output 'xml'
}
Function Get-RawTwitterAsJson {
param(
[string]$TwitterObject,
[string]$TweetPermaLink = "",
[string]$UserName = "",
[int] $results = 20,
[string] $FirstId = "",
[string] $LastId = "",
[string] $PageId = "-1",
[int] $ResultsPerPage = 20
)
[string] $HttpRequestType = "GET"
[string] $HttpEndpoint = ""
[string] $HttpQueryString = ""
[string] $ApiURL = ""
switch ($TwitterObject){
'TwitterMentions'{$ApiURL = $script:ApiRoot + "statuses/mentions_timeline.json?count=20&include_entities=true&include_rts=true"}
'TweetRetweets'{$ApiURL = $script:ApiRoot + "statuses/retweets/" + $TweetPermaLink.Split("/")[5] + ".json?count=100"}
'TwitterUser'{$ApiURL = $script:ApiRoot + "users/show.json?screen_name=" + $UserName.Trim() + "&include_entities=true"}
'Tweet'{$ApiURL = $script:ApiRoot + "statuses/show.json?id=" + $TweetPermaLink.Split("/")[5] + "&include_entities=true"}
'TwitterFavorites'{$ApiURL = $script:ApiRoot + "favorites/list.json?count=20&screen_name=" + $UserName.Trim() + "&include_entities=true"}
'TweetsFromUser'{
if (($FirstId -ne "") -and ($FirstId -match "\\d+")){$FilterParameters += "&max_id=" + $FirstId }
if (($LastId -ne "") -and ($LastId -match "\\d+")){$FilterParameters += "&since_id=" + $LastId }
$ApiURL = $script:ApiRoot + "statuses/user_timeline.json?include_entities=true&include_rts=true&exclude_replies=true&count=" + $results + $FilterParameters + "&screen_name=" + $UserName.Trim()
}
'TwitterTimeLine'{$ApiURL = $script:ApiRoot + "statuses/home_timeline.json?include_entities=true&count=20"}
'TwitterListSubscribers'{$ApiURL = $script:ApiRoot + "lists/subscribers.json?slug=" + $TweetPermaLink.Split("/")[4] + "&owner_screen_name=" + $TweetPermaLink.Split("/")[3] + "&include_entities=true&cursor=" + $PageId + "&skip_status=true"}
'TwitterListMembers'{$ApiURL = $script:ApiRoot + "lists/members.json?slug=" + $TweetPermaLink.Split("/")[4] + "&owner_screen_name=" + $TweetPermaLink.Split("/")[3] + "&include_entities=true&cursor=" + $PageId + "&skip_status=true"}
'TwitterListTimeLine'{$ApiURL = $script:ApiRoot + "lists/statuses.json?slug=" + $TweetPermaLink.Split("/")[4] + "&owner_screen_name=" + $TweetPermaLink.Split("/")[3] + "&count=" + $ResultsPerPage + "&include_entities=true&include_rts=true"}
'TwitterUserFriendsFromUser'{$ApiURL = $script:ApiRoot + "friends/list.json?screen_name=" + $UserName.Trim() + "&include_entities=true&cursor=" + $PageId + "&skip_status=true"}
'TwitterFollowersFromUser'{$ApiURL = $script:ApiRoot + "followers/list.json?screen_name=" + $UserName.Trim() + "&include_entities=true&cursor=" + $PageId + "&skip_status=true"}
''{}
}
if ($ApiURL.IndexOf("?") -ne -1){
$HttpEndpoint = $ApiURL.Split("?")[0]
$HttpQueryString = $ApiURL.Split("?")[1]
}
else {
$HttpEndpoint = $ApiURL
$HttpQueryString = ""
}
$OAuthConsumerKey = $TwitterConsumerKey
$OAuthConsumerSecret = $TwitterConsumerSecret
$OAuthToken = $TwitterAccessToken
$OAuthTokenSecret = $TwitterAccessTokenSecret
$OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()))
$OAuthTimeStamp = [int64](New-TimeSpan "01 January 1970 00:00:00" $(Get-Date)).TotalSeconds
$OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret
$OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken
[System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL)
$request.Method = $HttpRequestType
$request.UserAgent = $script:TwitterUserAgent
$request.Timeout = $script:TwitterTimeOut
$request.ContentType = "application/x-www-form-urlencoded"
$request.Headers.Add("Authorization", $OAuthHeader)
try {
[System.Net.HttpWebResponse] $response = $request.GetResponse()
if ($response -ne $null){
$ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream())
$ResponseStream.ReadToEnd().Trim()
}
$response.Close()
}
catch {$_.Exception.Message}
}
Function Get-RawTwitterMentionsAsJson {
Get-RawTwitterAsJson -TwitterObject 'TwitterMentions'
}
Function Get-RawTweetRetweetsAsJson($TweetPermaLink){
Get-RawTwitterAsJson -TwitterObject 'TweetRetweets' -TweetPermaLink $TweetPermaLink
}
Function Get-RawTwitterUserAsJson($UserName){
Get-RawTwitterAsJson -TwitterObject 'TwitterUser' -Username $Username
}
Function Get-RawTweetAsJson($TweetPermaLink){
Get-RawTwitterAsJson -TwitterObject 'Tweet' -TweetPermaLink $TweetPermaLink
}
Function Get-RawTwitterFavoritesAsJson($UserName){
Get-RawTwitterAsJson -TwitterObject 'TwitterFavorites' -UserName $UserName
}
Function Get-RawTweetsFromUserAsJson($UserName,$results = 20,$FirstId = "",$LastId = ""){
Get-RawTwitterAsJson -TwitterObject 'TweetsFromUser' -UserName $UserName -results $results -FirstId $FirstId -LastId $LastId
}
Function Get-RawTwitterTimeLineAsJson{
Get-RawTwitterAsJson -TwitterObject 'TwitterTimeLine'
}
Function Get-RawTwitterListSubscribersAsJson($TweetPermaLink,$PageId = "-1" ) {
Get-RawTwitterAsJson -TwitterObject 'TwitterListSubscribers' -TweetPermaLink $TweetPermaLink -PageId $PageId
}
Function Get-RawTwitterListMembersAsJson($TweetPermaLink,$PageId = "-1"){
Get-RawTwitterAsJson -TwitterObject 'TwitterListMembers' -TweetPermaLink $TweetPermaLink -PageId $PageId
}
Function Get-RawTwitterListTimeLineAsJson($TweetPermaLink,$ResultsPerPage = 20){
Get-RawTwitterAsJson -TwitterObject 'TwitterListTimeLine' -TweetPermaLink $TweetPermaLink -ResultsPerPage $ResultsPerPage
}
Function Get-RawTwitterUserFriendsFromUserAsJson($UserName,$PageId = "-1"){
Get-RawTwitterAsJson -TwitterObject 'TwitterUserFriendsFromUser' -UserName $UserName -PageId $PageId
}
Function Get-RawTwitterFollowersFromUserAsJson($UserName,$PageId = "-1"){
Get-RawTwitterAsJson -TwitterObject 'TwitterFollowersFromUser' -UserName $UserName -PageId $PageId
}
Function Get-RawTwitterSearchAsJson{
param(
[string] $query,
[int] $ResultsPerPage = 20,
[string] $Language = "",
[string] $ResultType = "",
[string] $StartDate = "",
[string] $GeoCode = "",
[int64] $SinceId = 0,
[int64] $MaxId = 0
)
# https://dev.twitter.com/docs/api/1.1/get/search/tweets
# https://dev.twitter.com/docs/using-search
# https://dev.twitter.com/docs/working-with-timelines
[string] $HttpRequestType = "GET"
[string] $HttpEndpoint = ""
[string] $HttpQueryString = ""
[string] $TwitterRawResponse = ""
[string] $SearchParameters = "include_entities=true"
if ($ResultType -eq ""){$SearchParameters += "&result_type=mixed"}
else {
switch ($ResultType){
"mixed" {$SearchParameters += "&result_type=mixed"}
"recent" {$SearchParameters += "&result_type=recent"}
"popular" {$SearchParameters += "&result_type=popular"}
default {$SearchParameters += "&result_type=mixed"}
}
}
if (($StartDate -ne "") -and ($StartDate -match "\\d{4}-\\d{2}-\\d{2}")){$SearchParameters += "&until=" + $StartDate}
if (($GeoCode -ne "") -and ($GeoCode -match "(\\-*[\\d\\.]+),(\\-*[\\d\\.]+),(\\d+)(km|mi)")){$SearchParameters += "&geocode=" + $GeoCode}
if ($SinceId -ne 0){$SearchParameters += "&since_id=" + $SinceId}
if ($MaxId -ne 0){$SearchParameters += "&max_id=" + $MaxId}
$SearchParameters += "&count=" + $ResultsPerPage + "&q="
[string] $ApiURL = $script:ApiRoot + "search/tweets.json?" + $SearchParameters + [System.Uri]::EscapeDataString($query.Trim())
if ($ApiURL.IndexOf("?") -ne -1){
$HttpEndpoint = $ApiURL.Split("?")[0]
$HttpQueryString = $ApiURL.Split("?")[1]
}
else {
$HttpEndpoint = $ApiURL
$HttpQueryString = ""
}
$OAuthConsumerKey = $TwitterConsumerKey
$OAuthConsumerSecret = $TwitterConsumerSecret
$OAuthToken = $TwitterAccessToken
$OAuthTokenSecret = $TwitterAccessTokenSecret
$OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()))
$OAuthTimeStamp = [int](New-TimeSpan "01 January 1970 00:00:00" $(Get-Date)).TotalSeconds
$OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret
$OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken
[System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL)
$request.Method = $HttpRequestType
$request.UserAgent = $script:TwitterUserAgent
$request.Timeout = $script:TwitterTimeOut
$request.ContentType = "application/x-www-form-urlencoded"
$request.Headers.Add("Authorization", $OAuthHeader)
try {
[System.Net.HttpWebResponse] $response = $request.GetResponse()
if ($response -ne $null){
$ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream())
$ResponseStream.ReadToEnd().Trim()
}
$response.Close()
}
catch {$_.Exception.Message}
}
Function Send-Tweet ([string] $TweetMessage){
# https://dev.twitter.com/docs/api/1.1/post/statuses/update
# Send-Tweet "This is my first Tweet from #PowerShell using, raw #DotNet and #OAuth!"
[string] $HttpRequestType = "POST"
[string] $HttpEndpoint = ""
[string] $HttpQueryString = ""
[string] $TwitterRawResponse = ""
[string] $ApiURL = $script:ApiRoot + "statuses/update.json"
if ($TweetMessage.Length -gt 140){$TweetMessage = $TweetMessage.Substring(0,140)}
# Body POST Data format is NOT documented!
# look at how the supplied example looks like @ https://dev.twitter.com/docs/api/1.1/post/statuses/update
[byte[]] $HttpPostBody = [System.Text.Encoding]::UTF8.GetBytes("status=" + (EscapeDataStringRfc3986 ($TweetMessage)))
$HttpEndpoint = $ApiURL
# The 'status' parameter gets encoded TWICE in the OAuth signature. This detail is NOT documented!
# Run an example with the OAuth Tool and look at the results for the OAuth signature.
# [System.Uri]::EscapeDataString() is not RFC3986 compliant in .NET < 4.x!
# RFC3986 compliancy is documented in OAuth 1.0A, not in Twitter documentation!
$HttpQueryString = "status=" + (EscapeDataStringRfc3986 $TweetMessage)
$OAuthConsumerKey = $TwitterConsumerKey
$OAuthConsumerSecret = $TwitterConsumerSecret
$OAuthToken = $TwitterAccessToken
$OAuthTokenSecret = $TwitterAccessTokenSecret
$OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()))
$OAuthTimeStamp = [int](New-TimeSpan "01 January 1970 00:00:00" $(Get-Date)).TotalSeconds
$OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret
$OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken
[System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL)
$request.Method = $HttpRequestType
$request.UserAgent = $script:TwitterUserAgent
$request.Timeout = $script:TwitterTimeOut
$request.ContentType = "application/x-www-form-urlencoded"
$request.ContentLength = $HttpPostBody.Length
$request.ServicePoint.Expect100Continue = $false
$request.Headers.Add("Authorization", $OAuthHeader)
try {
[System.IO.Stream] $RequestBody = $request.GetRequestStream()
$RequestBody.Write($HttpPostBody, 0, $HttpPostBody.Length)
# $RequestBody.Flush()
$RequestBody.Close()
[System.Net.HttpWebResponse] $response = $request.GetResponse()
if ($response -ne $null){
$ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream())
$ResponseStream.ReadToEnd().Trim()
}
$response.Close()
}
catch {$_.Exception.Message}
}
Function Get-TwitterProfile([string]$UserName){Get-RawTwitterUserAsJson $UserName | ConvertFrom-JSON}
Function Get-UnpagedFollowerList([object[]] $PagedFollowersList){
$UnpagedFollowers = @()
$PagedFollowersList | ForEach-Object {$UnpagedFollowers += $_.users }
$UnpagedFollowers = $UnpagedFollowers | Select-Object * -unique
return $UnpagedFollowers
}
Function Get-TwitterFollowers([string] $UserName){
begin{
[PSCustomObject[]] $RawFollowersPages = @()
$CurrentPage = $null
$TimeToWait = 66
$FollowersPerPage = 20
$PageCount = 0
[int] $TotalFollowers = (Get-RawTwitterUserAsJson $UserName | ConvertFrom-JSON).followers_count
}
process{
try {
$PageCount = 1
$CurrentPage = Get-RawTwitterFollowersFromUserAsJson $UserName | ConvertFrom-JSON
$RawFollowersPages += $CurrentPage
do {
Write-Progress -Activity "Retrieving Followers ..." -Status "Progress: " -PercentComplete ((($PageCount * $FollowersPerPage) / $TotalFollowers) * 100)
$PageCount++
$RawFollowersPages += $CurrentPage
Start-Sleep -Seconds $TimeToWait
$CurrentPage = Get-RawTwitterFollowersFromUserAsJson $UserName -PageId $CurrentPage.next_cursor | ConvertFrom-JSON
}
until ($CurrentPage.next_cursor -eq 0)
}
catch {
[PSCustomObject[]] $RawFollowersPages = @()
$_.Exception.Message
}
}
end {
Get-UnpagedFollowerList $RawFollowersPages
# $RawFollowersPages
}
}
Function Get-TweetsFromUser{
param(
[string]$UserName,
[int]$results = 20,
[switch]$quick,
[switch]$IncludeAll
)
# Get-TweetsFromUser cveira -results 250 -quick
# $DebugPreference = "Continue"
[PSObject[]] $TimeLine = @()
[PSObject[]] $tweets = @()
$SourcePattern = '((?s)<a[^>]*[^>]*>(?<TweetSource>.*?)</a>)'
$TwitterMaxResults = 100
$TimeToWait = 6
$ExtendedTimeToWait = 0
$TimeToWaitForRTs = 66
$TimeToWaitForFavs = 66
$IncludeRTs = $false
$IncludeFavorites = $false
if ($quick){
$IncludeAll = $false
$IncludeRTs = $false
$IncludeFavorites = $false
}
elseif ($IncludeAll){
$IncludeRTs = $true
$IncludeFavorites = $true
}
if ($TimeToWaitForRTs -ge $TimeToWaitForFavs){$ExtendedTimeToWait = $TimeToWaitForRTs}
else {$ExtendedTimeToWait = $TimeToWaitForFavs}
if ($results -lt $TwitterMaxResults){$tweets = Get-RawTweetsFromUserAsJson -UserName $UserName -results $results | ConvertFrom-Json}
else {
do {
Write-Progress -Activity "Retrieving Tweets ..." -Status "Progress: $($tweets.Count) / $results" -PercentComplete (($($tweets.Count) / $results) * 100)
$CurrentTweets = Get-RawTweetsFromUserAsJson -UserName $UserName -results $TwitterMaxResults -FirstId $LastId | ConvertFrom-Json
Write-Debug "[INFO] Retrieved Tweets: $($tweets.Count)"
Write-Debug "[INFO] CurrentTweets count: $($CurrentTweets.Count)"
Write-Debug "[INFO] LastId: $LastId"
Write-Debug "[INFO] FirstId: $($CurrentTweets[0].id)"
if ($CurrentTweets[0].id -eq $LastId){$FirstTweet = 1}
else {$FirstTweet = 0}
$LastId = $CurrentTweets[($CurrentTweets.Count -1)].id
$tweets += $CurrentTweets[ $FirstTweet..($CurrentTweets.Count - 1) ]
Start-Sleep -Seconds $TimeToWait
}
until ($tweets.Count -gt $results)
$tweets = $tweets[0..($results - 1)]
}
if ($quick){$tweets}
else {
$i = 1
$tweets | ForEach-Object {
if ($IncludeAll){
Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $results - ETC: $((($results - $i) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes - Time Elapsed: $((($i - 1) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes" -PercentComplete (($i / $results) * 100)
}
else {
Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $results" -PercentComplete (($i / $results) * 100)
}
$NewTweet = $_
$NewTweet.user = $NewTweet.user.screen_name
if ($NewTweet.source -match $SourcePattern){
$NewTweet.source = $Matches.TweetSource
}
Write-Debug ".Links not exists: $($NewTweet.Links -eq $null)"
if ($NewTweet.Links -eq $null){
$NewTweet | Add-Member -NotePropertyName Links -NotePropertyValue $NewTweet.entities.urls.expanded_url
}
else {
$NewTweet.Links = $NewTweet.entities.urls.expanded_url
}
Write-Debug ".HashTags not exists: $($null -eq $NewTweet.HashTags)"
if ($null -eq $NewTweet.HashTags){
$NewTweet | Add-Member -NotePropertyName HashTags -NotePropertyValue $NewTweet.entities.hashtags.text -force
}
else {
$NewTweet.HashTags = $NewTweet.entities.hashtags.text
}
Write-Debug ".Mentions not exists: $($null -eq $NewTweet.Mentions)"
if ($null -eq $NewTweet.Mentions){
$NewTweet | Add-Member -NotePropertyName Mentions -NotePropertyValue $NewTweet.entities.user_mentions.screen_name -force
}
else {
$NewTweet.Mentions = $NewTweet.entities.user_mentions.screen_name
}
Write-Debug ".PermaLink not exists: $($NewTweet.PermaLink -eq $null)"
if ($NewTweet.retweeted_status.user.screen_name -eq $null){
if ($NewTweet.PermaLink -eq $null){
$NewTweet | Add-Member -NotePropertyName PermaLink -NotePropertyValue "https://twitter.com/$($NewTweet.user)/status/$($NewTweet.id)"
}
else {
$NewTweet.PermaLink = "https://twitter.com/$($NewTweet.user)/status/$($NewTweet.id)"
}
}
else {
if ($NewTweet.PermaLink -eq $null){
$NewTweet | Add-Member -NotePropertyName PermaLink -NotePropertyValue "https://twitter.com/$($NewTweet.retweeted_status.user.screen_name)/status/$($NewTweet.retweeted_status.id)"
}
else {
$NewTweet.PermaLink = "https://twitter.com/$($NewTweet.retweeted_status.user.screen_name)/status/$($NewTweet.retweeted_status.id)"
}
}
Write-Debug "[INFO] PermaLink: $($NewTweet.PermaLink)"
if ($IncludeRTs){
if ($IncludeAll){
Write-Progress -Activity "Retrieving Retweets ..." -Status "Progress: $i / $results - ETC: $((($results - $i) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes - Time Elapsed: $((($i - 1) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes" -PercentComplete (($i / $results) * 100)
}
else {
Write-Progress -Activity "Retrieving Retweets ..." -Status "Progress: $i / $results" -PercentComplete (($i / $results) * 100)
}
Write-Debug ".retweets not exists: $($NewTweet.entities.retweets -eq $null)"
if ($NewTweet.entities.retweets -eq $null){
$NewTweet.entities | Add-Member -NotePropertyName retweets -NotePropertyValue @()
}
else {
$NewTweet.entities.retweets = @()
}
Write-Debug ".Interactions not exists: $($NewTweet.Interactions -eq $null)"
if ($NewTweet.Interactions -eq $null){
$NewTweet | Add-Member -NotePropertyName Interactions -NotePropertyValue @()
}
else {
$NewTweet.Interactions = @()
}
$NewTweet.entities.retweets = Get-RawTweetRetweetsAsJson $NewTweet.PermaLink | ConvertFrom-Json
# $NewTweet.retweet_count = $NewTweet.entities.retweets.Count
$NewTweet.Interactions += $NewTweet.entities.retweets | ForEach-Object {
New-Object PSObject -Property @{
screen_name = $_.user.screen_name
location = $_.user.location
}
}
Write-Debug "[INFO] Retrieved Retweets: $($NewTweet.entities.retweets.Count)"
Write-Debug "[INFO] Interactions: $($NewTweet.Interactions.Count)"
}
if ($IncludeFavorites){
if ($IncludeAll){
Write-Progress -Activity "Retrieving Favorites ..." -Status "Progress: $i / $results - ETC: $((($results - $i) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes - Time Elapsed: $((($i - 1) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes" -PercentComplete (($i / $results) * 100)
}
else {
Write-Progress -Activity "Retrieving Favorites ..." -Status "Progress: $i / $results" -PercentComplete (($i / $results) * 100)
}
Write-Debug ".favorites_count not exists: $($NewTweet.favorites_count -eq $null)"
if ($NewTweet.favorites_count -eq $null){
$NewTweet | Add-Member -NotePropertyName favorites_count -NotePropertyValue 0
}
else {
$NewTweet.favorites_count = 0
}
$SourceCode = Get-PageSourceCode $NewTweet.PermaLink
$NewTweet.favorites_count = Get-TweetFavoritesFromPage ([ref] $SourceCode)
Write-Debug "[INFO] Retrieved Favorites: $($NewTweet.favorites_count)"
}
if ($IncludeAll){Start-Sleep -Seconds $ExtendedTimeToWait }
$TimeLine += $NewTweet
$i++
}
$TimeLine
}# $DebugPreference = "SilentlyContinue"
}
Function Normalize-TwitterTimeLine{
param(
[PSObject[]]$TimeLine,
[switch]$IncludeAll
)
# $TimeLine = Normalize-TwitterTimeLine $tweets -IncludeAll
# $DebugPreference = "Continue"
[PSObject[]] $NewTimeLine = @()
$TimeToWait = 0
$TimeToWaitForRTs = 66
$TimeToWaitForFavs = 66
$SourcePattern = '((?s)<a[^>]*[^>]*>(?<TweetSource>.*?)</a>)'
$i = 1
$IncludeRTs = $false
$IncludeFavorites = $false
if ($IncludeAll){$IncludeRTs = $IncludeFavorites = $true}
if ($TimeToWaitForRTs -ge $TimeToWaitForFavs){$TimeToWait = $TimeToWaitForRTs}
else {$TimeToWait = $TimeToWaitForFavs}
$TimeLine | ForEach-Object {
$NewTweet = $_
if ($IncludeAll){Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $($TimeLine.Count) - ETC: $((($TimeLine.Count - $i)*($TimeToWaitForRTs + $TimeToWaitForFavs))/60) minutes - Time Elapsed: $((($i - 1)*($TimeToWaitForRTs + $TimeToWaitForFavs))/60) minutes" -PercentComplete (($i / $TimeLine.Count)* 100)}
else {Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $($TimeLine.Count)" -PercentComplete (($i / $TimeLine.Count) * 100)}
$NewTweet.user = $NewTweet.user.screen_name
if ($NewTweet.source -match $SourcePattern){$NewTweet.source = $Matches.TweetSource}
Write-Debug ".Links not exists: $($NewTweet.Links -eq $null)"
if ($NewTweet.Links -eq $null) {$NewTweet | Add-Member -NotePropertyName Links -NotePropertyValue $NewTweet.entities.urls.expanded_url}
else {$NewTweet.Links = $NewTweet.entities.urls.expanded_url}
Write-Debug ".HashTags not exists: $($null -eq $NewTweet.HashTags)"
if ($null -eq $NewTweet.HashTags) {$NewTweet | Add-Member -NotePropertyName HashTags -NotePropertyValue $NewTweet.entities.hashtags.text -force}
else {$NewTweet.HashTags = $NewTweet.entities.hashtags.text}
Write-Debug ".Mentions not exists: $($null -eq $NewTweet.Mentions)"
if ($null -eq $NewTweet.Mentions) {$NewTweet | Add-Member -NotePropertyName Mentions -NotePropertyValue $NewTweet.entities.user_mentions.screen_name -force}
else {$NewTweet.Mentions = $NewTweet.entities.user_mentions.screen_name}
Write-Debug ".PermaLink not exists: $($NewTweet.PermaLink -eq $null)"
if ($NewTweet.retweeted_status.user.screen_name -eq $null) {
if ($NewTweet.PermaLink -eq $null) {$NewTweet | Add-Member -NotePropertyName PermaLink -NotePropertyValue "https://twitter.com/$($NewTweet.user)/status/$($NewTweet.id)"}
else {$NewTweet.PermaLink = "https://twitter.com/$($NewTweet.user)/status/$($NewTweet.id)"}
}
else {
if ($NewTweet.PermaLink -eq $null) {$NewTweet | Add-Member -NotePropertyName PermaLink -NotePropertyValue "https://twitter.com/$($NewTweet.retweeted_status.user.screen_name)/status/$($NewTweet.retweeted_status.id)"}
else {$NewTweet.PermaLink = "https://twitter.com/$($NewTweet.retweeted_status.user.screen_name)/status/$($NewTweet.retweeted_status.id)"}
}
Write-Debug "[INFO] PermaLink: $($NewTweet.PermaLink)"
if ($IncludeRTs) {
if ($IncludeAll) {Write-Progress -Activity "Retrieving Retweets ..." -Status "Progress: $i / $($TimeLine.Count) - ETC: $((($TimeLine.Count - $i) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes - Time Elapsed: $((($i - 1) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes" -PercentComplete (($i / $TimeLine.Count) * 100) }
else {Write-Progress -Activity "Retrieving Retweets ..." -Status "Progress: $i / $($TimeLine.Count)" -PercentComplete (($i / $TimeLine.Count) * 100) }
Write-Debug ".retweets not exists: $($NewTweet.entities.retweets -eq $null)"
if ($NewTweet.entities.retweets -eq $null) {$NewTweet.entities | Add-Member -NotePropertyName retweets -NotePropertyValue @() }
else {$NewTweet.entities.retweets = @() }
Write-Debug ".Interactions not exists: $($NewTweet.Interactions -eq $null)"
if ($NewTweet.Interactions -eq $null) {$NewTweet | Add-Member -NotePropertyName Interactions -NotePropertyValue @() }
else {$NewTweet.Interactions = @() }
$NewTweet.entities.retweets = Get-RawTweetRetweetsAsJson $NewTweet.PermaLink | ConvertFrom-Json
# $NewTweet.retweet_count = $NewTweet.entities.retweets.Count
$NewTweet.Interactions += $NewTweet.entities.retweets | ForEach-Object {
New-Object PSObject -Property @{
screen_name = $_.user.screen_name
location = $_.user.location
}
}
Write-Debug "[INFO] Retrieved Retweets: $($NewTweet.entities.retweets.Count)"
Write-Debug "[INFO] Interactions: $($NewTweet.Interactions.Count)"
}
if ($IncludeFavorites) {
if ($IncludeAll) {Write-Progress -Activity "Retrieving Favorites ..." -Status "Progress: $i / $($TimeLine.Count) - ETC: $((($TimeLine.Count - $i) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes - Time Elapsed: $((($i - 1) * ($TimeToWaitForRTs + $TimeToWaitForFavs)) / 60) minutes" -PercentComplete (($i / $TimeLine.Count) * 100) }
else {Write-Progress -Activity "Retrieving Favorites ..." -Status "Progress: $i / $($TimeLine.Count)" -PercentComplete (($i / $TimeLine.Count) * 100) }
Write-Debug ".favorites_count not exists: $($NewTweet.favorites_count -eq $null)"
if ($NewTweet.favorites_count -eq $null) {$NewTweet | Add-Member -NotePropertyName favorites_count -NotePropertyValue 0 }
else {$NewTweet.favorites_count = 0 }
$SourceCode = Get-PageSourceCode $NewTweet.PermaLink
$NewTweet.favorites_count = Get-TweetFavoritesFromPage ([ref] $SourceCode)
Write-Debug "[INFO] Retrieved Favorites: $($NewTweet.favorites_count)"
}
if ($IncludeAll) {Start-Sleep -Seconds $TimeToWait }
$NewTimeLine += $NewTweet
$i++
}# end $TimeLine foreach
# $DebugPreference = "SilentlyContinue"
$NewTimeLine
}
Function Analyze-TwitterHasTags() {
begin {
$HashTags = @{}
[PSObject[]] $ranking = @()
}
process {
$post = $_
$post.HashTags | ForEach-Object {
if ($HashTags.ContainsKey("$_")) { $HashTags["$_"] = $HashTags["$_"] + 1 }
else { $HashTags.Add("$_", 1) }
}
}
end {
$HashTags.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
HashTag = $_
Count = $HashTags.$_
}
}
return $ranking
}
}
Function Analyze-TwitterMentions() {
begin {
$Mentions = @{}
[PSObject[]] $ranking = @()
}
process {
$post = $_
$post.Mentions | ForEach-Object {
if ($Mentions.ContainsKey("$_")) { $Mentions["$_"] = $Mentions["$_"] + 1 }
else { $Mentions.Add("$_", 1) }
}
}
end {
$Mentions.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
User = $_
Count = $Mentions.$_
}
}
return $ranking
}
}
Function Analyze-TwitterTimeProfile([string] $range = 'month') {
begin {
$Hours = @{}
$DaysOfWeek = @{}
$Days = @{}
$Months = @{}
$Years = @{}
[PSObject[]] $ranking = @()
$DAY_OF_WEEK = 0
$MONTH = 1
$DAY = 2
$HOUR = 3
$YEAR = 5
}
process {
$post = $_
$CreationDate = $post.created_at.Split(" ")
$CurrentDayOfWeek = $CreationDate[$DAY_OF_WEEK]
$CurrentDay = $CreationDate[$DAY]
$CurrentMonth = $CreationDate[$MONTH]
$CurrentYear = $CreationDate[$YEAR]
$CurrentHour = $CreationDate[$HOUR].Split(":")[0]
switch ($range.ToLower()) {
"hour" {
if ($Hours.ContainsKey("$CurrentHour")) { $Hours["$CurrentHour"] = $Hours["$CurrentHour"] + 1 }
else { $Hours.Add("$CurrentHour", 1) }
}
"DayOfWeek" {
if ($DaysOfWeek.ContainsKey("$CurrentDayOfWeek")) { $DaysOfWeek["$CurrentDayOfWeek"] = $DaysOfWeek["$CurrentDayOfWeek"] + 1 }
else { $DaysOfWeek.Add("$CurrentDayOfWeek", 1) }
}
"day" {
if ($Days.ContainsKey("$CurrentDay")) { $Days["$CurrentDay"] = $Days["$CurrentDay"] + 1 }
else { $Days.Add("$CurrentDay", 1) }
}
"month" {
if ($Months.ContainsKey("$CurrentMonth")) { $Months["$CurrentMonth"] = $Months["$CurrentMonth"] + 1 }
else { $Months.Add("$CurrentMonth", 1) }
}
"year" {
if ($Years.ContainsKey("$CurrentYear")) { $Years["$CurrentYear"] = $Years["$CurrentYear"] + 1 }
else { $Years.Add("$CurrentYear", 1) }
}
default {
if ($Months.ContainsKey("$CurrentMonth")) { $Months["$CurrentMonth"] = $Months["$CurrentMonth"] + 1 }
else { $Months.Add("$CurrentMonth", 1) }
}
}
}
end {
switch ($range.ToLower()) {
"hour" {
$Hours.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
Hour = $_
Count = $Hours.$_
}
}
}
"DayOfWeek" {
$DaysOfWeek.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
DayOfWeek = $_
Count = $DaysOfWeek.$_
}
}
}
"day" {
$Days.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
Day = $_
Count = $Days.$_
}
}
}
"month" {
$Months.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
Month = $_
Count = $Months.$_
}
}
}
"year" {
$Years.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
Year = $_
Count = $Years.$_
}
}
}
default {
$Months.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
Month = $_
Count = $Months.$_
}
}
}
}
return $ranking
}
}
Function Analyze-TwitterInteractions() {
begin {
$Interactions = @{}
[PSObject[]] $ranking = @()
}
process {
$post = $_
$post.Interactions.screen_name | ForEach-Object {
if ($Interactions.ContainsKey("$_")) { $Interactions["$_"] = $Interactions["$_"] + 1 }
else { $Interactions.Add("$_", 1) }
}
}
end {
$Interactions.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
User = $_
Count = $Interactions.$_
}
}
return $ranking
}
}
Function Analyze-TwitterLocations() {
begin {
$Locations = @{}
[PSObject[]] $ranking = @()
}
process {
$post = $_
if ($post.Connections.location -eq $null) {$LocationInfo = $post.location}
else {$LocationInfo = $post.Connections.location}
$LocationInfo | ForEach-Object {
if ($Locations.ContainsKey("$_")) { $Locations["$_"] = $Locations["$_"] + 1 }
else { $Locations.Add("$_", 1) }
}
}
end {
$Locations.keys | ForEach-Object {
$ranking += New-Object PSObject -Property @{
Location = $_
Count = $Locations.$_
}
}
return $ranking
}
}
Function Rebuild-TwitterTimeLine([PSObject[]] $from) {
[PSObject[]] $TimeLine = @()
$TimeToWait = 6
$i = 1
$ExecutionTime = [Diagnostics.Stopwatch]::StartNew()
$from | ForEach-Object {
if ($SourceSchema.count -eq 0) {
$SourceSchema = $_ | Get-Member -MemberType NoteProperty | ForEach-Object {$_.Name }
$PropertyName = GetMatchesInCollection "PermaLink" $SourceSchema
}
$ExecutionTime.Stop()
Write-Progress -Activity "Retrieving tweets ..." -Status "Progress: $i / $($from.Count) - ETC: $('{0:#0.00}' -f (($from.Count - $i) * $ExecutionTime.Elapsed.TotalMinutes)) minutes - Time Elapsed: $('{0:#0.00}' -f (($i - 1) * $ExecutionTime.Elapsed.TotalMinutes)) minutes" -PercentComplete (($i / $from.Count) * 100)
$ExecutionTime = [Diagnostics.Stopwatch]::StartNew()
if ($_.$PropertyName -match "twitter.com") {
$TimeLine += Get-RawTweetAsJson $_.$PropertyName | ConvertFrom-Json
Start-Sleep -Seconds $TimeToWait
}
else { Write-Host -foregroundcolor $COLOR_BRIGHT " INFO: Skipping non-Twitter post: $($_.$PropertyName)"}
$i++
}
return $TimeLine
}
Function Get-TwitterSearch{
param(
[string] $query,
[int] $results = 20,
[string] $language = "",
[string] $type = "mixed",
[string] $StartDate = "",
[string] $GeoCode = ""
)
# Get-TwitterSearch -query "#cloud" -results 250
# $DebugPreference = "Continue"
[PSObject[]] $tweets = @()
$TwitterMaxResults = 100
$SecondsToWait = 6
[int64] $MaxId = 0
if (($type -ne "recent") -and ($type -ne "popular")) {$type = "mixed" }
if (-not (($StartDate -ne "") -and ($StartDate -match "\\d{4}-\\d{2}-\\d{2}"))) {$StartDate = "" }
if (-not (($GeoCode -ne "") -and ($GeoCode -match "(\\-*[\\d\\.]+),(\\-*[\\d\\.]+),(\\d+)(km|mi)"))) {$GeoCode = "" }
if (-not (($language -ne "") -and ($language -match "\\w{2}"))) {$language = "" }
if ($results -lt $TwitterMaxResults) {$tweets = (Get-RawTwitterSearchAsJson -query $query -ResultsPerPage $results -Language $language -ResultType $type -StartDate $StartDate -GeoCode $GeoCode).statuses | ConvertFrom-Json }
else {
$MaxId = 0
$ExecutionTime = [Diagnostics.Stopwatch]::StartNew()
do {
$ExecutionTime.Stop()
Write-Progress -Activity "Retrieving Tweets ..." -Status "Progress: $($tweets.Count) / $results - ETC: $('{0:#0.00}' -f (($results - $($tweets.Count)) * $ExecutionTime.Elapsed.TotalMinutes)) minutes - Time Elapsed: $('{0:#0.00}' -f (($($tweets.Count) - 1) * $ExecutionTime.Elapsed.TotalMinutes)) minutes" -PercentComplete (($($tweets.Count) / $results) * 100)
$ExecutionTime = [Diagnostics.Stopwatch]::StartNew()
if ($MaxId -eq 0) {$CurrentTweets = Get-RawTwitterSearchAsJson -query $query -ResultsPerPage $TwitterMaxResults -Language $language -ResultType $type -StartDate $StartDate -GeoCode $GeoCode | ConvertFrom-Json}
else {
$CurrentTweets = Get-RawTwitterSearchAsJson -query $query -ResultsPerPage $TwitterMaxResults -Language $language -ResultType $type -StartDate $StartDate -GeoCode $GeoCode -MaxId ($MaxId - 1) | ConvertFrom-Json
if ($CurrentTweets.statuses.count -eq 0) {break}
}
Write-Debug "[INFO] Retrieved Tweets: $($tweets.Count)"
Write-Debug "[INFO] CurrentTweets count: $($CurrentTweets.statuses.Count)"
Write-Debug "[INFO] CurrentTweets metadata count: $($CurrentTweets.search_metadata.count)"
Write-Debug "[INFO] MaxId: $MaxId"
$MaxId = $CurrentTweets.search_metadata.max_id
$tweets += $CurrentTweets.statuses
Start-Sleep -Seconds $SecondsToWait
}
until ($tweets.Count -gt $results)
if ($tweets.count -gt $results) { $tweets = $tweets[0..($results - 1)] }
}
return $tweets
# $DebugPreference = "SilentlyContinue"
}
|
PowerShellCorpus/PoshCode/Read-HostWithPrompt_1.ps1
|
Read-HostWithPrompt_1.ps1
|
#############################################################################
##
## Read-HostWithPrompt
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Read user input, with choices restricted to the list of options you
provide.
.EXAMPLE
PS >$caption = "Please specify a task"
PS >$message = "Specify a task to run"
PS >$option = "&Clean Temporary Files","&Defragment Hard Drive"
PS >$helptext = "Clean the temporary files from the computer",
>> "Run the defragment task"
>>
PS >$default = 1
PS >Read-HostWithPrompt $caption $message $option $helptext $default
Please specify a task
Specify a task to run
[C] Clean Temporary Files [D] Defragment Hard Drive [?] Help
(default is "D"):?
C - Clean the temporary files from the computer
D - Run the defragment task
[C] Clean Temporary Files [D] Defragment Hard Drive [?] Help
(default is "D"):C
0
#>
param(
## The caption for the prompt
$Caption = $null,
## The message to display in the prompt
$Message = $null,
## Options to provide in the prompt
[Parameter(Mandatory = $true)]
$Option,
## Any help text to provide
$HelpText = $null,
## The default choice
$Default = 0
)
Set-StrictMode -Version Latest
## Create the list of choices
$choices = New-GenericObject `
Collections.ObjectModel.Collection `
Management.Automation.Host.ChoiceDescription
## Go through each of the options, and add them to the choice collection
for($counter = 0; $counter -lt $option.Length; $counter++)
{
$choice = New-Object Management.Automation.Host.ChoiceDescription `
$option[$counter]
if($helpText -and $helpText[$counter])
{
$choice.HelpMessage = $helpText[$counter]
}
$choices.Add($choice)
}
## Prompt for the choice, returning the item the user selected
$host.UI.PromptForChoice($caption, $message, $choices, $default)
|
PowerShellCorpus/PoshCode/ConvertFrom-Property_1.ps1
|
ConvertFrom-Property_1.ps1
|
<#
.SYNOPSIS
Converts data from flat or single-level property files into PSObjects
.DESCRIPTION
Converts delimited string data into objects
.PARAMETER PropertyText
The text to be parsed
.PARAMETER Separator
The value separator string used between name=value pairs. Allows regular expressions.
Defaults to "=" and is usually either "=" or ":" or ";"
.PARAMETER Delimiter
The property separator string used between sets of name=value pairs. Allows regular expressions.
Defaults to "\\n\\s*\\n?" and is usually either "`n" or "`n`n" or "\\n\\s*\\n"
.PARAMETER RecordSeparator
The record separator string is used between records or sections in a text file.
Defaults to "\\n\\[(.+)\\]\\s*\\n" for ini files, and is usually either "\\n\\s*\\n" or "\\n\\[(.*)\\]\\s*\\n"
To support named sections or records, make sure to use a regular expression here that has a capture group defined.
.EXAMPLE
ConvertFrom-PropertyString config.ini
Reads in an ini file (which has key=value pairs), using the default settings
.EXAMPLE
@"
ID:3468
Type:Developer
StartDate:1998-02-01
Code:SWENG3
Name:Baraka
ID:11234
Type:Management
StartDate:2005-05-21
Code:MGR1
Name:Jax
"@ |ConvertFrom-PropertyString -sep ":" -RecordSeparator "\\r\\n\\s*\\r\\n" | Format-Table
Code StartDate Name ID Type
---- --------- ---- -- ----
SWENG3 1998-02-01 Baraka 3468 Developer
MGR1 2005-05-21 Jax 11234 Management
Reads records from a key:value property file with records separated by blank lines.
.EXAMPLE
ConvertFrom-PropertyString data.txt -Separator ":"
Reads in a property file which has key:value pairs
.EXAMPLE
Get-Content data.txt -Delimiter "`r`n`r`n" | ConvertFrom-PropertyString -Separator ";"
Reads in a property file with key;value pairs, and sections separated by blank lines, and converts it to objects
.EXAMPLE
ConvertFrom-PropertyString data.txt -delimiter '\\r\\n\\r\\n' -Separator ";"
Reads in a property file with key;value pairs, and sections separated by blank lines, and converts it to objects
.EXAMPLE
ConvertFrom-PropertyString data.txt -RecordSeparator "^;(.*?)\\r*\\n" -Separator ";"
Reads in a property file with key:value pairs, and sections with a header that starts with the comment character ';'
.NOTES
v2 changes the output so that if there are multiple instances of the same key, we collect the values in an array
#>
#function ConvertFrom-PropertyString {
[CmdletBinding(DefaultParameterSetName="Data")]
param(
[Parameter(Position=99, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Data")]
[Alias("Data","Content")]
[string]$RecordText
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PSPath","FileName")]
[string]$InputFile
,
[Parameter()][Alias("ValueSeparator")]
[String]$Separator='='
,
[Parameter()][Alias("PropertySeparator")]
[String]$Delimiter='(?:\\s*\\n+\\s*)+'
,
[Parameter()]
[String]$RecordSeparator='(?:\\n|^)\\[([^\\]]+)\\]\\s*\\n'
,
[Parameter(ParameterSetName="Data")]
[Alias("MultiRecords","MR")]
[Switch]$MultipleRecords
)
begin {
$Splitter = New-Object System.Text.RegularExpressions.Regex ([System.String]$RecordSeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
process {
Write-Verbose "ParameterSet: $($PSCmdlet.ParameterSetName)"
$InputData = @{}
if($PSCmdlet.ParameterSetName -eq "File") {
$MultipleRecords = $true
$RecordText = Get-Content $InputFile -Delimiter ([char]0)
}
if($PsBoundParameters.ContainsKey("RecordSeparator")) {
$MultipleRecords = $true
}
if($MultipleRecords) {
$Records = $splitter.Split( $RecordText ) | ? { $_ }
if($Splitter.GetGroupNumbers().Count -gt 1) {
while($Records) {
$key,$value,$Records = $Records
$InputData.$Key += @($value)
}
} else {
$InputData."" = $Records
}
} else {
$InputData."" = @($RecordText)
}
foreach($key in $InputData.Keys) {
foreach($record in $InputData.$key) {
Write-Verbose "Record: $record"
if($Key) { $output = @{"PSName"=$key} }
elseif($InputFile) { $output = @{"PSName"=((get-item $InputFile).PSChildName)} }
else{ $output = @{} }
foreach($line in $record -split $Delimiter) {
[string[]]$data = $line -split $Separator,2 | foreach { $_.Trim() } | where { $_ }
Write-Verbose "Line: $Line | Data: $($data -join '--')"
switch($data.Count) {
1 { $output.($Data[0]) += @($null) }
2 { $output.($Data[0]) += @($Data[1]) }
}
}
foreach($key in $Output.Keys | Where { $Output.$_.Count -eq 1 } ) {
$Output.$key = $Output.$key[0]
}
if($output.Count) {
New-Object PSObject -Property $output
}
}
}
}
#}
|
PowerShellCorpus/PoshCode/mklink.ps1
|
mklink.ps1
|
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace mklink
{
class mklink
{
[DllImport("kernel32.dll")]
static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
static void Main(string[] args)
{
int dirlink = 0;
int c = 0;
string[] paths = new string[0];
Console.WriteLine("MKLINK - Create a symbolic or directory link. MKLINK -help for usage. Created in 2010 by James Gentile.");
foreach (string a in args)
{
if ((System.String.Compare(a, "-help", true) == 0) || (System.String.Compare(a, "-H", true) == 0))
{
Console.WriteLine("MKLINK [/D] <Symbolic Link> <file or directory source>");
return;
}
if (System.String.Compare(a, @"/d", true) == 0)
{
dirlink = 1;
continue;
}
Array.Resize(ref paths, paths.Length + 1);
paths[c] = a;
c++;
}
if (paths.Length != 2)
{
Console.WriteLine("Requires a <symbolic link> and <file or directory> source.");
return;
}
try
{
if (CreateSymbolicLink(paths[0], paths[1], dirlink))
Console.WriteLine("Symblic link created for " + paths[0] + " <<===>> " + paths[1]);
}
catch (Exception e)
{
Console.WriteLine("Error creating symbolic link: " + e.Message);
}
}
}
}
|
PowerShellCorpus/PoshCode/Prompt _for ISE_.ps1
|
Prompt _for ISE_.ps1
|
# just to know which file is invoked by my profile
write-host "loaded . $($MyInvocation.MyCommand.Path)"
if(!$global:WindowTitlePrefix) {
# But if you're running "elevated" on vista, we want to show that ...
if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista and ...
new-object Security.Principal.WindowsPrincipal (
[Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) )
{
##$Isadmin = $True
$global:WindowTitlePrefix = "PoSh V2 (CTP3) (ADMIN)"
#(get-host).UI.RawUI.Backgroundcolor="DarkRed"
$psise.options.CommandPaneBackground = 'pink'
clear-host
} else {
##$Isadmin = $False
$global:WindowTitlePrefix = "PoSh V2 (CTP3)"
}
}
function prompt {
# FIRST, make a note if there was an error in the previous command
$err = !$?
# Make sure Windows and .Net know where we are (they can only handle the FileSystem)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
# Also, put the path in the title ... (don't restrict this to the FileSystem
$Host.UI.RawUI.WindowTitle = "{0} - {1}/{2}@{3}" -f $global:WindowTitlePrefix, $env:USERDOMAIN, $env:USERNAME, $env:COMPUTERNAME
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# my New-Script and Get-PerformanceHistory functions use history IDs
# So, put the ID of the command in, so we can get/invoke-history easier
# eg: "r 4" will re-run the command that has [4]: in the prompt
$nextCommandId = (Get-History -count 1).Id + 1
# Output prompt string
# If there's an error, set the prompt foreground to "Red", otherwise, "DarkBlue"
if($err) { $fg = "Red" } else { $fg = "DarkBlue" }
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "[${Nesting}${nextCommandId}${Stack}]" -NoNewLine -Fore $fg
# "{0} - {1}/{2}@{3} {4} ({5})`n" -f $global:WindowTitlePrefix, $env:USERDOMAIN, $env:USERNAME, $env:COMPUTERNAME, $pwd.Path, $pwd.Provider.Name
"{0} ({1})`n" -f $pwd.Path, $pwd.Provider.Name
}
|
PowerShellCorpus/PoshCode/Get-ComputerSession.ps1
|
Get-ComputerSession.ps1
|
Function Get-ComputerSession {
<#
.SYNOPSIS
Retrieves all user sessions from local or remote server/s
.DESCRIPTION
Retrieves all user sessions from local or remote server/s. Requires query.exe in order to run properly.
.PARAMETER computer
Name of computer/s to run session query against.
.NOTES
Name: Get-ComputerSession
Author: Boe Prox
DateCreated: 01Nov2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-ComputerSessions -computer "server1"
Description
-----------
This command will query all current user sessions on 'server1'.
#>
[cmdletbinding(
DefaultParameterSetName = 'session',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ValueFromPipeline = $True)]
[string[]]$computer
)
Begin {
$report = @()
}
Process {
ForEach($c in $computer) {
# Parse 'query session' and store in $sessions:
$sessions = query session /server:$c
1..($sessions.count -1) | % {
$temp = "" | Select Computer,SessionName, Username, Id, State, Type, Device
$temp.Computer = $c
$temp.SessionName = $sessions[$_].Substring(1,18).Trim()
$temp.Username = $sessions[$_].Substring(19,20).Trim()
$temp.Id = $sessions[$_].Substring(39,9).Trim()
$temp.State = $sessions[$_].Substring(48,8).Trim()
$temp.Type = $sessions[$_].Substring(56,12).Trim()
$temp.Device = $sessions[$_].Substring(68).Trim()
$report += $temp
}
}
}
End {
$report
}
}
|
PowerShellCorpus/PoshCode/Experimental.IO 1.0.ps1
|
Experimental.IO 1.0.ps1
|
## Requires the Experimental.IO "LongPath" library from the BCL team: http://bcl.codeplex.com/
## Compile it against .Net 3.5 (for PowerShell's sake) and place it the module folder with this psm1
if(!("Microsoft.Experimental.IO.LongPathDirectory" -as [type])) {
Add-Type -Path $PSScriptRoot\\Microsoft.Experimental.IO.dll
}
function Get-LongPath {
[CmdletBinding(DefaultParameterSetName="AllItems")]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
[string]$Path = $pwd
,
[Parameter(ParameterSetName="DirectoriesOnly")]
[Alias("od","do")]
[switch]$DirectoriesOnly
,
[Parameter(ParameterSetName="FilesOnly")]
[Alias("of","fo")]
[switch]$FilesOnly
,
[switch]$Recurse
,
[switch]$Indent
)
begin {
if($Recurse -and $Indent -and (Test-Path variable:script:pad)) {
$script:pad += " "
} else {
$script:pad = ""
}
$null = $PSBoundParameters.Remove("Path")
if($PSCmdlet.ParameterSetName -eq "FilesOnly") {
Write-Verbose $Path
}
}
process {
switch($PSCmdlet.ParameterSetName) {
"FilesOnly" {
if($Recurse) {
[Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFileSystemEntries( $Path ) | %{
if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists( $_ ) ) {
Get-LongPath $_ @PSBoundParameters
} else {
$script:pad + $_
}
}
} else {
[Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFiles( $Path )
}
}
"DirectoriesOnly" {
if($Recurse) {
[Microsoft.Experimental.IO.LongPathDirectory]::EnumerateDirectories( $Path ) | %{
$script:pad + $_ + "\\"
if($recurse) {
Get-LongPath $_ @PSBoundParameters
}
}
} else {
[Microsoft.Experimental.IO.LongPathDirectory]::EnumerateDirectories( $Path )
}
}
"AllItems" {
if($recurse) {
[Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFileSystemEntries( $Path ) | %{
if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists( $_ ) ) {
$script:pad + $_ + "\\"
Get-LongPath $_ @PSBoundParameters
} else {
$script:pad + $_
}
}
} else {
[Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFileSystemEntries( $Path )
}
}
}
}
end {
if($Indent) {
if($script:pad.Length -gt 0) {
$script:pad = $script:pad.SubString(0, $script:pad.Length - 2)
} else {
remove-item variable:script:pad -EA 0
}
}
}
}
|
PowerShellCorpus/PoshCode/ConvertTo-Module_1.ps1
|
ConvertTo-Module_1.ps1
|
function ConvertTo-Module {
<#
.SYNOPSIS
Quickly convert a .NET type's static methods into functions
.DESCRIPTION
Quickly convert a .NET type's static methods into functions.
This function returns a PSModuleInfo, so you should pipe its
output to Import-Module to use the exported functions.
.PARAMETER Type
The type from which to import static methods.
.INPUTS
System.String, System.Type
.OUTPUTS
PSModuleInfo
.EXAMPLE
ConvertTo-Module System.Math | Import-Module -Verbose
.EXAMPLE
[math] | ConvertTo-Module | Import-Module -Verbose
#>
[outputtype([psmoduleinfo])]
param(
[parameter(
position=0,
valuefrompipeline=$true,
mandatory=$true)]
[validatenotnull()]
[type]$Type
)
new-module {
param($type)
($exports = $type.getmethods("static,public").Name | sort -uniq) | `
% {
$func = $_
new-item "function:script:$($_)" `
-Value {
# look mom! no [scriptblock]::create!
@@ ($type.FullName -as [type])::$func.invoke($args)
}.GetNewClosure() # capture the value of $func
}
export-modulemember -function $exports
} -name $type.Name -ArgumentList $type
}
|
PowerShellCorpus/PoshCode/Get-RemoteRegistryKeyPro.ps1
|
Get-RemoteRegistryKeyPro.ps1
|
##############################################################################\n##\n## Get-RemoteRegistryKeyProperty\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nGet the value of a remote registry key property\n\n.EXAMPLE\n\nPS >$registryPath =\n "HKLM:\\software\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell"\nPS >Get-RemoteRegistryKeyProperty LEE-DESK $registryPath ExecutionPolicy\n\n#>\n\nparam(\n ## The computer that you wish to connect to\n [Parameter(Mandatory = $true)]\n $ComputerName,\n\n ## The path to the registry item to retrieve\n [Parameter(Mandatory = $true)]\n $Path,\n\n ## The specific property to retrieve\n $Property = "*"\n)\n\nSet-StrictMode -Version Latest\n\n## Validate and extract out the registry key\nif($path -match "^HKLM:\\\\(.*)")\n{\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(\n "LocalMachine", $computername)\n}\nelseif($path -match "^HKCU:\\\\(.*)")\n{\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(\n "CurrentUser", $computername)\n}\nelse\n{\n Write-Error ("Please specify a fully-qualified registry path " +\n "(i.e.: HKLM:\\Software) of the registry key to open.")\n return\n}\n\n## Open the key\n$key = $baseKey.OpenSubKey($matches[1])\n$returnObject = New-Object PsObject\n\n## Go through each of the properties in the key\nforeach($keyProperty in $key.GetValueNames())\n{\n ## If the property matches the search term, add it as a\n ## property to the output\n if($keyProperty -like $property)\n {\n $returnObject |\n Add-Member NoteProperty $keyProperty $key.GetValue($keyProperty)\n }\n}\n\n## Return the resulting object\n$returnObject\n\n## Close the key and base keys\n$key.Close()\n$baseKey.Close()
|
PowerShellCorpus/PoshCode/Networker - Delete ssids_1.ps1
|
Networker - Delete ssids_1.ps1
|
Write-Host ""
Write-Host "This is dangerous - beware!"
Write-Host "Type: delssids client.domain.com to DELETE ALL it's SAVESETS!!"
function delssids {
## warning - no checks on first arg, security hole! ;)
$client = $args[0]
$ssids = (mminfo -av -q "client=$client" -r ssid)
$ssids | ForEach-Object { nsrmm -d -S $_ -y }
Write-Host "Removed SSID $_ "
}
|
PowerShellCorpus/PoshCode/Start-Verify_3.ps1
|
Start-Verify_3.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.
# Modified to add the logging at the beginning of the Prompt function, otherwise it appeared to
# impact some functions display options. I also added some verification to see that the log directory
# exists and to create it if not.
# The format operator doesn't like scriptblocks in the string it is doing the replacement into
# .. should be the last for a while.
function New-ScriptBlock()
{
param ([string]$scriptblock)
$executioncontext.InvokeCommand.NewScriptBlock($scriptblock.trim())
}
function Start-Verify ()
{
param ($logfile = 'c:\\scripts\\powershell\\logs\\verify.txt')
#if the log folder does not exist, create one
if (-not (test-path (split-path $logfile)))
{
mkdir (Split-Path $logfile) | Out-Null
}
$lastcmd = 'get-history | select -Last 1 | Foreach-Object { $_.CommandLine.ToString() } | Out-File -Append ' + $logfile
Get-Content -Path function:\\prompt | ForEach-Object { $function:prompt = New-ScriptBlock ("$lastcmd;`n" + $_.toString()) } | 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/Rollback Policy Module.ps1
|
Rollback Policy Module.ps1
|
Function Get-RollbackPolicy {
<#
.SYNOPSIS
Retieves the current rollback policy on a local or remote computer
.DESCRIPTION
Retieves the current rollback policy on a local or remote computer
.PARAMETER Computername
The name of the computer or computers to perform the query against
.NOTES
Name: Get-RollbackPolicy
Author: Boe Prox
DateCreated: 06/24/2011
Links:
.EXAMPLE
Get-RollbackPolicy -Computername DC1
Rollback Computer
-------- --------
Enabled dc1
Description
-----------
Performs a query against the server, DC1 and returns whether the rollback setting has been enabled
or disabled.
.EXAMPLE
Get-RollbackPolicy -Computername DC1,server1,server2
Rollback Computer
-------- --------
Enabled dc1
Disabled server1
Enabled server2
Description
-----------
Performs a query against the server, DC1 and returns whether the rollback setting has been enabled
or disabled.
#>
[cmdletbinding()]
Param (
[parameter()]
[string[]]$Computername
)
Process {
ForEach ($computer in $computername) {
Try {
#Make initial registry connection
Write-Verbose "Making registry connection to remote computer"
$registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computer)
#Connect to the subkey where the rollback is located
Write-Verbose "Making registry connection to 'Software' key"
If ($registry.GetSubkeyNames() -contains "Software") {
$subkey = $registry.OpenSubKey("Software",$True)
Write-Verbose "Making registry connection to 'Policies' key"
If ($subkey.GetSubKeyNames() -contains "Policies") {
$subkey = $subkey.OpenSubKey("Policies",$True)
Write-Verbose "Making registry connection to 'Microsoft' key"
If ($subkey.GetSubKeyNames() -contains "Microsoft") {
$subkey = $subkey.OpenSubKey("Microsoft",$True)
Write-Verbose "Making registry connection to 'Windows' key"
If ($subkey.GetSubKeyNames() -contains "Windows") {
$subkey = $subkey.OpenSubKey("Windows",$True)
Write-Verbose "Making registry connection to 'Installer' key"
If ($subkey.GetSubKeyNames() -contains "Installer") {
$subkey = $subkey.OpenSubKey("Installer",$True)
Write-Verbose "Checking to see if 'DisableRollback' value name exists"
If ($subkey.GetValueNames() -contains "DisableRollback") {
#Get the value of DisableRollback
Write-Verbose "Retrieving value of 'DisableRollback'"
$value = $subkey.GetValue('DisableRollback')
Switch ($value) {
0 {$hash = @{Computer = $computer;Rollback = "Enabled"}}
1 {$hash = @{Computer = $computer;Rollback = "Disabled"}}
Default {$hash = @{Computer = $computer;Rollback = "Unknown"}}
}
}
Else {
Write-Warning "$($computer): Missing 'DisableRollback' value name in registy!"
$hash = @{Computer = $computer;Rollback = "Missing DisableRollback value name"}
}
}
Else {
Write-Warning "$($computer): Missing 'Installer' key in registy!"
$hash = @{Computer = $computer;Rollback = "Missing Installer key"}
}
}
Else {
Write-Warning "$($computer): Missing 'Windows' key in registy!"
$hash = @{Computer = $computer;Rollback = "Missing Windows key"}
}
}
Else {
Write-Warning "$($computer): Missing 'Microsoft' key in registy!"
$hash = @{Computer = $computer;Rollback = "Missing Microsoft key"}
}
}
Else {
Write-Warning "$($computer): Missing 'Policies' key in registy!"
$hash = @{Computer = $computer;Rollback = "Missing Policies key"}
}
}
Else {
Write-Warning "$($computer): Missing 'Software' key in registy!"
$hash = @{Computer = $computer;Rollback = "Missing Software key"}
}
}
Catch {
Write-Warning "$($computer): $($Error[0])"
$hash = @{Computer = $computer;Rollback = ($error[0].exception.innerexception.message -split "`n")[0]}
}
Finally {
$object = New-Object PSObject -Property $hash
$object.PSTypeNames.Insert(0,'RollbackStatus')
Write-Output $object
}
}
}
}
Function Disable-RollbackPolicy {
<#
.SYNOPSIS
Disables the rollback policy on a local or remote computer
.DESCRIPTION
Disables the rollback policy on a local or remote computer
.PARAMETER Computername
The name of the computer or computers to disable the rollback policy on
.PARAMETER Passthru
Displays the returned object after disabling the policy.
.NOTES
Name: Disable-RollbackPolicy
Author: Boe Prox
DateCreated: 06/24/2011
Links:
.EXAMPLE
Disable-RollbackPolicy -Computername DC1 -Passthru
Rollback Computer
-------- --------
Disabled DC1
Description
-----------
This disables the rollback policy on DC1 and returns the object showing that the policy has
been disabled.
.EXAMPLE
Disable-RollbackPolicy -Computername DC1,server1,server2 -Passthru
Rollback Computer
-------- --------
Disabled DC1
Disabled server1
Disabled server2
Description
-----------
This disables the rollback policy on DC1,server1 and server2 and returns the object showing that the policy has
been disabled.
#>
[cmdletbinding(
SupportsShouldProcess = 'True'
)]
Param (
[parameter()]
[string[]]$Computername,
[parameter()]
[Switch]$Passthru
)
Process {
ForEach ($computer in $computername) {
Try {
#Make initial registry connection
Write-Verbose "Making registry connection to remote computer"
$registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computer)
If ($PScmdlet.ShouldProcess("$computer","Disable Rollback")) {
#Connect to the subkey where the rollback is located
Write-Verbose "Making registry connection to 'Software' key"
If ($registry.GetSubkeyNames() -notcontains "Software") {
$registry.CreateSubKey("Software")
$subkey = $registry.OpenSubKey("Software",$True)
}
Else {
$subkey = $registry.OpenSubKey("Software",$True)
}
Write-Verbose "Making registry connection to 'Policies' key"
If ($subkey.GetSubKeyNames() -notcontains "Policies") {
$subkey.CreateSubKey("Policies")
$subkey = $subkey.OpenSubKey("Policies",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Policies",$True)
}
Write-Verbose "Making registry connection to 'Microsoft' key"
If ($subkey.GetSubKeyNames() -notcontains "Microsoft") {
$subkey.CreateSubKey("Microsoft")
$subkey = $subkey.OpenSubKey("Microsoft",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Microsoft",$True)
}
Write-Verbose "Making registry connection to 'Windows' key"
If ($subkey.GetSubKeyNames() -notcontains "Windows") {
$subkey.CreateSubKey("Windows")
$subkey = $subkey.OpenSubKey("Windows",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Windows",$True)
}
Write-Verbose "Making registry connection to 'Installer' key"
If ($subkey.GetSubKeyNames() -notcontains "Installer") {
$subkey.CreateSubKey("Installer")
$subkey = $subkey.OpenSubKey("Installer",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Installer",$True)
}
Write-Verbose "Checking to see if 'DisableRollback' value name exists"
If ($subkey.GetValueNames() -notcontains "DisableRollback") {
Write-Verbose "Creating DisableRollback value name and setting to 1 (Disable)"
$subkey.SetValue("DisableRollback","1","DWord")
}
Else {
Write-Verbose "Disabling Rollback"
$subkey.SetValue("DisableRollback","1","DWord")
}
If ($PSBoundParameters['Passthru']) {
Write-Verbose "Retrieving value of 'DisableRollback'"
$value = $subkey.GetValue('DisableRollback')
Switch ($value) {
0 {$hash = @{Computer = $computer;Rollback = "Enabled"}}
1 {$hash = @{Computer = $computer;Rollback = "Disabled"}}
Default {$hash = @{Computer = $computer;Rollback = "Unknown"}}
}
}
}
}
Catch {
Write-Warning "$($computer): $($Error[0])"
}
Finally {
If ($PSBoundParameters['Passthru']) {
$object = New-Object PSObject -Property $hash
$object.PSTypeNames.Insert(0,'RollbackStatus')
Write-Output $object
}
}
}
}
}
Function Enable-RollbackPolicy {
<#
.SYNOPSIS
Enables the rollback policy on a local or remote computer
.DESCRIPTION
Enables the rollback policy on a local or remote computer
.PARAMETER Computername
Name of computer or computers to enable the rollback policy
.PARAMETER Passthru
Displays the object after enabling the rollback policy on a computer
.NOTES
Name: Enable-RollbackPolicy
Author: Boe Prox
DateCreated: 06/24/2011
Links:
.EXAMPLE
Enable-RollbackPolicy -Computername DC1 -Passthru
Rollback Computer
-------- --------
Enable DC1
Description
-----------
This enables the rollback policy on DC1 and returns the object showing that the policy has
been enabled.
.EXAMPLE
Enable-RollbackPolicy -Computername DC1,server1,server2 -Passthru
Rollback Computer
-------- --------
Enable DC1
Enable server1
Enable server2
Description
-----------
This enables the rollback policy on DC1,server1 and server2 and returns the object showing that the policy has
been enabled.
#>
[cmdletbinding(
SupportsShouldProcess = 'True'
)]
Param (
[parameter()]
[string[]]$Computername,
[parameter()]
[Switch]$Passthru
)
Process {
ForEach ($computer in $computername) {
Try {
#Make initial registry connection
Write-Verbose "Making registry connection to remote computer"
$registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computer)
If ($PScmdlet.ShouldProcess("$computer","Enable Rollback")) {
#Connect to the subkey where the rollback is located
Write-Verbose "Making registry connection to 'Software' key"
If ($registry.GetSubkeyNames() -notcontains "Software") {
$registry.CreateSubKey("Software")
$subkey = $registry.OpenSubKey("Software",$True)
}
Else {
$subkey = $registry.OpenSubKey("Software",$True)
}
Write-Verbose "Making registry connection to 'Policies' key"
If ($subkey.GetSubKeyNames() -notcontains "Policies") {
$subkey.CreateSubKey("Policies")
$subkey = $subkey.OpenSubKey("Policies",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Policies",$True)
}
Write-Verbose "Making registry connection to 'Microsoft' key"
If ($subkey.GetSubKeyNames() -notcontains "Microsoft") {
$subkey.CreateSubKey("Microsoft")
$subkey = $subkey.OpenSubKey("Microsoft",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Microsoft",$True)
}
Write-Verbose "Making registry connection to 'Windows' key"
If ($subkey.GetSubKeyNames() -notcontains "Windows") {
$subkey.CreateSubKey("Windows")
$subkey = $subkey.OpenSubKey("Windows",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Windows",$True)
}
Write-Verbose "Making registry connection to 'Installer' key"
If ($subkey.GetSubKeyNames() -notcontains "Installer") {
$subkey.CreateSubKey("Installer")
$subkey = $subkey.OpenSubKey("Installer",$True)
}
Else {
$subkey = $subkey.OpenSubKey("Installer",$True)
}
Write-Verbose "Checking to see if 'DisableRollback' value name exists"
If ($subkey.GetValueNames() -notcontains "DisableRollback") {
Write-Verbose "Creating DisableRollback value name and setting to 0 (Enable)"
$subkey.SetValue("DisableRollback","0","DWord")
}
Else {
Write-Verbose "Enabling Rollback"
$subkey.SetValue("DisableRollback","0","DWord")
}
If ($PSBoundParameters['Passthru']) {
Write-Verbose "Retrieving value of 'DisableRollback'"
$value = $subkey.GetValue('DisableRollback')
Switch ($value) {
0 {$hash = @{Computer = $computer;Rollback = "Enabled"}}
1 {$hash = @{Computer = $computer;Rollback = "Disabled"}}
Default {$hash = @{Computer = $computer;Rollback = "Unknown"}}
}
}
}
}
Catch {
Write-Warning "$($computer): $($Error[0])"
}
Finally {
If ($PSBoundParameters['Passthru']) {
$object = New-Object PSObject -Property $hash
$object.PSTypeNames.Insert(0,'RollbackStatus')
Write-Output $object
}
}
}
}
}
Export-ModuleMember -Function Get-RollbackPolicy,Enable-RollbackPolicy,Disable-RollbackPolicy
|
PowerShellCorpus/PoshCode/PowerShellServer Cmdlet .ps1
|
PowerShellServer Cmdlet .ps1
|
\n#Global Hashtable to Control all Powershell Server Runspace\nSet-Variable -name '__PSRUNSPACES__' -scope 'global' -value @{} -force\n\nfunction global:New-PowerShellServerRunspace\n{\n param(\n $Credential,\n $ErrorAction='Stop',\n [switch]$Force,\n $Password,\n $Port=22,\n $Server='127.0.0.1',\n $SSHAccept,\n $Timeout=30,\n $user\n )\n Write-FPEvent "Calling New-PowerShellServerRunspace Function"\n $ErrorActionPreference = $ErrorAction\n trap{\n Write-FPEvent -EventInfo "Function New-PowerShellServerRunspace threw error $($error[0])" -EventType 'Error'\n }\n if(($Credential -eq $null) -and (($User -eq $null) -and ($Password -eq $null))){\n Throw "You Must Provide Authenication `n PSCredential or User and Password"\n }\n\n if($User -and $Password){$script:Credential = Get-FPCredential -Username $User -Password $Password}\n \n if( ($global:__PSRUNSPACES__.Keys -contains "$Server") -and ($global:__PSRunspaces__['10.27.1.4'].RunspaceStateInfo -eq 'OPENED' ) )\n {\n Write-Output $global:__PSRUNSPACES__["$Server"]\n return\n }\n else\n {\n if($Force){\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -Force -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -Force -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n elseif($SSHAccept){\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -SSHAccept $SSHAccept -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -SSHAccept $SSHAccept -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n else{\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n $global:__PSRUNSPACES__["$Server"] = $script:rs\n Write-Output $global:__PSRUNSPACES__["$Server"]\n return\n }\n}\n\nfunction global:Remove-PowerShellServerRunspace\n{\n param(\n $SSHRunspace\n )\n if($SSHRunspace)\n {\n & (Get-Command -commandType 'Cmdlet' -name 'Remove-PowerShellServerRunspace') -SSHRunspace $SSHRunspace\n if( $global:__PSRUNSPACES__.Keys -contains $SSHRunspace.SSHServer )\n {\n $global:__PSRUNSPACES__.Remove($SSHRunspace.SSHServer)\n }\n }\n elseif( $global:__FPRUNSPACES__.Count -gt 0 )\n {\n $global:__FPRUNSPACES__ | Foreach-Object { \n & (Get-Command -commandType 'Cmdlet' -name 'Remove-PowerShellServerRunspace') -SSHRunspace $_\n }\n $global:__PSRUNSPACES__.Clear()\n }\n}
|
PowerShellCorpus/PoshCode/Set-Computername_8.ps1
|
Set-Computername_8.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/PowerBoots Gadgets_1.ps1
|
PowerBoots Gadgets_1.ps1
|
$gadgetWindow = @{
# Transparency, WindowStyle, and background work together
# to get rid of the standard window's chrome and make the window "irregular" shaped
# that is, the window will be the shape of it's content.
AllowsTransparency = $True
WindowStyle = "None"
Background = "Transparent"
# Async means the window will keep running but PowerShell will return to the prompt
Async = $True
# Assuming you put something on your window, this will make the window draggable
# It might get in the way of clicking on controls, so bear that in mind.
On_MouseDown = { $this.DragMove() }
# This makes a timer for you, based on the TITLE and TAG of the window
On_SourceInitialized = {
$this.Tag = DispatcherTimer -Interval $this.Tag[0] -On_Tick $this.Tag[1]
$this.Tag.Start()
}
# Stop that timer or it will just keep right on firing.
On_Closing = {
$this.Tag.Stop()
}
}
## Example uses:
# Create a little clock that's always topmost ...
boots { label -fontsize 24 | tee -var global:clock } @gadgetWindow -Title "Clock" -Topmost -Tag "00:00:00.2", { $global:clock.Content = "$(Get-Date -f 'hh:mm:ss')" }
# World's simplest weather report, updates every 5 minutes
$weatherUrl = "http`://weather.yahooapis.com/forecastrss?p={0}" -f 14586 # Must be a "woeid"
# 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.
boots { Image -Stretch Uniform -Width 250 -height 180| tee -var global:weather } @gadgetWindow -Title "Weather" -Tag "00:05",
{ $h = ([int](Get-Date -f hh)); if($h -gt 8 -and $h -lt 7){$dayOrNight = 'd'}else{$dayOrNight = 'n'}
$code = ([xml](New-Object Net.WebClient).DownloadString($weatherUrl)).rss.channel.item.condition.code
$global:Weather.Source = "http`://l.yimg.com/a/i/us/nws/weather/gr/{0}{1}.png" -f $code, $dayOrNight
}
|
PowerShellCorpus/PoshCode/Get-WebFile _1.6.ps1
|
Get-WebFile _1.6.ps1
|
## Get-WebFile (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## v3.6 - Add -Passthru switch to output TEXT files
## v3.5 - Add -Quiet switch to turn off the progress reports ...
## v3.4 - Add progress report for files which don't report size
## v3.3 - Add progress report for files which report their size
## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter:
## it was messing up binary files, and making mistakes with extended characters in text
## v3.1 - Unwrap the filename when it has quotes around it
## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
## v2 - adds a ton of parsing to make the output pretty
## added measuring the scripts involved in the command, (uses Tokenizer)
##############################################################################################################
function Get-WebFile {
param(
$url = (Read-Host "The URL to download"),
$fileName = $null,
[switch]$Passthru,
[switch]$quiet
)
$req = [System.Net.HttpWebRequest]::Create($url);
@@ #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw
@@ $req.CookieContainer = New-Object System.Net.CookieContainer
$res = $req.GetResponse();
if($fileName -and !(Split-Path $fileName)) {
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName)))
{
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
$fileName = $fileName.trim("\\/""'")
if(!$fileName) {
$fileName = $res.ResponseUri.Segments[-1]
$fileName = $fileName.trim("\\/")
if(!$fileName) {
$fileName = Read-Host "Please provide a file name"
}
$fileName = $fileName.trim("\\/")
if(!([IO.FileInfo]$fileName).Extension) {
$fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
}
}
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
if($Passthru) {
$encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet )
[string]$output = ""
}
if($res.StatusCode -eq 200) {
[int]$goal = $res.ContentLength
$reader = $res.GetResponseStream()
if($fileName) {
$writer = new-object System.IO.FileStream $fileName, "Create"
}
[byte[]]$buffer = new-object byte[] 4096
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length);
if($fileName) {
$writer.Write($buffer, 0, $count);
}
if($Passthru){
$output += $encoding.GetString($buffer,0,$count)
} elseif(!$quiet) {
$total += $count
if($goal -gt 0) {
Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
} else {
Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
}
}
} while ($count -gt 0)
$reader.Close()
if($fileName) {
$writer.Flush()
$writer.Close()
}
if($Passthru){
$output
}
}
$res.Close();
if($fileName) {
ls $fileName
}
}
|
PowerShellCorpus/PoshCode/ScriptTransforms module_1.ps1
|
ScriptTransforms module_1.ps1
|
function New-ParameterTransform {
#.Synopsis
# Generates Parameter Transformation Attributes in simple PowerShell syntax
#.Description
# New-ParameterTransform allows the creation of .Net Attribute classes which can be applied to PowerShell parameters to transform or manipulate data as it's being passed in.
#.Example
# Transform TrimBraces {
# param($string)
# if($string -is [String] -and $string.Length -gt 2 -and $string[0] -eq '[' -and $string[-1] -eq ']') {
# $string.SubString(1, $string.Length-2)
# } else {
# $string
# }
# }
#
# function Where-Type {
# param(
# [Type][TrimBraces()][String]
# [Parameter(Mandatory=$true, Position=0)]
# $Type,
#
# [Parameter(ValueFromPipeline=$true)]
# $InputObject
# )
# process {
# if($InputObject -is $Type) { $InputObject }
# }
# }
#
# Description
# -----------
# This example allows us to pass the "Type" to Where-Type with or without the [Braces] which would normally cause an exception when casting to a type:
#
# Get-ChildItem | Where-Type IO.FileInfo
#
# Get-ChildItem | Where-Type [IO.FileInfo]
#
# Get-ChildItem | Where-Type ([IO.FileInfo])
#
#.Notes
# It is now possible to redefine transforms by name by running the New-ParameterTransform command again, but type aliases that are generated are bound at function definition time, so any functions that are using the transform before it is redefined must also be redefined to take advantage of the new transform definition.
[cmdletbinding()]
param(
# The name of the parameter transform to generate
[Parameter(Mandatory=$true,Position=0)]
[string] $name,
# The script definition of the parameter transform
[Parameter(Mandatory=$true, Position=1)]
[scriptblock] $script
)
end {
$className = [Convert]::ToBase64String( ([Guid]::NewGuid().ToByteArray()) ).Replace('+','ñ').Replace('/','ß').TrimEnd('=')
$Type = Add-Type -Passthru -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Collections.ObjectModel;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ${name}Attribute${className} : ArgumentTransformationAttribute {
private ScriptBlock _scriptblock;
private string _noOutputMessage = "Transform Script had no output.";
public ${name}Attribute${className}() {
this.Script = ScriptBlock.Create( @"
$($script.ToString() -replace '"','""' )
" );
}
public override string ToString() {
return Script.ToString();
}
public override Object Transform( EngineIntrinsics engine, Object inputData) {
try {
Collection<PSObject> output =
engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData );
if(output.Count > 1) {
Object[] transformed = new Object[output.Count];
for(int i =0; i < output.Count;i++) {
transformed[i] = output[i].BaseObject;
}
return transformed;
} else if(output.Count == 1) {
return output[0].BaseObject;
} else {
throw new ArgumentTransformationMetadataException(NoOutputMessage);
}
} catch (ArgumentTransformationMetadataException) {
throw;
} catch (Exception e) {
throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e);
}
}
public ScriptBlock Script {
get { return _scriptblock; }
set { _scriptblock = value; }
}
public string NoOutputMessage {
get { return _noOutputMessage; }
set { _noOutputMessage = value; }
}
}
"@
$xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
if($xlr8r::AddReplace) {
$xlr8r::AddReplace( ${name}, $Type)
} else {
$null = $xlr8r::Remove( ${name} )
$xlr8r::Add( ${name}, $Type)
}
}}
New-Alias -Name Transform -Value New-ParameterTransform;
Export-ModuleMember -Alias Transform -Function *
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUTPVAYxC0ZjgQ4fcYFMPNexV5
# qYegggUrMIIFJzCCBA+gAwIBAgIQHCAgf57pVOnJcjKrMO/dtjANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTExMDQyNTAwMDAwMFoXDTEyMDQyNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANaXR+8W+aH6ofiO
# bZRdIRBuvemJ/8c2fDwbHVLBMieiG9Eqs5+XKZ3M17Sz8GBNzQ4bluk2esIycr9z
# yR/ISBjVxz1RcxH79vuvM6husOAKc2YhnGqA6vmfWokmEfDrOH1qLKA4226tPXBE
# eNTSDrYtXFZ6jYWv9kqGcRMBzV7NPvJwQoMDEl1dbNAXo99RaHGjAfVkCSNYMM11
# jzZ2/DyAqVgKVnNviRQ+Wq8HPxP7Eqg/6b2DVw1Nokg3IDeyFRlo2he09YwVEV+r
# GLvjUBmVRQPauJIr1EUgz85byWtYAUWOXNIFiWrqOKj/Clvi5Y9M05a1TwSi4o0F
# yfa4keECAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTKaDgQ0lToUHAI+jy/CDn0BluXFjAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAeGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAzwUwy00sEOggAavqrNoNeEVr0o623DgG2/2EuTsA6
# 2wI0Arb5D0s/icanshHgWwJZBEMZeHa17Ai/E3foCpj6rA3Y4vIQXHukluiSmjU6
# bWTgF5VbNTpvhlOO6E7Ya/rBr4oj4dqTEErkS7acgBHKrjPOptCiU4BSDqtl0k5z
# OIiawyRSITHYEcCcI0Yl7VIz8EDblOQI3b4JGYcmJ7D+peYrnI2zoQyXDigcIj4l
# VlipnjnvYsF+JbPkQY8XbMO+Yc490Bh8BMXPtuLR1KMuIXPK7DKX7JPmJcY7kKF/
# SPviyk0HE7Rldsses73UF8wT3lgj57FiUqX8FdTa7NllMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQHCAgf57pVOnJcjKrMO/dtjAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUAZ76oQxT
# FCS/GTPt3vFPxINoPS0wDQYJKoZIhvcNAQEBBQAEggEA0e7s3o95oxMWZXzdu0XE
# c3y1fnKXmgN1gfAFh3lvWQWiiKPBAd0/PBfyAZmendJ7wsLTAafxB21ks74q3WqM
# FJ3/BW8FAZtm8QBuseNkbP3R5pEEhnrEaRo4ZKGez+TfEZe7Swyzo1Vqv8by8a1I
# PCqbZzH6CzU1IR9aoApCvM/OY2Rxp9f4ozdCRqk91Kk6/ryjor/ZJOroAh4ZmEpC
# Z0fRsnKWJ9x3YI8M3dZG53/cBEfaS06GjQvFQasx3BJK1VMQ6suaYYWU4Q/49VWc
# pZ7FhQjw79gZlweVJWENw2dWk2u0OHYTIN+IPVtnLmxgtLRfhenS8TsdjaI3ebUA
# 7w==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/tst.ps1
|
tst.ps1
|
# Follwoing code to install and deploye site
# Parameter Section Start
$languagePack="{1033}" # this line is used to notify the language pack used by the sharepoint server
$path= "D:\\tmp\\ps\\template\\kolam.wsp" # path of the wsp to be read
$feature = "kolamWebTemplate" #Feature Name of the wsp to be activated which should be site as scope kolamWebTemplate
$solution = "kolam.wsp" # Solution name for the wsp which is going to be installed and deployed
$targetUrl = "http://spf/kolam36" # Target location of the site with its url going to be created
$targetWebAppUrl = "http://spf" # web application URl where the site will be deployed
$targetSiteColUrl = "http://spf" # site collection URl where the site will be deployed
$SiteTitle = " Проверка работы сайта " # Title of the site which will be fetched from web template
$SiteName ="kolam36" # Name of the site which will be created
$SiteDesc = " Test Site kolam" # Description of the site which will be created
# Parameter Section End
# Function Section Start # Below code is used as a timer job for the installation and retracting process
function WaitForJobToFinish([string]$SolutionFileName)
{
$JobName = "*solution-deployment*$SolutionFileName*"
$job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
if ($job -eq $null)
{
Write-Host 'Timer job not found'
}
else
{
$JobFullName = $job.Name
Write-Host -NoNewLine "Waiting to finish job $JobFullName"
while ((Get-SPTimerJob $JobFullName) -ne $null)
{
Write-Host -NoNewLine .
Start-Sleep -Seconds 2
}
Write-Host "Finished waiting for job.."
}
}
# Function Section End
# Main Section Start
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
Write-Host "Loading SharePoint Powershell Snap-in"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
$user=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host "current user = $user"
Write-Host "Deploying Solution Started.."
$WSP = Get-SPSolution | Where {
($solution -eq $_.Name)
}
if($WSP -eq $null) {
}
else
{
Write-Host "De-Activating feature -"$feature
Disable-SPFeature -identity $feature -Url $targetSiteColURL -Confirm:$false
Write-Host "Feature de-activated - "$feature
Write-Host "Found " $WSP " - Uninstalling."
Uninstall-SPSolution -Identity $solution -Confirm:$false
WaitForJobToFinish($solution)
Write-Host $WSP "Uninstalled."
Write-Host "removing Solution -" $solution
Remove-SPSolution -Identity $solution -Confirm:$false
WaitForJobToFinish($solution)
Write-Host "removed Solution -" $solution
Write-Host "Deleting target site -" $targetUrl
Remove-SPWEB -identity $targetUrl -Confirm:$false
Write-Host "Deleted target site - " $targetUrl
}
Write-Host "Adding Solution"
Add-SPSolution -LiteralPath $path -Confirm:$false
Write-Host "Added Solution"
Write-Host "Installing Solution"
Install-SPSolution -Identity $solution -GACDeployment -Confirm:$false
WaitForJobToFinish($solution)
Write-Host "Installed Solution"
Write-Host "Activating feature - "$feature
Enable-SPFeature -identity $feature -Url $targetWebAppURL -Confirm:$false
Write-Host "Feature activated - " $feature
#Below code finds the TemplateID for the site
$site= new-Object Microsoft.SharePoint.SPSite($targetWebAppUrl)
#$loc= [System.Int32]::Parse(1033)
#$templates= $site.GetWebTemplates($loc)
$templates= $site.GetWebTemplates($loc)
$templateId=""
foreach ($child in $templates)
{
if($child.Title -eq $SiteTitle)
{
$templateId= $child.Name
}
}
$site.Dispose()
Write-Host "Creating New site with templateID -" $templateId
$web = New-SPWeb -Url $targetUrl -Name $SiteName -Description $SiteDesc -AddToTopNav -Confirm:$false
Write-Host "New Site Created"
Write-Host "Applying template please wait....."
$web.ApplyWebTemplate($templateId)
$web.Dispose()
Write-Host "Site template applied successfully! Template = $templateId "
Write-Host -Fore Green "Solution deployment completed"
Write-Host "To visit the created site Browse - "-Fore Blue $targetUrl
get-pssession | remove-pssession
# Main Section End
|
PowerShellCorpus/PoshCode/FileCop.ps1
|
FileCop.ps1
|
$nul = "<NULL>"
$sec = "MD5", "SHA1", "SHA256", "SHA384", "SHA512", "RIPEMD160"
##################################################################################################
function Add-RootsTree {
[IO.Directory]::GetLogicalDrives() | % {
$nod = New-Object Windows.Forms.TreeNode
$nod = $tvRoots.Nodes.Add($_)
$nod.Nodes.Add($nul)
}
}
function Show-ExceptMessage([string]$msg) {
[Windows.Forms.MessageBox]::Show($msg, $frmMain.Text,
[Windows.Forms.MessageBoxButtons]::OK,
[Windows.Forms.MessageBoxIcon]::Exclamation
)
}
function Add-Folders {
$_.Node.Nodes.Clear()
try {
foreach ($i in [IO.Directory]::GetDirectories($_.Node.FullPath)) {
$node = $_.Node.Nodes.Add([IO.Path]::GetFileName($i))
$node.Nodes.Add($nul)
}
}
catch { Show-ExceptMessage $_.Exception.Message }
}
function Add-Files {
try {
foreach ($i in [IO.Directory]::GetFiles($_.Node.FullPath)) {
$node = $_.Node.Nodes.Add([IO.Path]::GetFileName($i))
$node.Tag = "File"
$node.ImageIndex = 1
}
}
catch {}
}
function Format-String([string]$par) {
if ($par -eq "") { 'n/a' }
else { $par }
}
function Get-Checksum([string]$alg, [string]$obj) {
([Security.Cryptography.HashAlgorithm]::Create($alg).ComputeHash(
[IO.File]::ReadAllBytes($obj)
) | % {"{0:x2}" -f $_}) -as [string] -replace " ", ""
}
function Get-Image([string]$img) {
[Drawing.Image]::FromStream((New-Object IO.MemoryStream(($$ = `
[Convert]::FromBase64String($img)), 0, $$.Length)))
}
function Clear-Output {
$lblName.Text = [String]::Empty
$lblAttr.Text = [String]::Empty
$lblSign.Text = [String]::Empty
$lblBorn.Text = [String]::Empty
$lblAccs.Text = [String]::Empty
$lblWrit.Text = [String]::Empty
$lblSize.Text = [String]::Empty
$lblType.Text = [String]::Empty
$lblPubl.Text = [String]::Empty
$lblDesc.Text = [String]::Empty
$lblProd.Text = [String]::Empty
$lblVers.Text = [String]::Empty
$lblOriN.Text = [String]::Empty
$lblIntN.Text = [String]::Empty
$lblCopy.Text = [String]::Empty
$lblComm.Text = [String]::Empty
}
##################################################################################################
$tvRoots_AfterSelect= {
$lstStrm.Items.Clear()
$lstHash.Items.Clear()
if ($_.Node.Tag -eq 'File') {
$fi = [IO.FileInfo]($_.Node.FullPath)
if (Test-Path $fi.FullName) {
$lblName.Text = $fi.FullName
$lblAttr.Text = $fi.Attributes
$lblSign.Text = (Get-AuthenticodeSignature $fi.FullName).Status
$lblBorn.Text = $fi.CreationTime
$lblAccs.Text = $fi.LastAccessTime
$lblWrit.Text = $fi.LastWriteTime
$lblSize.Text = $fi.Length
$lblType.Text = (New-Object -com Scripting.FileSystemObject).GetFile($fi.FullName).Type
$vi = [Diagnostics.FileVersionInfo]::GetVersionInfo($fi.FullName)
$lblPubl.Text = (Format-String $vi.CompanyName)
$lblDesc.Text = (Format-String $vi.FileDescription)
$lblProd.Text = (Format-String $vi.ProductName)
$lblVers.Text = (Format-String $vi.ProductVersion)
$lblOriN.Text = (Format-String $vi.OriginalFileName)
$lblIntN.Text = (Format-String $vi.InternalName)
$lblCopy.Text = (Format-String $vi.LegalCopyright)
$lblComm.Text = (Format-String $vi.Comments)
try {
[IO.Streams]::Dump($fi.FullName).Split(";") | % {
$itm = $lstStrm.Items.Add($_.Split(" ")[0])
$itm.SubItems.Add($_.Split(" ")[1])
$itm.SubItems.Add($_.Split(" ")[2])
}
}
catch {}
$sec | % {
$itm = $lstHash.Items.Add($_)
if ($fi.Length -ne 0) {
$itm.SubItems.Add((Get-Checksum $_ $fi.FullName))
}
else { $itm.SubItems.Add('n/a') }
}
}
else { Clear-Output; $lblName.Text = 'File does not exist or has been moved' }
}
else { Clear-Output }
}
$tvRoots_BeforeExpand= {
Add-Folders
Add-Files
}
$mnuUpdt_Click= {
$tvRoots.Nodes.Clear()
$lstStrm.Items.Clear()
$lstHash.Items.Clear()
Clear-Output
$sbPanel.Text = "Refreshed at " + (Get-Date -f 'HH:mm:ss')
Add-RootsTree
}
$mnuSBar_Click= {
$toggle =! $mnuSBar.Checked
$mnuSbar.Checked = $toggle
$sbPanel.Visible = $toggle
}
$frmMain_load= {
Add-RootsTree
$sbPanel.Text = "Ready"
}
##################################################################################################
$code = @'
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
namespace IO {
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Win32StreamID {
public StreamType dwStreamId;
public int dwStreamAttributes;
public long Size;
public int dwStreamNameSize;
}
public enum StreamType {
Unknown = 0,
Data,
ExternalData,
SecurityData,
AlternateData,
Link,
PropertyData,
ObjectId,
ReparseData,
SparseDock,
TransactionData
}
struct StreamInfo {
public StreamInfo(string name, StreamType type, long size) {
Name = name;
Type = type;
Size = size;
}
public readonly string Name;
public readonly StreamType Type;
public readonly long Size;
}
internal static class WinAPI {
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool BackupRead(SafeFileHandle hFile, IntPtr lpBuffer,
uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead,
[MarshalAs(UnmanagedType.Bool)] bool bAbort,
[MarshalAs(UnmanagedType.Bool)] bool bProcessSecurity,
ref IntPtr lpContext);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool BackupSeek(SafeFileHandle hFile, uint dwLowBytesToSeek,
uint dwHighBytesToSeek, out uint lpdwLowByteSeeked,
out uint lpdwHighByteSeeked, ref IntPtr lpContext);
public static IEnumerable<StreamInfo> GetStreams(FileInfo file) {
const int buff = 4096;
using (FileStream fs = file.OpenRead()) {
IntPtr context = IntPtr.Zero;
IntPtr buffer = Marshal.AllocHGlobal(buff);
try {
while (true) {
uint numRead;
if (!BackupRead(fs.SafeFileHandle, buffer,
(uint)Marshal.SizeOf(typeof(Win32StreamID)), out numRead,
false, true, ref context)) throw new Win32Exception();
if (numRead > 0) {
Win32StreamID stream = (Win32StreamID)Marshal.PtrToStructure(buffer,
typeof(Win32StreamID));
string name = null;
if (stream.dwStreamNameSize > 0) {
if (!BackupRead(fs.SafeFileHandle, buffer, (uint)Math.Min(buff,
stream.dwStreamNameSize), out numRead,
false, true, ref context)) throw new Win32Exception();
name = Marshal.PtrToStringUni(buffer, (int)numRead / 2);
}
yield return new StreamInfo(name, stream.dwStreamId, stream.Size);
if (stream.Size > 0) {
uint lo, hi;
BackupSeek(fs.SafeFileHandle, uint.MaxValue,
int.MaxValue, out lo, out hi, ref context);
}
}
else break;
}
}
finally {
Marshal.FreeHGlobal(buffer);
uint numRead;
if (!BackupRead(fs.SafeFileHandle, IntPtr.Zero, 0,
out numRead, true, false, ref context)) throw new Win32Exception();
}
}
}
}
public static class Streams {
public static string Dump(string file) {
List<StreamInfo> streams =
new List<StreamInfo>(WinAPI.GetStreams(new FileInfo(file)));
string res = "";
foreach (StreamInfo stream in streams) {
res += (stream.Name != null ? stream.Name : "<Unnamed>") +
" " + stream.Type + " " + stream.Size + ";";
}
return res;
}
}
}
'@
##################################################################################################
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
Add-Type $code
$ico = [Drawing.Icon]::ExtractAssociatedIcon(($PSHome + '\\powershell.exe'))
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MainMenu
$mnuFile = New-Object Windows.Forms.MenuItem
$mnuUpdt = New-Object Windows.Forms.MenuItem
$mnuExit = New-Object Windows.Forms.MenuItem
$mnuView = New-Object Windows.Forms.MenuItem
$mnuTCol = New-Object Windows.Forms.MenuItem
$mnuSBar = New-Object Windows.Forms.MenuItem
$mnuHelp = New-Object Windows.Forms.MenuItem
$mnuInfo = New-Object Windows.Forms.MenuItem
$scSplt1 = New-Object Windows.Forms.SplitContainer
$scSplt2 = New-Object Windows.Forms.SplitContainer
$tvRoots = New-Object Windows.Forms.TreeView
$lblL_01 = New-Object Windows.Forms.Label
$lblL_02 = New-Object Windows.Forms.Label
$lblL_03 = New-Object Windows.Forms.Label
$lblL_04 = New-Object Windows.Forms.Label
$lblL_05 = New-Object Windows.Forms.Label
$lblL_06 = New-Object Windows.Forms.Label
$lblL_07 = New-Object Windows.Forms.Label
$lblL_08 = New-Object Windows.Forms.Label
$lblL_09 = New-Object Windows.Forms.Label
$lblL_10 = New-Object Windows.Forms.Label
$lblL_11 = New-Object Windows.Forms.Label
$lblL_12 = New-Object Windows.Forms.Label
$lblL_13 = New-Object Windows.Forms.Label
$lblL_14 = New-Object Windows.Forms.Label
$lblL_15 = New-Object Windows.Forms.Label
$lblL_16 = New-Object Windows.Forms.Label
$lblName = New-Object Windows.Forms.Label
$lblAttr = New-Object Windows.Forms.Label
$lblSign = New-Object Windows.Forms.Label
$lblBorn = New-Object Windows.Forms.Label
$lblAccs = New-Object Windows.Forms.Label
$lblWrit = New-Object Windows.Forms.Label
$lblSize = New-Object Windows.Forms.Label
$lblType = New-Object Windows.Forms.Label
$lblPubl = New-Object Windows.Forms.Label
$lblDesc = New-Object Windows.Forms.Label
$lblProd = New-Object Windows.Forms.Label
$lblVers = New-Object Windows.Forms.Label
$lblOriN = New-Object Windows.Forms.Label
$lblIntN = New-Object Windows.Forms.Label
$lblCopy = New-Object Windows.Forms.Label
$lblComm = New-Object Windows.Forms.Label
$lstStrm = New-Object Windows.Forms.ListView
$chSName = New-Object Windows.Forms.ColumnHeader
$chSType = New-Object Windows.Forms.ColumnHeader
$chSSize = New-Object Windows.Forms.ColumnHeader
$lstHash = New-Object Windows.Forms.ListView
$chHType = New-Object Windows.Forms.ColumnHeader
$chHData = New-Object Windows.Forms.ColumnHeader
$imgList = New-Object Windows.Forms.ImageList
$sbPanel = New-Object Windows.Forms.StatusBar
#
#mnuMain
#
$mnuMain.MenuItems.AddRange(@($mnuFile, $mnuView, $mnuHelp))
#
#mnuFile
#
$mnuFile.MenuItems.AddRange(@($mnuUpdt, $mnuExit))
$mnuFile.Text = "&File"
#
#mnuUpdt
#
$mnuUpdt.Shortcut = "F5"
$mnuUpdt.Text = "&Refresh"
$mnuUpdt.Add_Click($mnuUpdt_Click)
#
#mnuExit
#
$mnuExit.Shortcut = "CtrlX"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click({$frmMain.Close()})
#
#mnuView
#
$mnuView.MenuItems.AddRange(@($mnuTCol, $mnuSBar))
$mnuView.Text = "&View"
#
#mnuTCol
#
$mnuTCol.Shortcut = "CtrlC"
$mnuTCol.Text = "&Collapse Tree"
$mnuTCol.Add_Click({$tvRoots.CollapseAll()})
#
#mnuSBar
#
$mnuSBar.Checked = $true
$mnuSBar.Text = "Toggle Status &Bar"
$mnuSBar.Add_Click($mnuSBar_Click)
#
#mnuHelp
#
$mnuHelp.MenuItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#
#mnuInfo
#
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click({frmInfo_Show})
#
#scSplt1
#
$scSplt1.Dock = "Fill"
$scSplt1.Orientation = "Horizontal"
$scSplt1.Panel1.Controls.Add($scSplt2)
$scSplt1.Panel2.Controls.Add($lstHash)
$scSplt1.Panel1MinSize = 450
$scSplt1.SplitterDistance = 90
$scSplt1.SplitterWidth = 1
#
#scSplt2
#
$scSplt2.Dock = "Fill"
$scSplt2.Panel1.Controls.Add($tvRoots)
$scSplt2.Panel2.Controls.AddRange(@($lblL_01, $lblL_02, $lblL_03, $lblL_04, $lblL_05, `
$lblL_06, $lblL_07, $lblL_08, $lblL_09, $lblL_10, $lblL_11, $lblL_12, $lblL_13, `
$lblL_14, $lblL_15, $lblL_16, $lblName, $lblAttr, $lblSign, $lblBorn, $lblAccs, `
$lblWrit, $lblSize, $lblType, $lblPubl, $lblDesc, $lblProd, $lblVers, $lblOriN, `
$lblIntN, $lblCopy, $lblComm, $lstStrm))
$scSplt2.Panel1MinSize = 43
$scSplt2.SplitterDistance = 43
$scSplt2.SplitterWidth = 1
#
#tvRoots
#
$tvRoots.Dock = "Fill"
$tvRoots.ImageList = $imgList
$tvRoots.Select()
$tvRoots.SelectedImageIndex = 2
$tvRoots.Add_AfterSelect($tvRoots_AfterSelect)
$tvRoots.Add_BeforeExpand($tvRoots_BeforeExpand)
#
#lblL_01
#
$lblL_01.Location = New-Object Drawing.Point(8, 13)
$lblL_01.Width = 80
$lblL_01.Text = "Full Name:"
#
#lblL_02
#
$lblL_02.Location = New-Object Drawing.Point(8, 35)
$lblL_02.Width = 80
$lblL_02.Text = "Attributes:"
#
#lblL_03
#
$lblL_03.Location = New-Object Drawing.Point(8, 57)
$lblL_03.Width = 80
$lblL_03.Text = "Signed:"
#
#lblL_04
#
$lblL_04.Location = New-Object Drawing.Point(8, 79)
$lblL_04.Width = 80
$lblL_04.Text = "Creation:"
#
#lblL_05
#
$lblL_05.Location = New-Object Drawing.Point(8, 101)
$lblL_05.Width = 80
$lblL_05.Text = "Last Access:"
#
#lblL_06
#
$lblL_06.Location = New-Object Drawing.Point(8, 123)
$lblL_06.Width = 80
$lblL_06.Text = "Last Write:"
#
#lblL_07
#
$lblL_07.Location = New-Object Drawing.Point(8, 145)
$lblL_07.Width = 80
$lblL_07.Text = "Size:"
#
#lblL_08
#
$lblL_08.Location = New-Object Drawing.Point(8, 167)
$lblL_08.Width = 80
$lblL_08.Text = "Shell Type:"
#
#lblL_09
#
$lblL_09.Location = New-Object Drawing.Point(8, 189)
$lblL_09.Width = 80
$lblL_09.Text = "Publisher:"
#
#lblL_10
#
$lblL_10.Location = New-Object Drawing.Point(8, 211)
$lblL_10.Width = 80
$lblL_10.Text = "Description:"
#
#lblL_11
#
$lblL_11.Location = New-Object Drawing.Point(8, 233)
$lblL_11.Width = 80
$lblL_11.Text = "Product:"
#
#lblL_12
#
$lblL_12.Location = New-Object Drawing.Point(8, 255)
$lblL_12.Width = 80
$lblL_12.Text = "Version:"
#
#lblL_13
#
$lblL_13.Location = New-Object Drawing.Point(8, 277)
$lblL_13.Width = 80
$lblL_13.Text = "Original Name:"
#
#lblL_14
#
$lblL_14.Location = New-Object Drawing.Point(8, 299)
$lblL_14.Width = 80
$lblL_14.Text = "Internal Name:"
#
#lblL_15
#
$lblL_15.Location = New-Object Drawing.Point(8, 321)
$lblL_15.Width = 80
$lblL_15.Text = "Copyright:"
#
#lblL_16
#
$lblL_16.Location = New-Object Drawing.Point(8, 343)
$lblL_16.Width = 80
$lblL_16.Text = "Comment:"
#
#lblName
#
$lblName.BorderStyle = "Fixed3D"
$lblName.Location = New-Object Drawing.Point(91, 11)
$lblName.Size = New-Object Drawing.Size(461, 20)
$lblName.TextAlign = "MiddleLeft"
#
#lblAttr
#
$lblAttr.BorderStyle = "Fixed3D"
$lblAttr.Location = New-Object Drawing.Point(91, 33)
$lblAttr.Size = New-Object Drawing.Size(461, 20)
$lblAttr.TextAlign = "MiddleLeft"
#
#lblSign
#
$lblSign.BorderStyle = "Fixed3D"
$lblSign.Location = New-Object Drawing.Point(91, 55)
$lblSign.Size = New-Object Drawing.Size(461, 20)
$lblSign.TextAlign = "MiddleLeft"
#
#lblBorn
#
$lblBorn.BorderStyle = "Fixed3D"
$lblBorn.Location = New-Object Drawing.Point(91, 77)
$lblBorn.Size = New-Object Drawing.Size(461, 20)
$lblBorn.TextAlign = "MiddleLeft"
#
#lblAccs
#
$lblAccs.BorderStyle = "Fixed3D"
$lblAccs.Location = New-Object Drawing.Point(91, 99)
$lblAccs.Size = New-Object Drawing.Size(461, 20)
$lblAccs.TextAlign = "MiddleLeft"
#
#lblWrit
#
$lblWrit.BorderStyle = "Fixed3D"
$lblWrit.Location = New-Object Drawing.Point(91, 121)
$lblWrit.Size = New-Object Drawing.Size(461, 20)
$lblWrit.TextAlign = "MiddleLeft"
#
#lblSize
#
$lblSize.BorderStyle = "Fixed3D"
$lblSize.Location = New-Object Drawing.Point(91, 143)
$lblSize.Size = New-Object Drawing.Size(461, 20)
$lblSize.TextAlign = "MiddleLeft"
#
#lblType
#
$lblType.BorderStyle = "Fixed3D"
$lblType.Location = New-Object Drawing.Point(91, 165)
$lblType.Size = New-Object Drawing.Size(461, 20)
$lblType.TextAlign = "MiddleLeft"
#
#lblPubl
#
$lblPubl.BorderStyle = "Fixed3D"
$lblPubl.Location = New-Object Drawing.Point(91, 187)
$lblPubl.Size = New-Object Drawing.Size(461, 20)
$lblPubl.TextAlign = "MiddleLeft"
#
#lblDesc
#
$lblDesc.BorderStyle = "Fixed3D"
$lblDesc.Location = New-Object Drawing.Point(91, 209)
$lblDesc.Size = New-Object Drawing.Size(461, 20)
$lblDesc.TextAlign = "MiddleLeft"
#
#lblProd
#
$lblProd.BorderStyle = "Fixed3D"
$lblProd.Location = New-Object Drawing.Point(91, 231)
$lblProd.Size = New-Object Drawing.Size(461, 20)
$lblProd.TextAlign = "MiddleLeft"
#
#lblVers
#
$lblVers.BorderStyle = "Fixed3D"
$lblVers.Location = New-Object Drawing.Point(91, 253)
$lblVers.Size = New-Object Drawing.Size(461, 20)
$lblVers.TextAlign = "MiddleLeft"
#
#lblOriN
#
$lblOriN.BorderStyle = "Fixed3D"
$lblOriN.Location = New-Object Drawing.Point(91, 275)
$lblOriN.Size = New-Object Drawing.Size(461, 20)
$lblOriN.TextAlign = "MiddleLeft"
#
#lblIntN
#
$lblIntN.BorderStyle = "Fixed3D"
$lblIntN.Location = New-Object Drawing.Point(91, 297)
$lblIntN.Size = New-Object Drawing.Size(461, 20)
$lblIntN.TextAlign = "MiddleLeft"
#
#lblCopy
#
$lblCopy.BorderStyle = "Fixed3D"
$lblCopy.Location = New-Object Drawing.Point(91, 319)
$lblCopy.Size = New-Object Drawing.Size(461, 20)
$lblCopy.TextAlign = "MiddleLeft"
#
#lblComm
#
#$lblComm.Anchor = "Left, Top, Right"
$lblComm.BorderStyle = "Fixed3D"
$lblComm.Location = New-Object Drawing.Point(91, 341)
$lblComm.Size = New-Object Drawing.Size(461, 20)
$lblComm.TextAlign = "MiddleLeft"
#
#lstStrm
#
$lstStrm.Columns.AddRange(@($chSName, $chSType, $chSSize))
$lstStrm.FullRowSelect = $true
$lstStrm.Location = New-Object Drawing.Point(8, 367)
$lstStrm.Size = New-Object Drawing.Size(545, 80)
$lstStrm.View = "Details"
#
#chSName
#
$chSName.Text = "Stream Name"
$chSName.Width = 150
#
#chSType
#
$chSType.Text = "Stream Type"
$chSType.TextAlign = "Right"
$chSType.Width = 150
#
#chSSize
#
$chSSize.Text = "Stream Size"
$chSSize.Width = 75
#
#lstHash
#
$lstHash.Columns.AddRange(@($chHType, $chHData))
$lstHash.Dock = "Fill"
$lstHash.FullRowSelect = $true
$lstHash.ShowItemToolTips = $true
$lstHash.View = "Details"
#
#chHType
#
$chHType.Text = "Hash"
$chHType.TextAlign = "Right"
$chHType.Width = 90
#
#chHData
#
$chHData.Text = "Data"
$chHData.Width = 679
#
#imgList
#
$i_1, $i_2, $i_3 | % { $imgList.Images.Add((Get-Image $_)) }
#
#sbPanel
#
$sbPanel.SizingGrip = $false
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(790, 550)
$frmMain.Controls.AddRange(@($scSplt1, $sbPanel))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.Icon = $ico
$frmMain.MaximizeBox = $false
$frmMain.Menu = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "FileCop [" + [Security.Principal.WindowsIdentity]::GetCurrent().Name + "]"
$frmMain.Add_Load($frmMain_Load)
[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 = "FileCop v2.01"
#
#lblCopy
#
$lblCopy.Location = New-Object Drawing.Point(67, 37)
$lblCopy.Size = New-Object Drawing.Size(360, 23)
$lblCopy.Text = "(C) 2011-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()
}
##################################################################################################
$i_1 = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nI" + `
"CIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMj" + `
"IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAARABYDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQE" + `
"AAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEI" + `
"I0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4e" + `
"XqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6e" + `
"rx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ" + `
"3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZH" + `
"SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6w" + `
"sPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2vUL4x3f2bzpYdqK4MK" + `
"B3csWGACD0CknAJ+mDmk+tX9rDIRZyXYQEqWhmjdhjoQIiuffIH07V/EUs+n6xbaiLW4ng2BCIE3sCBIOR/wA" + `
"DH5H8cu48WTSQSRrpGrZZSB/ox9PrXkVq2JhVlyxbXTTT8jqjCDS1X3nZabqMOp2nnw7lwxSSNxho3HVWHYii" + `
"sXwUk/2DUbma3ltxd6jNPGky7W2NjGR26UV6lNuUE5KzOaSSbsdLRRRViCiiigD/2Q=="
$i_2 = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nI" + `
"CIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMj" + `
"IyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAASABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQE" + `
"AAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEI" + `
"I0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4e" + `
"XqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6e" + `
"rx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ" + `
"3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZH" + `
"SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6w" + `
"sPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2gSWscJmuppVzLIMiV8" + `
"cM3YHgACq8WoxpfbIpfMtZHCgksxVuBjkf3uOvcdOaydZgvr6zRLBAxMlyjls4H7zHb8aybXTdSPiTTpLmOSO" + `
"J3WNsoeTH86ln/jYhOTgZ7Dito04OHM5a9jmnWqKooRjdaanayaNpcsjSSabZu7kszNApJJ6knFOg0nTraZZo" + `
"NPtYpV+68cKqw7dQKKKxOk//2Q=="
$i_3 = "/9j/4AAQSkZJRgABAQEAYABgAAD/4QAWRXhpZgAASUkqAAgAAAAAAAAAAAD/2wBDAAgGBgcGBQgHBwcJCQgKD" + `
"BQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDR" + `
"gyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAANAAg" + `
"DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9" + `
"AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdIS" + `
"UpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxM" + `
"XGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgc" + `
"ICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYk" + `
"NOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUl" + `
"ZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADA" + `
"MBAAIRAxEAPwDtvDfjq4XxvqXhzUBLPG9/OlpKql2jw7fI2OdmBwf4e/y/dK63RPC1jol/qOoRjzb6/nklkmY" + `
"cqrOWCL6AcZ9SMnsAVlRjOMbTZ6GZVsNVrKWHjZWV/N9Xbp/TP//Z"
##################################################################################################
frmMain_Show
|
PowerShellCorpus/PoshCode/Select-ViaGUI_1.ps1
|
Select-ViaGUI_1.ps1
|
function Select-ViaUI {
#.Synopsis
# Select objects through a visual interface
#.Description
# Uses a graphical interface to select (and pass-through) pipeline objects
# Idea from Lee Holmes (http://www.leeholmes.com/blog)
#.Example
# Get-ChildItem | Select-ViaUI -show | Remove-Item -WhatIf
[OutputType([Windows.Controls.Grid])]
[CmdletBinding(DefaultParameterSetName="DefaultView")]
param(
# Specifies the object properties that appear in the display and the order in which they appear. Type one or more property names (separated by commas), or use a hash table to display a calculated property. Wildcards are permitted.
#
# If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command.
#
# The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hashtable. Valid keys are:
# -- Name (or Label) <string>
# -- Expression <string> or <script block> (MANDATORY)
[Parameter(Position=0, ParameterSetName="Property")]
[Object[]]$Property,
# Specifies the name of an alternate table format or "view." You cannot use the Property and View parameters in the same command.
[Parameter(ParameterSetName="View")]
[String]$View,
# Specifies the objects to be displayed for selection. Enter a variable that contains the objects, or type a command or expression that gets the objects.
[Parameter(ValueFromPipeline=$true)]
[PSObject[]]$InputObject,
# The name of the control
[string]$Name,
# If the control is a child element of a Grid control (see New-Grid),
# then the Row parameter will be used to determine where to place the
# top of the control. Using the -Row parameter changes the
# dependency property [Windows.Controls.Grid]::RowProperty
[Int]$Row,
# If the control is a child element of a Grid control (see New-Grid)
# then the Column parameter will be used to determine where to place
# the left of the control. Using the -Column parameter changes the
# dependency property [Windows.Controls.Grid]::ColumnProperty
[Int]$Column,
# If the control is a child element of a Grid control (see New-Grid)
# then the RowSpan parameter will be used to determine how many rows
# in the grid the control will occupy. Using the -RowSpan parameter
# changes the dependency property [Windows.Controls.Grid]::RowSpanProperty
[Int]$RowSpan,
# If the control is a child element of a Grid control (see New-Grid)
# then the RowSpan parameter will be used to determine how many columns
# in the grid the control will occupy. Using the -ColumnSpan parameter
# changes the dependency property [Windows.Controls.Grid]::ColumnSpanProperty
[Int]$ColumnSpan,
# The -Width parameter will be used to set the width of the control
[Int]$Width,
# The -Height parameter will be used to set the height of the control
[Int]$Height,
# If the control is a child element of a Canvas control (see New-Canvas),
# then the Top parameter controls the top location within that canvas
# Using the -Top parameter changes the dependency property
# [Windows.Controls.Canvas]::TopProperty
[Double]$Top,
# If the control is a child element of a Canvas control (see New-Canvas),
# then the Left parameter controls the left location within that canvas
# Using the -Left parameter changes the dependency property
# [Windows.Controls.Canvas]::LeftProperty
[Double]$Left,
# If the control is a child element of a Dock control (see New-Dock),
# then the Dock parameter controls the dock style within that panel
# Using the -Dock parameter changes the dependency property
# [Windows.Controls.DockPanel]::DockProperty
[Windows.Controls.Dock]$Dock,
# If Show is set, then the UI will be displayed as a modal dialog within the current
# thread. If the -Show and -AsJob parameters are omitted, then the control should be
# output from the function
[Switch]$Show,
# If AsJob is set, then the UI will displayed within a WPF job.
[Switch]$AsJob
)
begin {
$Items = New-Object System.Collections.ArrayList
}
process {
$Items.AddRange($InputObject)
}
end {
# We're going to need the parameters later
$uiParameters = @{} + $psBoundParameters
$null = $uiParameters.Remove("Property")
$null = $uiParameters.Remove("View")
$null = $uiParameters.Remove("InputObject")
$formatParameters = @{}
if($psBoundParameters.ContainsKey("Property")){
$formatParameters.Property = $PsBoundParameters.Property + @{Name="OriginalItem";Expression={$_}}
}
if($psBoundParameters.ContainsKey("View")){
$formatParameters.View = $psBoundParameters.View
}
# we need to store the original items ... so we can output them later
# But we're going to convert them to strings to display them
$global:SelectViaUIStringItems = New-Object System.Collections.ArrayList
if($psBoundParameters.ContainsKey("Property")) {
$SelectViaUIStringItems = $items | Select-Object @formatParameters
$Strings = $Items | Format-Table @formatParameters -AutoSize | Tee-Object -variable formattedData | Out-String -Width 10000 -Stream
$tableColumnInfo = $formattedData[0].shapeInfo.tableColumnInfoList |
Select-Object width, alignment, @{n="label";e={if($_.label){$_.label}else{$_.propertyName}}} |
Where-Object { $_.label -ne "OriginalItem" }
} else {
Write-Warning $psBoundParameters.Keys
## Convert input to string representations and store ...
$Strings = $Items | Format-Table | Tee-Object -variable formattedData | Out-String -Width 10000 -Stream
$tableColumnInfo = $formattedData[0].shapeInfo.tableColumnInfoList | Select-Object width, alignment, @{n="label";e={if($_.label){$_.label}else{$_.propertyName}}}
for($c=0;$c -lt $Strings.Length;$c++) {
## We're looking for a line that has at least one "-" and nothing but " " and "-"
if( $Strings[$c] -match '^ *-+[ -]*$' ) {
$separators = [regex]::Matches($Strings[$c],"(?<=^|\\s+)-+") + (New-Object PSObject -Property @{Index =$Delimiters.Length})
break
}
}
# $Headers = foreach($column in $separators) {
# $Strings[($c-1)].substring($column.Index,$column.length).TrimEnd()
# }
$Strings = $Strings[($c+1)..($Strings.Count -2)] | where-object { $_ }
# $formattedData[@(2..($formattedData.Count-3))] | %{ $field = $_.formatEntryInfo.formatPropertyFieldList[0]; $_.formatEntryInfo.formatPropertyFieldList.clear(); $_.formatEntryInfo.formatPropertyFieldList.Add($field) }
for($i=0; $i -lt $Items.Count;$i++) {
$start = 0
$line = $Strings[$i]
$outputRow = @{}
for($c=0;$c -lt $tableColumnInfo.Count;$c++) {
$length = $tableColumnInfo[$c].width
if(!$length) {
if($tableColumnInfo.Count -gt $c) {
## If right aligned, use the right side of the column header:
if($tableColumnInfo[$c].alignment -eq 3) {
$length = $start - ($separators[$c].index + $separators[$c].length)
## If the NEXT one is left aligned, use the left side of that header
} elseif($tableColumnInfo[$c+1].alignment -eq 1) {
$length = $Start - $separators[$c+1].index
## Otherwise, it's really hard to say what the right answer is...
## Technically, we need to scan all the way down the columns looking for whitespace
## Let's try a shortcut though...
} else {
$length = $start - ($separators[$c].index + $separators[$c].length)
}
}
$length = $tableColumnInfo[$c].width = $line.Length - $start
}
# Write-Warning "Start: $start, Length: $length (of $($line.Length))"
$outputRow.($tableColumnInfo[$c].label) = $line.substring($start, $length).Trim()
$start += $length + 1
}
$outputRow = New-Object PSObject -Property $outputRow
$outputRow | Add-Member -Type NoteProperty -Name OriginalItem -Value $Items[$i]
$null = $SelectViaUIStringItems.Add( $outputRow )
}
}
# Stick the original items on there ...
$SelectViaUIStringItems | Add-Member -Type ScriptMethod -Name ToString -Value { ($this.OriginalItem | Format-Table @formatParameters -HideTableHeaders | Out-String -Width 10000).Trim() } -Force
## Generate the window
# Show-UI -Title "Object Filter" -MinWidth 400 -Height 600 {
Grid -Margin 5 -ControlName SelectFTList -Rows Auto, *, Auto, Auto -Children {
## This is just a label ...
TextBlock -Margin 5 -Row 0 "Type or click to search. Press Enter or click OK to pass the items down the pipeline."
## Put the items in a ListBox, inside a ScrollViewer so it can scroll :)
ScrollViewer -Margin 5 -Row 1 {
ListView -SelectionMode Extended -ItemsSource $SelectViaUIStringItems -Name SelectedItems `
-FontFamily "Consolas, Courier New" -View {
GridView {
foreach($h in $tableColumnInfo) {
GridViewColumn -Header $h.label -DisplayMember { Binding $h.Label }
}
}
} -On_SelectionChanged {
if($selectedItems.SelectedItems.Count -gt 0)
{
$SelectFTList | Set-UIValue -value ( $selectedItems.SelectedItems | ForEach-Object { $_.OriginalItem } )
} else {
$SelectFTList | Set-UIValue -value ( $selectedItems.Items | ForEach-Object { $_.OriginalItem } )
}
} -On_Loaded {
## Default output, in case you close the window without selecting anything
$SelectFTList | Set-UIValue -value ( $selectedItems.Items | ForEach-Object { $_.OriginalItem } )
}
# -On_MouseDoubleClick { Close-Control $parent }
}
## This is the filter box: Notice we update the filter on_KeyUp
TextBox -Margin 5 -Name SearchText -Row 2 -On_KeyUp {
$filterText = $this.Text
[System.Windows.Data.CollectionViewSource]::GetDefaultView( $SelectedItems.ItemsSource ).Filter = [Predicate[Object]]{
param([string]$item)
## default to true
trap { return $true }
## Do a regex match
$item -match $filterText
}
## Update the output after the filter
if($selectedItems.SelectedItems.Count -gt 0)
{
$SelectFTList | Set-UIValue -value ( $selectedItems.SelectedItems | ForEach-Object { $_.OriginalItem } )
} else {
$SelectFTList | Set-UIValue -value ( $selectedItems.Items | ForEach-Object { $_.OriginalItem } )
}
}
## Use a GridPanel ... it's a simple, yet effective way to lay out a couple of buttons.
Grid -Margin 5 -HorizontalAlignment Right -Columns 65, 10, 65 {
Button "OK" -IsDefault -Width 65 -On_Click { Close-Control $window } -Column 0
Button "Cancel" -IsCancel -Width 65 -On_Click { $SelectFTList | Set-UIValue -value $null } -Column 2
} -Row 3
## Focus on the Search box by default
} -On_Loaded {
$SearchText.Focus()
} @uiParameters
}}
|
PowerShellCorpus/PoshCode/vProfile.ps1
|
vProfile.ps1
|
# vProfiler.ps1 : vSphere profiling script
# This script will export recursively all objects and properties of a VI/vSphere entity to a XML file
# Parameters:
# $entityName : the name of the vSphere entity for which the properties should be written to the XML file
# $childShow : Boolean switch, export all children of $entityName, and their properties, to the XML file
# $configShow : Boolean switch, export the properties to the XML file
# $vmDump : Boolean switch, include VirtualMachines in the XML file
# $profileDir : directory where the XML file will be written
# Author: LucD
# History:
# v1.0 27/08/09 first version, handles Folder, VirtualMachine, Datacenter, HostSystem, ClusterComputeResource, ResourcePool
#
# Parameters
$entityName = "Clus1"
$childShow = $true
$configShow = $false
$vmDump = $true
$profileDir = "C:\\"
# Root of the XML file
$vInventory = [xml]"<Inventory></Inventory>"
function New-XmlNode{
param($node, $nodeName)
$tmp = $global:vInventory.CreateElement($nodeName)
$node.AppendChild($tmp)
}
function Set-XmlAttribute{
param($node, $name, $value)
$node.SetAttribute($name, $value)
}
function Get-XmlNode{
param($path)
$global:vInventory.SelectNodes($path)
}
function Get-Properties{
param($BaseName, $Property, $XMLnode)
if(-not($Property -match "DynamicProperty$|DynamicType$")){
if($Property.Length -eq 0){
$XMLnewnode = New-XmlNode $XMLnode $BaseName.Substring(1)
}
else{
$XMLnewnode = New-XmlNode $XMLnode $Property
}
if((Invoke-Expression $BaseName) -ne $null){
$result = Invoke-Expression $BaseName
$type = Invoke-Expression ($BaseName + ".GetType()")
Set-XmlAttribute $XMLnewnode "Type" $type.Name
if($type.IsArray){
$ArrCount = Invoke-Expression ($BaseName + ".Count")
Set-XmlAttribute $XMLnewnode "Count" $ArrCount
for($i = 0; $i -lt $ArrCount; $i++){
Get-Properties ($BaseName + "[" + $i + "]") ($Property + "-" + $i + "-") $XMLnewnode
}
}
elseif($type.IsPrimitive -or $type.Name -eq "String" -or $type.Name -eq "DateTime"){
Set-XmlAttribute $XMLnewnode "Value" $result
}
else{
$props = $result | gm -memberType Property,NoteProperty
foreach($prop in $props){
Get-Properties ($BaseName + "." + $prop.Name) $prop.Name $XMLnewnode
}
}
}
}
}
function Get-Configuration{
param($object, $XMLnode, $label)
New-Variable -Name $label -Value $object
$properties = Get-Properties ('$' + $label) '' $XMLnode
}
function Get-Children{
param($entity, $path, $XMLnode, $recurse, $config)
if("vm","host" -notcontains $entity.Name){
$path += ("/" + $entity.Name)
}
switch -regex ($entity.gettype().name){
"Folder" {
if("vm","host" -notcontains $entity.Name){
$XMLnewnode = New-XmlNode $XMLnode "Folder"
Set-XmlAttribute $XMLnewnode "Name" $entity.Name
}
if($recurse -and $entity.ChildEntity -ne $null){
foreach($childfld in (Get-View -Id $entity.ChildEntity)){
Get-Children $childfld $path $XMLnewnode $recurse $config
}
}
}
"VirtualMachine"{
if($vmDump){
if($entity.Config.Template){$VMtype = "Template"} else {$VMtype = "VM"}
$XMLnewnode = New-XmlNode $XMLnode $VMtype
Set-XmlAttribute $XMLnewnode "Name" $entity.Name
if($config){
Get-Configuration $entity.Config $XMLnewnode "Config"
}
}
}
"Datacenter"{
$XMLnewnode = New-XmlNode $XMLnode "Datacenter"
Set-XmlAttribute $XMLnewnode "Name" $entity.Name
if($recurse -and $entity.HostFolder -ne $null){
foreach($childfld in (Get-View -Id $entity.HostFolder)){
Get-Children $childfld $path $XMLnewnode $recurse $config
}
}
}
"HostSystem|^ComputeResource$"{
$XMLnewnode = New-XmlNode $XMLnode "Host"
Set-XmlAttribute $XMLnewnode "Name" $entity.Name
if($config){
Get-Configuration $entity.Config $XMLnewnode "Config"
}
if($recurse -and $entity.ChildEntity -ne $null){
foreach($childfld in (Get-View -Id $entity.ChildEntity)){
Get-Children $childfld $path $XMLnewnode $recurse $config
}
}
}
"ClusterComputeResource" {
$XMLnewnode = New-XmlNode $XMLnode "Cluster"
Set-XmlAttribute $XMLnewnode "Name" $entity.Name
if($config){
Get-Configuration $entity.ConfigurationEx $XMLnewnode "ConfigurationEx"
}
if($recurse){
foreach($esx in (Get-View -Id $entity.Host)){
Get-Children $esx $path $XMLnewnode $recurse $config
}
$resourcePoolparent = Get-View -Id $entity.ResourcePool
if($resourcePoolParent.Vm -ne $null){
foreach($vm in (Get-View -Id $resourcePoolParent.Vm)){
Get-Children $vm $path $XMLnewnode $recurse $config
}
}
if($resourcePoolParent.resourcePool -ne $null){
foreach($respool in (Get-View -Id $resourcePoolParent.resourcePool)){
Get-Children $respool $path $XMLnewnode $recurse $config
}
}
}
}
"ResourcePool"{
$XMLnewnode = New-XmlNode $XMLnode "ResourcePool"
Set-XmlAttribute $XMLnewnode "Name" $entity.Name
if($config){
Get-Configuration $entity.Config $XMLnewnode "Config"
}
if($recurse -and $entity.Vm -ne $null){
foreach($childfld in (Get-View -Id $entity.Vm)){
Get-Children $childfld $path $XMLnewnode $recurse $config
}
}
}
Default{
write-host "Unhandled type" $entity.gettype().name
}
}
}
# Main function
Get-Inventory -Name $entityName | Get-View | % {
Get-Children $_ $path (Get-XmlNode "Inventory") $childShow $configShow
}
# Create vProfile XML file
$vInventory.Save($profileDir + "vProfile-" + $entityName + ".xml")
|
PowerShellCorpus/PoshCode/Check Exchange2010 queue.ps1
|
Check Exchange2010 queue.ps1
|
# Script: Exch2010QueueMonitor.ps1
# Purpose: This script can be set as a scheduled task to run every 30minutes and will monitor all exchange 2010 queue's. If a threshold of 10 is met an
# output file with the queue details will be e-mailed to all intended admins listed in the e-mail settings
# Author: Paperclips (The Dark Lord)
# Email: magiconion_M@hotmail.com
# Date: May 2011
# Comments: Lines 27, 31-35 should be populated with your own e-mail settings
# Notes:
# - tested with Exchange 2010 SP1
# - The log report output file will be created under "c:\\temp\\qu.txt"
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ukvms-wcas2/PowerShell/ -Authentication Kerberos
Import-PSSession $s
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
. $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1
Connect-ExchangeServer -auto
$filename = “c:\\temp\\qu.txt”
Start-Sleep -s 10
if (Get-ExchangeServer | Where { $_.isHubTransportServer -eq $true } | get-queue | Where-Object { $_.MessageCount -gt 10 })
{
Get-ExchangeServer | Where { $_.isHubTransportServer -eq $true } | get-queue | Where-Object { $_.MessageCount -gt 10 } | Format-Table -Wrap -AutoSize | out-file -filepath c:\\temp\\qu.txt
Start-Sleep -s 10
$smtpServer = “xxx.xxx.xxx.xxx”
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = “Monitor@contoso.com”
$msg.To.Add("admin1@mycompany.com")
#$msg.To.Add("admin2@mycompany.com")
#$msg.To.Add("admin3@mycompany.com")
#$msg.To.Add("admin4@mycompany.com")
$msg.Subject = “CAS SERVER QUEUE THRESHOLD REACHED - PLEASE CHECK EXCHANGE QUEUES”
$msg.Body = “Please see attached queue log file for queue information”
$msg.Attachments.Add($att)
$smtp.Send($msg)
}
|
PowerShellCorpus/PoshCode/Get-Parameter_10.ps1
|
Get-Parameter_10.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\\[System.Int32\\]" { $process.Type = "Int32 (nullable)"; break }
"Nullable``1\\[System.Boolean\\]" { $process.Type = "Boolean (nullable)"; break }
"Nullable``1\\[(.+)\\]" { $process.Type = $matches[1].Split('.')[-1]; 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/Get-Screenshot.ps1
|
Get-Screenshot.ps1
|
## Get-Screenshot -- THIS ONE works on PowerShell 1.0 and .Net 2.0 (or better)
############################################################################################################
## Usage:
## Get-Screenshot "C:\\Screencaps\\Screenshot.jpg"
## Get-Screenshot "$pwd\\Screen $(Get-Date -f 'yyyy-MM-dd HH.mm.ss').bmp"
## Get-Screenshot "$pwd\\$(Get-Date -f 'HH.mm.ss').png" | % { [Diagnostics.Process]::Start( $_ ) }
############################################################################################################
[Reflection.Assembly]::LoadWithPartialName( "System.Drawing" )
[Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" )
function Get-Screenshot {
param($filename)
$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen;
$screenshot = new-object System.Drawing.Bitmap $bounds.width, $bounds.height
$graphics = [System.Drawing.Graphics]::FromImage($screenshot)
# $bounds.Location.Offset(50,50)
$graphics.CopyFromScreen( $bounds.Location, [System.Drawing.Point]::Empty, $bounds.size)
$screenshot.Save($filename)
$graphics.Dispose()
$screenshot.Dispose()
ls $filename
}
|
PowerShellCorpus/PoshCode/Custom Speech Commands_2.ps1
|
Custom Speech Commands_2.ps1
|
#Filename commands.ps1
import-module "G:\\Documents\\Speech Macros\\custom.psm1"
import-module "G:\\Documents\\Speech Macros\\alice.psm1"
Add-SpeechCommands @{
"test command" = { Say $(Respond "3:2,4:0-2") }
" * the percentages * " = { Say $(Percentages) }
" * star date * " = { Say "Current, Star date,"$((Get-Date).year).$([math]::round($((Get-Date).dayofyear)/365, 2)*100)" -replace "([A-Za-z0-9.]){1}","`$1 " -replace "\\.","point")" }
" * mail * " = { Start-Process "https://mail.google.com" }
"Google * please" = { $term = $_ -replace "$Computer(.+?)Google (.+?) please", '$2'; Start-Process "http://www.google.com/search?q=$term" }
"What * time * " = { Say "It is $(Get-Date -f "h:mm tt")" }
"What is * time * " = { Say "It is $(Get-Date -f "h:mm tt")" }
"What time * " = { Say "It is $(Get-Date -f "h:mm tt")" }
" * some music * " = { Start-Process "grooveshark.exe" }
"What * date today" = { Say $(Get-Date -f "dddd, MMMM dd") }
#list processes
"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")
}
#Word Definition
" * the definition for * please" = {$define = $_ -replace "$Computer(.+?)the definition for (.+?) please", '$2' ;$outtext = Get-Definition("$define");Say "Definitions for $define, , , $outtext"}
} -Computer "alice" -Verbose
#eof
#Filename custom.psm1
function Get-Definition($word) {
#.Synopsis
# Polls wiktionary for top text definitons for a given $word input
#.Description
# This Function parses the top $lines definitions for a given
# $term into one string formatted for speech synthesis
#
#
Say "Sure"
if($word -match " "){Say "Fail, one word at a time please"; break}
$page = "http://simple.wiktionary.org/wiki/$word"
$ie = new-object -com "InternetExplorer.Application"
$ie.visible = $false
$ie.navigate($page)
while($ie.busy){Start-Sleep 1}
$output = " "
$lines = 0
for($d=0;$d -le $lines;$d++) { ## grab the definition strings from each table
$ol = @($ie.Document.getElementsByTagName("ol"))[0]
$li = @($ol.getElementsByTagName("li"))[$d]
$def = @($li.innerHTML)
$output += "$def"
if($d -lt $lines){ $output += ", or, " }
}
$ie.Quit()
$closeIE = [System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($ie)
Remove-Variable ie
$Clean-String($output)
}
function Clean-String([string]$str){
#.Synopsis
# Cleans string from web (most concerned about x/html tags)
#.Description
# Cleans input string of xml tags
# returns $str
#
#
$str = $str -replace "\\<[^<]*\\>", " "
$str = $str.replace(" ", "")
$str
}
function Respond($in, [string]$del = ","){
#.Synopsis
# Recursive.
# Returns a random response from $responses via the three dimensional array of choices: $choices[<groups>][<dimensions>][<values>]
# This function takes in a string indicating which responses from the $responses array
# to to choose from. It supports ranges (-) and direct selections (/) in each seed separated by (,).
#.Description
# the idea here is to respond based on this format: $in = "3:2,4:1-2,0/2-4/6:1"
# where 3:2 is a direct seed, 4:1-2 is a range seed (from 4:1 to 4:2),
# and 0/2-4/6:1 combines the two (effectively adds 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the choices)
# In heap, the above example would effectively add 3:2, 4:1, 4:2, 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the
# available choices, and will appear as $choices(@($xs(3),$ys(2)),@($xs(4),$ys(1,2)),@($xs(0,2,3,4,6),$ys(1)))
#
switch -wildcard ($del){
"`,"{
if($in -match "`,"){ #if more than one coordset, handle each
$coordsets = $in -split "`," #split coordsets apart
foreach($coordset in $coordsets){
$choices += ,(Respond $coordset "`:")
}
}
else{ #else pass the string to the next step,
$choices = ,(Respond $in "`:")
}
$choice = $choices[(get-random -min 0 -max $choices.count)] #choose one of the groups randomly
$responses[$choice[0]][$choice[1]];#pass response out of the function
}
"`:"{
$coords = $in -split "`:" #split coordset apart
foreach ($coord in $coords){
if(($coord -match "`/")-or($coord -match "`-")){ #if there's an or operator or a range
$dimensions += ,(Respond $coord "`/") # handle them, and add all values (in array) to this dimension (split fails elegantly)
}
else{
$dimensions += ,$coord #else just add the coord value (in an array) via comma operator
}
}
$dimensions #pass dimensions out dimensions is two dimensional array
}
"`/"{
$ranges = $in -split "`/" #split ORs apart (if theres not OR, the string is still added to $ranges[0])
foreach($range in $ranges){
if($range -match "`-"){#if theres a range to handle, do so
foreach ($val in (Respond $range "`-")){
$orVals += ,$val #append all values in returned range array to new array
}
}
else{# else just append the value to teh new array
$orVals += ,$range
}
}
,($orVals | get-random) #pass out single element array of random value from vals array
}
"`-"{
$vals = $in -split "`-" #split ranges apart
$vals[0]..$vals[1] # pass out array containing all values in range
}
}
}
$responses = (#Response Array
(##0-correct
"Right",
"Correct"
),
(##1-incorrect
"Wrong",
"Incorrect"
),
(##2-positive
"Yes",
"Aye",
"I'll give it a shot"
),
(##3-negative
"No",
"Negative",
"Not going to happen"
),
(##4-affirmation
"Sure",
"OK",
"Lets See"
),
(##5-retort
"your mom",
"your face"
),
(##6-insult
"You\\'re dumb",
"you fail"
),
(##7-eager
"I'm ready",
"Lets check it out"
),
(##8-apprehensive
"I don't know",
"Just a seck"
),
(##9-neutral
"oh",
"Hum"
)
)
function Percentages {
#.Synopsis
# Specific speech command that reads back
# remaining percentages of year, month, week, and day
#.Description
# Pretty self explanitory, basic maths, elucidatory var names
#
#
$date = get-date #capture date object
$daysInYear = [int]$(if([datetime]::IsLeapYear($date.year)){366}else{365}) #if leap year, 366, else 365
$daysInMonth = [int]$([datetime]::DaysInMonth($date.year, $date.month)) #capture days in month
$dayOfYear = [int]$date.dayofyear #days past (including today)
$dayOfMonth = [int]$date.day #days past (including today)
$hoursOfDay = [int]$date.hour #hours past (including current)
$minutesOfHour = [int]$date.minute #minutes past (including current)
switch ($date.dayofweek.toString()){ #assumes start of week is sunday
Sunday { [int]$dayOfWeek="1"; break }
Monday { [int]$dayOfWeek="2"; break }
Tuesday { [int]$dayOfWeek="3"; break }
Wednesday { [int]$dayOfWeek="4"; break }
Thursday { [int]$dayOfWeek="5"; break }
Friday { [int]$dayOfWeek="6"; break }
Saturday { [int]$dayOfWeek="7"; break }
}
$percentYearGone = $dayOfYear/$daysInYear #days of this year (including today) divided by total days in this year
$percentMonthGone = ((($dayOfMonth*24)-24)+$hoursOfDay)/($daysInMonth*24) #hours of this month divided by total hours in this month
$percentWeekGone = ((($dayOfWeek*24)-24)+$hoursOfDay)/(7*24) #hours of this week divided by total hours in a week
$percentDayGone = ((($hoursOfDay*60)-60)+$minutesOfDay)/(24*60) #minutes of today divided by total minutes in a day
$percentYearLeft = [math]::round((1-$percentYearGone)*100,1) #opposite percentages rounded to one decimal place
$percentMonthLeft = [math]::round((1-$percentMonthGone)*100,1) #^
$percentWeekLeft = [math]::round((1-$percentWeekGone)*100,1) #^
$percentDayLeft = [math]::round((1-$percentDayGone)*100,1) #^
$str = ""
$str += "There's "
$str += $percentYearLeft
$str += "% of this year, "
$str += $percentMonthLeft
$str += "% of this month, "
$str += $percentWeekLeft
$str += "% of this week, and "
$str += $percentDayLeft
$str += "% of today remaining, what will you do with it?"
$str
}
#eof
|
PowerShellCorpus/PoshCode/Test-VM_2.ps1
|
Test-VM_2.ps1
|
Function Test-VM
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$true,Position=1)]
[string[]]$Name,
[Parameter(Mandatory=$true,Position=2)]
[string[]]$ComputerName
)
Process
{
$results = @()
foreach ($cName in $ComputerName) {
foreach ($vName in $Name) {
$result = New-Object System.Management.Automation.PSObject
Try
{
$vm = Get-VM -ComputerName $cName -Name $vName -ErrorAction Stop
}
Catch
{
#Display an error message
}
if ($vm -ne $null) {
$Existence = $true
} else {
$Existence = $false
}
$result | Add-Member -NotePropertyName ComputerName -NotePropertyValue $cName
$result | Add-Member -NotePropertyName Name -NotePropertyValue $vName
$result | Add-Member -NotePropertyName Existence -NotePropertyValue $Existence
$results += $result
}
}
return $results
}
}
|
PowerShellCorpus/PoshCode/System Analyst II.ps1
|
System Analyst II.ps1
|
$strComputer = "PrinterName"
$Ports = get-wmiobject -class "win32_tcpipprinterport" -namespace "root\\CIMV2" -computername $strComputer
$Printers = get-wmiobject -class "Win32_Printer" -namespace "root\\CIMV2" -computername $strComputer
$ports | Select-Object Name,Hostaddress | Set-Variable port
$Printers | Select-Object Name,PortName,DriverName,location,Description | Set-Variable print
$num = 0
$hash = @{}
do {
$hash.Add($port.name[$num], $port.hostaddress[$num])
$num = $num + 1
} until ($num -eq $ports.Count)
# Creates Table
$table = New-Object system.Data.DataTable “$PrinterInfo”
$colName = New-Object system.Data.DataColumn PrinterName,([string])
$colIP = New-Object system.Data.DataColumn IP,([string])
$colDrive = New-Object system.Data.DataColumn DriverName,([string])
$colLoc = New-Object system.Data.DataColumn location,([string])
$colDesc = New-Object system.Data.DataColumn Description,([string])
$table.columns.add($colName)
$table.columns.add($colIP)
$table.columns.add($colDrive)
$table.columns.add($colLoc)
$table.columns.add($colDesc)
$num = 0
Do {
$row = $table.NewRow()
$row.PrinterName = $printers.name[$num]
$row.IP = $hash.get_item($printers.PortName[$num])
$row.DriverName = $printers.drivername[$num]
$row.Location = $printers.Location[$num]
$row.Description = $printers.Description[$num]
$table.Rows.Add($row)
$num = $num + 1
} until ($num -eq $printers.Count)
$table | Select-Object PrinterName,IP,DriverName,Location,Description | Export-Csv C:\\Printers.csv
|
PowerShellCorpus/PoshCode/Get-RecurseMember_3.ps1
|
Get-RecurseMember_3.ps1
|
function Get-RecurseMember {
<#
.Synopsis
Does a recursive search for unique users that are members of an AD group.
.Description
Recursively gets a list of unique users that are members of the specified
group, expanding any groups that are members out into their member users.
Note: Requires the Quest AD Cmdlets
http://www.quest.com/powershell/activeroles-server.aspx
.Parameter group
The name of the group.
.Example
PS> Get-RecurseMember 'My Domain Group'
.Notes
NAME: Get-RecurseMember
AUTHOR: tojo2000
#Requires -Version 2.0
#>
param([Parameter(Position = 0,
Mandatory = $true)]
[string]$group)
$users = @{}
try {
$members = Get-QADGroupMember $group
} catch [ArgumentException] {
Write-Host "`n`n'$group' not found!`n"
return $null
}
foreach ($member in $members) {
if ($member.Type -eq 'user') {
$users.$($member.Name.ToLower()) = $member
} elseif ($member.Type -eq 'group') {
foreach ($user in (Get-RecurseMember $member.Name)) {
$users.$($user.Name.ToLower()) = $user
}
}
}
foreach ($user in $users.Keys | sort) {
Write-Output $users.$user
}
}
|
PowerShellCorpus/PoshCode/Convert-StringSID.ps1
|
Convert-StringSID.ps1
|
function Convert-StringSID {
<#
.Synopsis
Takes a SID string and outputs a Win32_SID object.
.Parameter sidstring
The SID in SDDL format. Example: S-1-5-21-39260824-743453154-142223018-195717
.Description
Takes a SID string and outputs a Win32_SID object.
Note: it also adds an extra property, base64_sid, the base64 representation
of the binary SID.
.Example
PS> Convert-StringSID 'S-1-5-21-39260824-743453154-142223018-195717'
.Example
PS> $list_of_sids |
Convert-StringSID |
%{Write-Output "$($_.ReferenceDomainName)\\$($_.AccountName)"}
MYDOMAIN\\somename
MYDOMAIN\\anotheraccount
.Notes
NAME: Convert-Base64SID
AUTHOR: tojo2000
#Requires -Version 2.0
#>
param([Parameter(Position = 0,
Mandatory = $true,
ValueFromPipeline = $true]
[string]$sidstring)
BEGIN {}
PROCESS{
[wmi]$obj = 'Win32_SID.SID="{0}"' -f $sidstring
$encoded = [System.Convert]::ToBase64String($obj.BinaryRepresentation)
$obj |
Add-Member -MemberType NoteProperty -Name base64_sid -Value $encoded
Write-Output $obj
}
END{}
}
|
PowerShellCorpus/PoshCode/hugo.ps1
|
hugo.ps1
|
$choices = [System.Management.Automation.Host.ChoiceDescription[]](
(New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Choose me!"),
(New-Object System.Management.Automation.Host.ChoiceDescription "&No","Pick me!"))
$Answer = $host.ui.PromptForChoice('Caption',"Message",$choices,(1))
Write-Output $Answer
$fields = new-object "System.Collections.ObjectModel.Collection"[[System.Management.Automation.Host.FieldDescription]]"
$f = New-Object System.Management.Automation.Host.FieldDescription "String Field"
$f.HelpMessage = "This is the help for the first field"
$f.DefaultValue = "Field1"
$f.Label = "&Any Text"
$fields.Add($f)
$f = New-Object System.Management.Automation.Host.FieldDescription "Secure String"
$f.SetparameterType( [System.Security.SecureString] )
$f.HelpMessage = "You will get a password input with **** instead of characters"
$f.DefaultValue = "Password"
$f.Label = "&Password"
$fields.Add($f)
$f = New-Object System.Management.Automation.Host.FieldDescription "Numeric Value"
$f.SetparameterType( [int] )
$f.DefaultValue = "42"
$f.HelpMessage = "You need to type a number, or it will re-prompt"
$f.Label = "&Number"
$fields.Add($f)
$results = $Host.UI.Prompt( "Caption", "Message", $fields )
Write-Output $results
|
PowerShellCorpus/PoshCode/powershell ise config_2.ps1
|
powershell ise config_2.ps1
|
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" />
<supportedRuntime version="v2.0" />
<process>
<rollForward enabled="false" />
</process>
</startup>
<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>
</configuration>
|
PowerShellCorpus/PoshCode/Convert-StringSID_1.ps1
|
Convert-StringSID_1.ps1
|
function Convert-StringSID {
<#
.Synopsis
Takes a SID string and outputs a Win32_SID object.
.Parameter sidstring
The SID in SDDL format. Example: S-1-5-21-39260824-743453154-142223018-195717
.Description
Takes a SID string and outputs a Win32_SID object.
Note: it also adds an extra property, base64_sid, the base64 representation
of the binary SID.
.Example
PS> Convert-StringSID 'S-1-5-21-39260824-743453154-142223018-195717'
.Example
PS> $list_of_sids |
Convert-StringSID |
%{Write-Output "$($_.ReferenceDomainName)\\$($_.AccountName)"}
MYDOMAIN\\somename
MYDOMAIN\\anotheraccount
.Notes
NAME: Convert-Base64SID
AUTHOR: tojo2000
#Requires -Version 2.0
#>
param([Parameter(Position = 0,
Mandatory = $true,
@@ ValueFromPipeline = $true]
[string]$sidstring)
BEGIN {}
@@ PROCESS{
[wmi]$obj = 'Win32_SID.SID="{0}"' -f $sidstring
$encoded = [System.Convert]::ToBase64String($obj.BinaryRepresentation)
$obj |
Add-Member -MemberType NoteProperty -Name base64_sid -Value $encoded
Write-Output $obj
}
END{}
}
|
PowerShellCorpus/PoshCode/10.100.5.32.ps1
|
10.100.5.32.ps1
|
function Set-IPAddress {
param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"),
[string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"),
[string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"),
[string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"),
[string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"),
[string]$dns2,
[string]$registerDns = "TRUE"
)
$dns = $dns1
if($dns2){$dns ="$dns1,$dns2"}
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
$NetInterface.EnableStatic($ip, $subnetmask)
$NetInterface.SetGateways($gateway)
$NetInterface.SetDNSServerSearchOrder($dns)
$NetInterface.SetDynamicDNSRegistration($registerDns)
}
|
PowerShellCorpus/PoshCode/Out-DataTable_3.ps1
|
Out-DataTable_3.ps1
|
#######################
<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
Any object can be piped to Out-DataTable
.OUTPUTS
System.Data.DataTable
.EXAMPLE
$dt = Get-psdrive| Out-DataTable
This example creates a DataTable from the properties of Get-psdrive and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Fixed Issue with Properties
v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0
v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties
v1.4 - Chad Miller - Corrected issue with DBNull
v1.5 - Chad Miller - Updated example
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
[CmdletBinding()]
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
foreach ($object in $InputObject)
{
$DR = $DT.NewRow()
foreach($property in $object.PsObject.get_properties())
{
if ($first)
{
$Col = new-object Data.DataColumn
$Col.ColumnName = $property.Name.ToString()
if ($property.value)
{
if ($property.value -isnot [System.DBNull])
{ $Col.DataType = $property.value.gettype() }
}
$DT.Columns.Add($Col)
}
if ($property.IsArray)
{ $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }
else { $DR.Item($property.Name) = $property.value }
}
$DT.Rows.Add($DR)
$First = $false
}
}
End
{
Write-Output @(,($dt))
}
} #Out-DataTable
|
PowerShellCorpus/PoshCode/SpeakToMe.ps1
|
SpeakToMe.ps1
|
<#
inspired by HelloKitty script and Mike Hays's obsession for Julie Andrews
added voice selection menu, should work for everyone anywhere
interluded speaking by using string array joined with newline
still need to figure out $voiceToUse code, it's working but I don't know why or how
https://github.com/chriskenis/POSH.git
#>
[CmdletBinding()]
param(
[string] $Name = [Environment]::UserName,
[string[]] $Greetings = @("This is your computer speaking","It is now $(Get-Date)","The end"),
[byte] $Speed = 1
)
process{
$message = @"
.-. __ _ .-.
| ` / \\ |
/ '.()--\\
| '._/
_| O _ O |_
=\\ '-' /=
'-._____.-'
/`/\\___/\\`\\
/\\/o o\\/\\
(_| |_)
|____,____|
(____|____)
Hello World
"@
Write-Host $message -foregroundcolor magenta
$voice = new-object -com SAPI.SpVoice
$voice.Voice = $(SelectVoice $voice)
$voice.Rate = $Speed
}
begin{
# script variables
$nl = [Environment]::NewLine
Function SelectVoice($VoiceCom){
$voiceList = $VoiceCom.GetVoices()
$voiceDescList = @()
For ($i=0; $i -lt $voiceList.Count; $i++){
$voiceDescList += $($voiceList.Item($i).GetDescription())
write-verbose "$voiceDescList[$i]"
}
Write-Host "$nl Voice Selection: $nl"
For ($i=0; $i -lt $voiceList.Count; $i++){Write-Host -ForegroundColor Green "$i --> $($voiceDescList[$i])"}
Write-Host -ForegroundColor Green "q --> quit script"
Do {
$SelectIndex = Read-Host "Select voice by number or 'enter' (=default voice)"
Switch -regex ($SelectIndex){
"^q.*" {$SelectIndex="quit"; $kip = $true}
"\\d" {$SelectIndex = $SelectIndex -as [int];$kip = $false}
"^\\s*$" {$SelectIndex=0; $kip = $false}
}
}
Until (($SelectIndex -lt $voiceList.Count) -OR $SelectIndex -like "q*")
If ($kip) {exit}
$voiceMember = "Name=" + $voiceDescList[$SelectIndex]
write-verbose "$voiceMember"
$voiceToUse = $VoiceCom.GetVoices($voiceMember.Id).Item($SelectIndex)
write-verbose "Voice to use = $($voiceToUse.Id)"
return $voiceToUse
}
}
end{
[void]$voice.speak("Hi $Name, " + $nl + [string]::join($nl,$Greetings))
}
|
PowerShellCorpus/PoshCode/e0f06189-086f-4d62-a6c3-5a7e1f3ca246.ps1
|
e0f06189-086f-4d62-a6c3-5a7e1f3ca246.ps1
|
$computers = gc "listofservers.txt"
Get-WmiObject Win32_NetworkAdapterConfiguration -computer $computers -filter "IPEnabled ='true'" | select __Server,IPAddress
|
PowerShellCorpus/PoshCode/Read-HostMasked.ps1
|
Read-HostMasked.ps1
|
function Read-HostMasked([string]$prompt="Password") {
$password = Read-Host -AsSecureString $prompt;
$BSTR = [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($password);
$password = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR);
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR);
return $password;
}
|
PowerShellCorpus/PoshCode/FunctionInfo.types.ps1xm.ps1
|
FunctionInfo.types.ps1xm.ps1
|
<?xml version="1.0" encoding="utf-8" ?>
<Types>
<Type>
<Name>System.Management.Automation.FunctionInfo</Name>
<Members>
<ScriptProperty>
<Name>Verb</Name>
<GetScriptBlock>
if ($this.Name.Contains("-")) {
$this.Name.Substring(0,$this.Name.Indexof("-"))
} else {
$null
}
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Noun</Name>
<GetScriptBlock>
if ($this.Name.Contains("-")){
$this.Name.Substring(($this.Name.Indexof("-")+1),($this.Name.length - ($this.Name.Indexof("-")+1)))
} else {
$this.Name
}
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Prefix</Name>
<GetScriptBlock>
$prefix_val = $((gmo $this.Module).ExportedFunctions.Values + (gcm -mo $this.ModuleName -CommandType "Function") |
where { $_.Verb -eq $this.Verb } |
group { $_.Definition } |
% {
$names = $_.Group |
Select -Expand Name;
$ofs = "-";
$verb,[string]$noun = @($names)[0] -split "-";
foreach($name in $names){
if ( $name.contains("-") ) {
$name.substring($name.IndexOf("-") + 1, $name.LastIndexOf($noun) - $name.IndexOf("-") - 1 )
}
}
} | where {$_} | select -unique | foreach { $_ | where {$this.Noun -match $_ } })
if ( $prefix_val ) {
$prefix_val
} else {
$null
}
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>InternalName</Name>
<GetScriptBlock>
$prefix = $this.Prefix
if ($prefix) {
"$($this.Verb)-$($this.Noun.Replace($prefix, $null))"
} else {
"$($this.Name)"
}
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
</Types>
|
PowerShellCorpus/PoshCode/JSON.ps1
|
JSON.ps1
|
#requires -version 2.0
# No help (yet) because I'm still changing and renaming everything every time I mess with this code
Add-Type -Assembly System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
function Convert-JsonToXml
{
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN { $mStream = new-object System.IO.MemoryStream }
PROCESS {
$json | Write-String -Stream $mStream
}
END {
$mStream.Position = 0
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
try
{
$xml = new-object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
function Convert-XmlToJson
{
PARAM([Parameter(ValueFromPipeline=$true)][xml]$xml)
Process{
$mStream = new-object System.IO.MemoryStream
$jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream)
try
{
$xml.Save($jsonWriter)
$bytes = $mStream.ToArray()
[System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}
finally
{
$jsonWriter.Close()
$mStream.Dispose()
}
}
}
function ConvertFrom-Json {
PARAM( [Parameter(Mandatory=$true)][Type[]]$type, [Parameter(ValueFromPipeline=$true,Mandatory=$true)][String]$json )
PROCESS{
$ms = New-object IO.MemoryStream (,$utf8.GetBytes($json))
Import-Json $type $ms
$ms.dispose()
}
}
function Import-Json {
[CmdletBinding(DefaultParameterSetName="File")]
PARAM(
[Parameter(Mandatory=$true,Position=1)][Type[]]$type
,
[Parameter(Mandatory=$true,Position=2,ParameterSetName="Stream")][IO.Stream]$Stream
,
[Parameter(Mandatory=$true,Position=2,ParameterSetName="File")][String]$Path
)
BEGIN {
if($PSCmdlet.ParameterSetName -eq "File") {
$Stream = [IO.File]::Open($Path, "Read")
}
}
PROCESS{
if($type.Count -gt 1) {
$t,$types = @($type)
$js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $t, (,@($types))
} else {
$js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer @($type)[0]
}
Write-Output $js.ReadObject($Stream)
}
END {
if($PSCmdlet.ParameterSetName -eq "File") {
$Stream.Dispose()
}
}
}
function Export-Json {
[CmdletBinding(DefaultParameterSetName="File")]
PARAM(
[Parameter(Mandatory=$true,Position=1)][Array]$InputObject
,
[Parameter(Mandatory=$true,Position=2,ParameterSetName="Stream")][IO.Stream]$Stream
,
[Parameter(Mandatory=$true,Position=2,ParameterSetName="File")][String]$Path
)
BEGIN {
if($PSCmdlet.ParameterSetName -eq "File") {
$Stream = [IO.File]::Open($Path, "Write")
}
}
PROCESS {
[type]$Type = @($InputObject)[0].GetType()
if($Type -isnot [Array]) { #$InputObject.Count -gt 1 -and
[type]$Type = "$($Type)[]"
}
[Type[]]$types = ($InputObject | select -expand PsTypeNames) | % { $_ -split "`n" -replace "^Selected\\." } | Select -unique
#Write-Verbose $($Types | select -expand FullName | out-string)
#Write-Verbose "Stream: $($Stream.GetType())"
Write-Verbose "Output: $Type"
Write-Verbose "Input: $($InputObject.GetType())"
$js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $Type #, $Types #, ([int]::MaxValue), $false, $null, $false
$js.WriteObject( $stream, $InputObject )
}
END {
if($PSCmdlet.ParameterSetName -eq "File") {
$Stream.Dispose()
}
}
}
function ConvertTo-Json {
PARAM( [Parameter(ValueFromPipeline=$true,Mandatory=$true)]$object )
BEGIN {
[type]$lastType = $null
function Out-JsonString {
Param($items)
$ms = New-Object IO.MemoryStream
Export-Json $items.ToArray() $ms
$utf8.GetString( $ms.ToArray(), 0, $ms.Length )
$ms.Dispose()
}
}
PROCESS {
$thisType = $object.GetType()
if(!$lastType -or $lastType -ne $thisType) {
if($lastType) { Out-JsonString $items }
# make a new collection
$items = new-object "System.Collections.Generic.List[$thisType]"
}
$items.Add($object)
$lastType = $thisType
}
END {
Out-JsonString $items
}
}
function Write-String {
param([Parameter()]$stream,[Parameter(ValueFromPipeline=$true)]$string)
process {
$bytes = $utf8.GetBytes($string)
$stream.Write( $bytes, 0, $bytes.Length )
}
}
New-Alias fromjson ConvertFrom-Json
New-Alias tojson ConvertTo-Json
New-Alias cvfjs ConvertFrom-Json
New-Alias cvtjs ConvertTo-Json
New-Alias ipjs Import-Json
New-Alias epjs Export-Json
Export-ModuleMember -Function ConvertFrom-Json, Import-Json, Export-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson -Alias *
|
PowerShellCorpus/PoshCode/8bcc60bd-75ac-494b-9b5a-36860a627c35.ps1
|
8bcc60bd-75ac-494b-9b5a-36860a627c35.ps1
|
#Generated Form Function
function GenerateForm {
########################################################################
# THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE RISK
# OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
#
# Code Generated By: Richard Yaw
# Generated On: 23/09/2010
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$MigrationForm = New-Object System.Windows.Forms.Form
$Header = new-object System.Windows.Forms.Label
$MigrateButton = New-Object System.Windows.Forms.Button
$ClusterListBox = New-Object System.Windows.Forms.ListBox
$SourceHostListBox = New-Object System.Windows.Forms.ListBox
$SourceDBListBox = New-Object System.Windows.Forms.CheckedListBox
$SourceVMListBox = New-Object System.Windows.Forms.CheckedListBox
$DestinationListBox = New-Object System.Windows.Forms.ListBox
$vCenterLabel = New-Object System.Windows.Forms.Label
$VCTextBox = New-Object System.Windows.Forms.TextBox
$LoginButton = New-Object System.Windows.Forms.Button
$ClearMsgButton = New-Object System.Windows.Forms.Button
$UndoButton = New-Object System.Windows.Forms.Button
$UndoALLButton = New-Object System.Windows.Forms.Button
$SaveTaskButton = New-Object System.Windows.Forms.Button
$ClusterLabel = New-Object System.Windows.Forms.Label
$HostToHostButton = New-Object System.Windows.Forms.Button
$VMToHostButton = New-Object System.Windows.Forms.Button
$DBtoDBButton = New-Object System.Windows.Forms.Button
$VMtoDBButton = New-Object System.Windows.Forms.Button
$SourceButton = New-Object System.Windows.Forms.Button
$DestinationButton = New-Object System.Windows.Forms.Button
$ResetButton = New-Object System.Windows.Forms.Button
$ChangeVCButton = New-Object System.Windows.Forms.Button
$CloseButton = New-Object System.Windows.Forms.Button
$MessagesLabel = New-Object System.Windows.Forms.Label
$MessagesListBox = New-Object System.Windows.Forms.ListBox
$TaskLabel = New-Object System.Windows.Forms.Label
$TaskListBox = New-Object System.Windows.Forms.ListBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$LoginButton_Click=
{
#TODO: Place custom script here
If ($VCTextBox.Text -eq "")
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Enter a Valid vCenter Server.')
}
Else
{
if ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "VMware.VimAutomation.Core"
}
#Connect to vCenter
Connect-VIServer $VCTextBox.Text
$ClusterListBox.Enabled = $true
#Get Cluster
Get-Cluster | % { [void]$ClusterListBox.items.add($_.Name) }
If ($ClusterListBox.items -ne $null)
{
$LoginButton.Enabled = $false
$VCTextBox.Enabled = $false
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$ResetButton.Enabled = $true
$ChangeVCButton.Enabled = $true
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$HostToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$SourceHostListBox.Enabled = $true
$SourceHostListBox.Items.Clear()
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$SourceHostListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select One Host'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$HostToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$VMToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$DBtoDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceDBListBox)
$SourceDBListBox.Enabled = $true
$SourceDBListBox.Items.Clear()
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select a Datastore'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$DBtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$VMtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$SourceButton_OnClick=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
If ($SourceHostname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Source Host.')
}
Else
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object {$_.Name -notlike "$SourceHostname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceHostListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$SourceVMname = $SourceVMListBox.SelectedItem
If ($SourceVMname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One or More VMs.')
}
Else
{
if ($DestinationButton.Text -like "Destination Host")
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) }
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$DestinationListBox.items.add($_.Name) }
}
$DestinationListBox.Enabled = $true
$SourceVMListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -like "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
If ($SourceDBname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One Datastore.')
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceDBListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
}
$DestinationButton_OnClick=
{
#TODO: Place custom script here
$DestinationName = $DestinationListBox.SelectedItem
If ($DestinationName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Destination.')
}
Else
{
$DestinationListBox.Enabled = $false
$DestinationButton.Enabled = $false
$MigrateButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$MigrateButton_OnClick=
{
#TODO: Place custom script here
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-VMHost $SourceHostname | Get-VM
foreach($VM in $VMs)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceHostName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$DestinationListBox.Items.Clear()
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$DestinationName = $DestinationListBox.SelectedItem
If($DestinationButton.Text -eq "Destination Host")
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$SourceName = Get-VM -Name $VM | Get-VMHost | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
Else
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$DestinationListBox.Items.Clear()
}
If ($SourceButton.Text -eq "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-Datastore -Name $SourceDBname | Get-VM
If($VMs.count -gt 0)
{
foreach($VM in $VMs)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
If ($VMsize -gt $DBFreeSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceDBName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - No VM is present on the source datastore $SourceDBname."
[void]$MessagesListBox.items.add($MsgLine)
}
$SourceDBListBox.enabled = $true
$SourceButton.enabled = $true
$DestinationListBox.Items.Clear()
$MigrateButton.Enabled = $false
}
}
$RESETButton_OnClick=
{
#TODO: Place custom script here
$ClusterListBox.Enabled = $true
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
}
$ChangeVCButton_OnClick=
{
#TODO: Place custom script here
$VCTextBox.Text = ""
$VCTextBox.Enabled = $true
$LoginButton.Enabled = $true
$ClusterListBox.Items.Clear()
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$ResetButton.Enabled = $false
$ChangeVCButton.Enabled = $false
$MessagesListBox.Items.Clear()
$TaskListBox.Items.Clear()
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
$CloseButton_OnClick=
{
#TODO: Place custom script here
If ($VCTextBox.Text -ne "")
{
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
#Close Form
$MigrationForm.close()
}
$ClearMsgButton_Click=
{
#TODO: Place custom script here
If($MessagesListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('No messages to clear.')
}
Else
{
$MessagesListBox.items.clear()
}
}
$UndoButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
If ($TaskListBox.SelectedItems.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please select one or more tasks.')
}
Else
{
foreach($Task in $TaskListBox.SelectedItems)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$SourceName = $Task[9]
$DestinationName = $Task[7]
Get-VM -Name $VM | Move-VM -Destination (Get-VMhost $DestinationName)
}
While($TaskListBox.SelectedItems.Count -gt 0)
{
$TaskListBox.Items.Remove($TaskListBox.SelectedItems[0])
}
}
}
}
$UndoALLButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
foreach($Task in $TaskListBox.Items)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$SourceName = $Task[9]
$DestinationName = $Task[7]
Get-VM -Name $VM | Move-VM -Destination (Get-VMhost $DestinationName)
}
$TaskListBox.Items.Clear()
}
}
$SaveTaskButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Nothing to save to log file.')
}
Else
{
$SaveFileD = new-object System.Windows.Forms.SaveFileDialog
$SaveFileD.Filter = "All files (*.*)|*.*|log files (*.log)|*.log";
$SaveFileD.Title = "Save to a log file";
$SaveFileD.FilterIndex = 2;
$SaveFileD.RestoreDirectory = $true;
if ($SaveFileD.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $SaveFileD.FileName
$Tasks = $TaskListBox.items
$logheader = "Easy Migration Tool v1.0 - Log generated on " + (Get-Date)
#Save a log file for this session to a location selected by the user
Out-File -InputObject $logheader -FilePath $Filename
Out-File -InputObject "" -Append -FilePath $FileName
Out-File -InputObject $Tasks -Append -FilePath $FileName
}
}
}
#----------------------------------------------
#region Generated Form Code
# Start Main Form
$MigrationForm.Text = 'Easy Migration Tool v1.0'
$MigrationForm.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MigrationForm.Name = 'EasyMigrationForm'
$MigrationForm.StartPosition = "CenterScreen"
$MigrationForm.FormBorderStyle = "FixedDialog"
$MigrationForm.MaximizeBox = $false
$MigrationForm.MinimizeBox = $false
$MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 1030
$System_Drawing_Size.Height = 500
$MigrationForm.ClientSize = $System_Drawing_Size
# End Main Form
#Start Easy_Migration Header
$Header.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold)
$Header.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
$Header.Text = 'Easy Migration Tool v1.0'
$Header.Location = new-object System.Drawing.Point(150,15)
$Header.Size = new-object System.Drawing.Size(230, 20)
$MigrationForm.Controls.Add($Header)
#End Easy_Migration Header
# Start vCenter Server Label
$vCenterLabel.TabIndex = 2
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 20
$vCenterLabel.Size = $System_Drawing_Size
$vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$vCenterLabel.Text = 'vCenter Server:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 15
$System_Drawing_Point.Y = 50
$vCenterLabel.Location = $System_Drawing_Point
$vCenterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$vCenterLabel.Name = 'vCenterLabel'
$MigrationForm.Controls.Add($vCenterLabel)
# End vCenter Server Label
# Start vCenter Textbox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 20
$VCTextBox.Size = $System_Drawing_Size
$VCTextBox.Font = new-object System.Drawing.Font("Tahoma",8)
$VCTextBox.DataBindings.DefaultDataSourceUpdateMode = 0
$VCTextBox.Name = 'VCTextBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 50
$VCTextBox.Location = $System_Drawing_Point
$VCTextBox.TabIndex = 1
$MigrationForm.Controls.Add($VCTextBox)
# End vCenter Textbox
# Start Login Button
$LoginButton.TabIndex = 0
$LoginButton.Name = 'LoginButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 20
$LoginButton.Size = $System_Drawing_Size
$LoginButton.Font = new-object System.Drawing.Font("Tahoma",8)
$LoginButton.UseVisualStyleBackColor = $True
$LoginButton.Text = 'Login'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 50
$LoginButton.Location = $System_Drawing_Point
$LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0
$LoginButton.add_Click($LoginButton_Click)
$MigrationForm.Controls.Add($LoginButton)
# End Login Button
# Start Change VC Button
$ChangeVCButton.TabIndex = 19
$ChangeVCButton.Name = 'ChangeVCButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 20
$ChangeVCButton.Size = $System_Drawing_Size
$ChangeVCButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ChangeVCButton.UseVisualStyleBackColor = $True
$ChangeVCButton.Text = 'Change vCenter'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 360
$System_Drawing_Point.Y = 50
$ChangeVCButton.Location = $System_Drawing_Point
$ChangeVCButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ChangeVCButton.add_Click($ChangeVCButton_OnClick)
$ChangeVCButton.Enabled = $false
$MigrationForm.Controls.Add($ChangeVCButton)
# End Change VC Button
# Start Cluster Listbox
$ClusterLabel.TabIndex = 5
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 85
$System_Drawing_Size.Height = 20
$ClusterLabel.Size = $System_Drawing_Size
$ClusterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$ClusterLabel.Text = 'Select Cluster:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 20
$System_Drawing_Point.Y = 90
$ClusterLabel.Location = $System_Drawing_Point
$ClusterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterLabel.Name = 'ClusterLabel'
$MigrationForm.Controls.Add($ClusterLabel)
$ClusterListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 100
$ClusterListBox.Size = $System_Drawing_Size
$ClusterListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$ClusterListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterListBox.Name = 'ClusterListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 90
$ClusterListBox.Location = $System_Drawing_Point
$ClusterListBox.MultiColumn = $false
$ClusterListBox.TabIndex = 5
$ClusterListBox.Sorted = $True
$MigrationForm.Controls.Add($ClusterListBox)
# End Cluster Listbox
# Start Host to Host Button
$HostToHostButton.TabIndex = 3
$HostToHostButton.Name = 'HostToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$HostToHostButton.Size = $System_Drawing_Size
$HostToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$HostToHostButton.UseVisualStyleBackColor = $True
$HostToHostButton.Text = 'Host to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 90
$HostToHostButton.Location = $System_Drawing_Point
$HostToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$HostToHostButton.add_Click($HostToHostButton_Click)
$HostToHostButton.Enabled = $false
$MigrationForm.Controls.Add($HostToHostButton)
# End Host to Host Button
# Start VM to Host Button
$VMToHostButton.TabIndex = 3
$VMToHostButton.Name = 'VMToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMToHostButton.Size = $System_Drawing_Size
$VMToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMToHostButton.UseVisualStyleBackColor = $True
$VMToHostButton.Text = 'VM to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 115
$VMToHostButton.Location = $System_Drawing_Point
$VMToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMToHostButton.add_Click($VMToHostButton_Click)
$VMToHostButton.Enabled = $false
$MigrationForm.Controls.Add($VMToHostButton)
# End VM to Host Button
# Start Datastore to Datastore Button
$DBtoDBButton.TabIndex = 3
$DBtoDBButton.Name = 'DBtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$DBtoDBButton.Size = $System_Drawing_Size
$DBtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DBtoDBButton.UseVisualStyleBackColor = $True
$DBtoDBButton.Text = 'Datastore to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 140
$DBtoDBButton.Location = $System_Drawing_Point
$DBtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DBtoDBButton.add_Click($DBtoDBButton_Click)
$DBtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($DBtoDBButton)
# End Datastore to Datastore Button
# Start VM to Datastore Button
$VMtoDBButton.TabIndex = 3
$VMtoDBButton.Name = 'VMtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMtoDBButton.Size = $System_Drawing_Size
$VMtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMtoDBButton.UseVisualStyleBackColor = $True
$VMtoDBButton.Text = 'VM to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 165
$VMtoDBButton.Location = $System_Drawing_Point
$VMtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMtoDBButton.add_Click($VMtoDBButton_Click)
$VMtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($VMtoDBButton)
# End VM to Datastore Button
# Start Source Host List Box
$SourceHostListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceHostListBox.Size = $System_Drawing_Size
$SourceHostListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceHostListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceHostListBox.Name = 'SourceHostListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceHostListBox.Location = $System_Drawing_Point
$SourceHostListBox.MultiColumn = $false
$SourceHostListBox.TabIndex = 5
$SourceHostListBox.Sorted = $True
$MigrationForm.Controls.Add($SourceHostListBox)
# End Source Host List Box
# Start Source Datastore List Box
$SourceDBListBox.FormattingEnabled = $True
$SourceDBListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceDBListBox.Size = $System_Drawing_Size
$SourceDBListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceDBListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceDBListBox.Name = 'SourceDBListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceDBListBox.Location = $System_Drawing_Point
$SourceDBListBox.MultiColumn = $false
$SourceDBListBox.TabIndex = 5
$SourceDBListBox.Sorted = $True
# End Source Datastore List Box
# Start Source VM List Box
$SourceVMListBox.FormattingEnabled = $True
$SourceVMListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceVMListBox.Size = $System_Drawing_Size
$SourceVMListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceVMListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceVMListBox.Name = 'SourceVMListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceVMListBox.Location = $System_Drawing_Point
$SourceVMListBox.MultiColumn = $false
$SourceVMListBox.TabIndex = 5
$SourceVMListBox.Sorted = $True
# End Source VM List Box
# Start Source Button
$SourceButton.TabIndex = 7
$SourceButton.Name = 'Source Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$SourceButton.Size = $System_Drawing_Size
$SourceButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceButton.UseVisualStyleBackColor = $True
$SourceButton.Text = 'Source'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 415
$SourceButton.Location = $System_Drawing_Point
$SourceButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceButton.add_Click($SourceButton_OnClick)
$SourceButton.Enabled = $false
$MigrationForm.Controls.Add($SourceButton)
# End Source Button
# Start Destination List Box
$DestinationListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$DestinationListBox.Size = $System_Drawing_Size
$DestinationListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationListBox.Name = 'DestinationListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 210
$DestinationListBox.Location = $System_Drawing_Point
$DestinationListBox.MultiColumn = $false
$DestinationListBox.TabIndex = 5
$DestinationListBox.Sorted = $True
$MigrationForm.Controls.Add($DestinationListBox)
# End Destination List Box
# Start Destination Button
$DestinationButton.TabIndex = 7
$DestinationButton.Name = 'Destination Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$DestinationButton.Size = $System_Drawing_Size
$DestinationButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationButton.UseVisualStyleBackColor = $True
$DestinationButton.Text = 'Destination'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 415
$DestinationButton.Location = $System_Drawing_Point
$DestinationButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationButton.add_Click($DestinationButton_OnClick)
$DestinationButton.Enabled = $false
$MigrationForm.Controls.Add($DestinationButton)
# End Destination Button
# Start Migrate Button
$MigrateButton.TabIndex = 7
$MigrateButton.Name = 'MigrateButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$MigrateButton.Size = $System_Drawing_Size
$MigrateButton.Font = new-object System.Drawing.Font("Tahoma",8)
$MigrateButton.UseVisualStyleBackColor = $True
$MigrateButton.Text = 'Migrate'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 450
$MigrateButton.Location = $System_Drawing_Point
$MigrateButton.DataBindings.DefaultDataSourceUpdateMode = 0
$MigrateButton.add_Click($MigrateButton_OnClick)
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Add($MigrateButton)
# End Migrate Button
# Start RESET Button
$ResetButton.TabIndex = 19
$ResetButton.Name = 'ResetButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 140
$System_Drawing_Size.Height = 25
$ResetButton.Size = $System_Drawing_Size
$ResetButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ResetButton.UseVisualStyleBackColor = $True
$ResetButton.Text = 'Reset'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 450
$ResetButton.Location = $System_Drawing_Point
$ResetButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ResetButton.add_Click($ResetButton_OnClick)
$ResetButton.Enabled = $false
$MigrationForm.Controls.Add($ResetButton)
# End RESET Button
# Start CLOSE Button
$CloseButton.TabIndex = 19
$CloseButton.Name = 'CloseButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$CloseButton.Size = $System_Drawing_Size
$CloseButton.Font = new-object System.Drawing.Font("Tahoma",8)
$CloseButton.UseVisualStyleBackColor = $True
$CloseButton.Text = 'Close'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 320
$System_Drawing_Point.Y = 450
$CloseButton.Location = $System_Drawing_Point
$CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0
$CloseButton.add_Click($CloseButton_OnClick)
$MigrationForm.Controls.Add($CloseButton)
# End CLOSE Button
# Start Messages ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$MessagesLabel.Size = $System_Drawing_Size
$MessagesLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MessagesLabel.Text = 'Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 50
$MessagesLabel.Location = $System_Drawing_Point
$MessagesLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesLabel.Name = 'MessagesLabel'
$MigrationForm.Controls.Add($MessagesLabel)
$MessagesListBox.FormattingEnabled = $True
$MessagesListBox.SelectionMode = "None"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 140
$MessagesListBox.Size = $System_Drawing_Size
$MessagesListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$MessagesListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesListBox.Name = 'MessagesListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 70
$MessagesListBox.Location = $System_Drawing_Point
$MessagesListBox.MultiColumn = $false
$MessagesListBox.HorizontalScrollbar = $true
$MigrationForm.Controls.Add($MessagesListBox)
# End Messages ListBox
# Start Task ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$TaskLabel.Size = $System_Drawing_Size
$TaskLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$TaskLabel.Text = 'Recent Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 215
$TaskLabel.Location = $System_Drawing_Point
$TaskLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskLabel.Name = 'TaskLabel'
$MigrationForm.Controls.Add($TaskLabel)
$TaskListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 200
$TaskListBox.Size = $System_Drawing_Size
$TaskListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$TaskListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskListBox.Name = 'TaskListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 235
$TaskListBox.Location = $System_Drawing_Point
$TaskListBox.MultiColumn = $false
$TaskListBox.HorizontalScrollbar = $true
$TaskListBox.SelectionMode = "MultiExtended"
$MigrationForm.Controls.Add($TaskListBox)
# End Task ListBox
# Start Clear Messages Button
$ClearMsgButton.TabIndex = 0
$ClearMsgButton.Name = 'ClearMsgButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 25
$ClearMsgButton.Size = $System_Drawing_Size
$ClearMsgButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ClearMsgButton.UseVisualStyleBackColor = $True
$ClearMsgButton.Text = 'Clear Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 450
$ClearMsgButton.Location = $System_Drawing_Point
$ClearMsgButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ClearMsgButton.add_Click($ClearMsgButton_Click)
$MigrationForm.Controls.Add($ClearMsgButton)
# End Clear Messages Button
# Start Undo Button
$UndoButton.TabIndex = 0
$UndoButton.Name = 'UndoButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 25
$UndoButton.Size = $System_Drawing_Size
$UndoButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoButton.UseVisualStyleBackColor = $True
$UndoButton.Text = 'Undo'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 615
$System_Drawing_Point.Y = 450
$UndoButton.Location = $System_Drawing_Point
$UndoButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoButton.add_Click($UndoButton_Click)
$MigrationForm.Controls.Add($UndoButton)
# End Undo Button
# Start UndoALL Button
$UndoALLButton.TabIndex = 0
$UndoALLButton.Name = 'UndoALLButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 25
$UndoALLButton.Size = $System_Drawing_Size
$UndoALLButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoALLButton.UseVisualStyleBackColor = $True
$UndoALLButton.Text = 'Undo ALL'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 750
$System_Drawing_Point.Y = 450
$UndoALLButton.Location = $System_Drawing_Point
$UndoALLButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoALLButton.add_Click($UndoALLButton_Click)
$MigrationForm.Controls.Add($UndoALLButton)
# End UndoALL Button
# Start Save Task Button
$SaveTaskButton.TabIndex = 0
$SaveTaskButton.Name = 'SaveTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 25
$SaveTaskButton.Size = $System_Drawing_Size
$SaveTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SaveTaskButton.UseVisualStyleBackColor = $True
$SaveTaskButton.Text = 'Save Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 885
$System_Drawing_Point.Y = 450
$SaveTaskButton.Location = $System_Drawing_Point
$SaveTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SaveTaskButton.add_Click($SaveTaskButton_Click)
$MigrationForm.Controls.Add($SaveTaskButton)
# End Save Task Button
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $MigrationForm.WindowState
#Init the OnLoad event to correct the initial state of the form
$MigrationForm.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$MigrationForm.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Get Network Utilization_2.ps1
|
Get Network Utilization_2.ps1
|
$counters = @()
foreach ($inst in (new-object System.Diagnostics.PerformanceCounterCategory("network interface")).GetInstanceNames()){
$cur = New-Object system.Diagnostics.PerformanceCounter('Network Interface','Bytes Total/sec', $inst)
$max = New-Object system.Diagnostics.PerformanceCounter('Network Interface','Current Bandwidth', $inst)
$cur.NextValue() | Out-Null
$max.NextValue() | Out-Null
$counters += @{"Throughput"=$cur;"Bandwidth"=$max;"Name"=$inst}
}
sleep 2
foreach($counter in $counters) {
$curnum = $counter.Throughput.NextValue()
$maxnum = $counter.Bandwidth.NextValue()
New-Object PSObject -Property @{"Util"=$((( $curnum * 8 ) / $maxnum ) * 100);"Name"=$counter.Name}
}
|
PowerShellCorpus/PoshCode/Script permissions_2.ps1
|
Script permissions_2.ps1
|
<#
.SYNOPSIS
Applies permissions and roles to vSphere vApps
.DESCRIPTION
Applies permissions and roles to vSphere vApps
-VIServer (Optional, defaults to Development) {FQDN of VCentre Server}
-AppName (Required) {VApp Label}
-ADGroup (Optional) {Domain\\Group_Object}
-Role (Optional) {vSphere Role, ReadOnly, Owner-Managed, Supplier-Managed}
.EXAMPLE
Grants the Owner-Managed vSphere role to MYDOM\\MYGroup on the "Test VApp".
Create-Permissions -AppName "Test VApp" -ADGroup "MYDOM\\MYGroup" -Role "Owner-Managed"
#>
#Author: Ant B 2012
Param(
[String]$VIServer = "<Default VC>",
[parameter(Mandatory=$true)][String]$AppName,
[parameter(Mandatory=$true)][string]$ADGroup,
[parameter(Mandatory=$true)][string]$Role
)
#Check for the VMware Snapin, load if it isn't already there.
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin VMware.VimAutomation.Core
}
#Connect to VCentre
Connect-VIServer $VIServer
$authmgr = Get-View AuthorizationManager
$perm = New-Object Vmware.VIM.Permission
$perm.principal = $ADGroup
$perm.group = $true
$perm.propagate = $true
$perm.roleid = ($authmgr.Rolelist | where{$_.bosshog -eq $Role}).Roleid
$target = get-vapp | select name, Id | where{$_.Name -eq $AppName}
$authmgr.SetEntityPermissions($target.Id, $perm)
#Close our connection to VCentre
Disconnect-VIServer -Server * -Force -Confirm:$False
|
PowerShellCorpus/PoshCode/Add-ExtendedFileProperti.ps1
|
Add-ExtendedFileProperti.ps1
|
##############################################################################\n##\n## Add-ExtendedFileProperties\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nAdd the extended file properties normally shown in Exlorer's\n"File Properties" tab.\n\n.EXAMPLE\n\nGet-ChildItem | Add-ExtendedFileProperties.ps1 | Format-Table Name,"Bit Rate"\n\n#>\n\nbegin\n{\n Set-StrictMode -Version Latest\n\n ## Create the Shell.Application COM object that provides this\n ## functionality\n $shellObject = New-Object -Com Shell.Application\n\n ## Store the property names and identifiers for all of the shell\n ## properties\n $itemProperties = $null\n}\n\nprocess\n{\n ## Get the file from the input pipeline. If it is just a filename\n ## (rather than a real file,) piping it to the Get-Item cmdlet will\n ## get the file it represents.\n $fileItem = $_ | Get-Item\n\n ## Don't process directories\n if($fileItem.PsIsContainer)\n {\n $fileItem\n return\n }\n\n ## Extract the file name and directory name\n $directoryName = $fileItem.DirectoryName\n $filename = $fileItem.Name\n\n ## Create the folder object and shell item from the COM object\n $folderObject = $shellObject.NameSpace($directoryName)\n $item = $folderObject.ParseName($filename)\n\n ## Populate the item properties\n if(-not $itemProperties)\n {\n $itemProperties = @{}\n\n $counter = 0\n $columnName = ""\n do\n {\n $columnName = $folderObject.GetDetailsOf(\n $folderObject.Items, $counter)\n if($columnName) { $itemProperties[$counter] = $columnName }\n\n $counter++\n } while($columnName)\n }\n\n ## Now, go through each property and add its information as a\n ## property to the file we are about to return\n foreach($itemProperty in $itemProperties.Keys)\n {\n $fileItem | Add-Member NoteProperty $itemProperties[$itemProperty] `\n $folderObject.GetDetailsOf($item, $itemProperty) -ErrorAction `\n SilentlyContinue\n }\n\n ## Finally, return the file with the extra shell information\n $fileItem\n}
|
PowerShellCorpus/PoshCode/Test-IPMask.ps1
|
Test-IPMask.ps1
|
<#
.SYNOPSIS
Tests for a valid IP mask.
.DESCRIPTION
The Test-IPMask script validates the input string against all CIDR subnet masks and returns a boolean value.
.PARAMETER IPMask
The IP mask to be evaluated.
.EXAMPLE
Test-IPMask 255.255.255.0
Description
-----------
Tests if the IP mask "255.255.255.0" is a valid CIDR subnet mask.
.INPUTS
System.String
.OUTPUTS
System.String
System.Boolean
.NOTES
Name: Test-IPMask.ps1
Author: Rich Kusak (rkusak@cbcag.edu)
Created: 2011-01-03
LastEdit: 2011-01-05 00:37
Version 1.0.0
#Requires -Version 2.0
.LINK
http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
.LINK
about_regular_expressions
#>
[CmdletBinding()]
param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[string]$IPMask
)
begin {
# Common subnet mask values
$common = '0|128|192|224|240|248|252|254|255'
# Build a regular expression to represent all possible mask strings
$masks = @(
"(^($common)\\.0\\.0\\.0$)"
"(^255\\.($common)\\.0\\.0$)"
"(^255\\.255\\.($common)\\.0$)"
"(^255\\.255\\.255\\.($common)$)"
)
# Join all possible strings with the regex "or" operator
$regex = [string]::Join('|', $masks)
}
process {
# Evaluate the IPMask input
$result = [regex]::Match($IPMask, $regex).Success
# Create an output object containing the results of the evaluation
New-Object PSObject -Property @{
'IPMask' = $IPMask
'Valid' = $(
if ($result) {
$true
} else {
$false
}
)
}
}
|
PowerShellCorpus/PoshCode/SharePoint Large Lists_2.ps1
|
SharePoint Large Lists_2.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 ($list.RoleAssignments.Count -gt 0 -and $listAdmins.Count -gt 0)
{
$fields += $listAdmins[0].Member.Name
$fields += $listAdmins[0].Member.Email
$fields += [string]::Join("; ", @($listAdmins | % { $_.Member.ToString() } ))
} 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/WPFDbSpace.ps1
|
WPFDbSpace.ps1
|
#Usage: Get-SqlDatabase 'Z002\\Sql2k8' | where {$_.name -like "pubs*"} | ./WPFDbSpace.ps1
#Note: Requires .NET 3.5, Visifire Charts (tested on v2.1.0), Powerboots (tested on v0.1), and SQLPSX (tested on v1.5)
$libraryDir = Convert-Path (Resolve-Path "$ProfileDir\\Libraries")
[Void][Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path "$libraryDir\\WPFVisifire.Charts.dll")) )
. $libraryDir\\LibrarySmo.ps1
if (!(Get-PSSnapin | ?{$_.name -eq 'PoshWpf'}))
{ Add-PsSnapin PoshWpf }
New-BootsWindow -Async {
$chart = New-Object Visifire.Charts.Chart
$chart.Height = 500
$chart.Width = 800
$chart.watermark = $false
$chart.Theme = "Theme2"
$chart.View3D = $true
$chart.BorderBrush = [System.Windows.Media.Brush]"Gray"
$chart.CornerRadius = [System.Windows.CornerRadius]5
$chart.BorderThickness = [System.Windows.Thickness]0.5
$chart.AnimationEnabled = $false
$ds1 = New-Object Visifire.Charts.DataSeries
$ds1.RenderAs = [Visifire.Charts.RenderAs]"StackedBar"
$ds1.LegendText = "UsedSpace"
$ds1.LabelEnabled = $true
$ds1.LabelText = "#YValue"
$ds2 = New-Object Visifire.Charts.DataSeries
$ds2.RenderAs = [Visifire.Charts.RenderAs]"StackedBar"
$ds2.LegendText = "FreeSpace"
$ds2.LabelEnabled = $true
$ds2.LabelText = "#YValue"
$ds2.RadiusX = 5
$ds2.RadiusY = 5
foreach ($db in $input)
{
if ($db.GetType().Name -ne 'Database')
{ throw 'Input must be Database object' }
foreach ($file in Get-SqlDataFile $db)
{
$dp1 = new-object Visifire.Charts.DataPoint
$dp1.AxisXLabel = ($db.Name + '.' + $file.Name)
$dp1.YValue = ([int]($file.UsedSpace/1KB))
$ds1.DataPoints.Add($dp1)
$dp2 = new-object Visifire.Charts.DataPoint
$dp2.YValue = ([int](($file.Size - $file.UsedSpace)/1KB))
$ds2.DataPoints.Add($dp2)
}
$log = Get-SqlLogFile $db
$dp3 = new-object Visifire.Charts.DataPoint
$dp3.AxisXLabel = ($db.Name + '.' + $log.Name)
$dp3.YValue = ([int]($log.UsedSpace/1KB))
$ds1.DataPoints.Add($dp3)
$dp4 = new-object Visifire.Charts.DataPoint
$dp4.YValue = ([int](($log.Size - $log.UsedSpace)/1KB))
$ds2.DataPoints.Add($dp4)
}
$chart.Series.Add($ds1)
$chart.Series.Add($ds2)
$chart
} -Title "Database Space"
|
PowerShellCorpus/PoshCode/Get-Help.ps1
|
Get-Help.ps1
|
#function get-help() {\ncmdlet -DefaultParameterSet AllUsersView `\n\nparam(\n [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]\n [System.String]\n $Name,\n\n [ValidateSet("Alias","Cmdlet","Provider","General","FAQ","Glossary","HelpFile","All")]\n [System.String[]]\n $Category,\n\n [System.String[]]\n $Component,\n\n [System.String[]]\n $Functionality,\n\n [System.String[]]\n $Role,\n\n [Parameter(ParameterSetName="DetailedView")]\n [Switch]\n $Detailed,\n\n [Parameter(ParameterSetName="AllUsersView")]\n [Switch]\n $Full,\n\n [Parameter(ParameterSetName="Examples")]\n [Switch]\n $Examples,\n\n [Parameter(ParameterSetName="Parameters")]\n [System.String]\n $Parameter\n)\nBegin\n{ \n $wrappedCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet('Get-Help')\n $scriptCmd = { \n Microsoft.PowerShell.Core\\Get-Help @CommandLineParameters -EA "SilentlyContinue"\n }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline()\n $steppablePipeline.Begin($PSCmdlet)\n}\n\nProcess\n{ \n $out = $steppablePipeline.Process($_) \n\n if(!$out) { \n (get-command $Name).ParameterSets | format-list Name, @{l="Definition"; e={"$_"}} \n } \n}\n\nEnd\n{ $steppablePipeline.End() }\n\n#}
|
PowerShellCorpus/PoshCode/DNS functions_1.ps1
|
DNS functions_1.ps1
|
Param (
[Parameter(Mandatory=$true, Position=1)][string] $SourceServer,
[Parameter(Mandatory=$true, Position=2)][string] $SourceZone,
[Parameter(Mandatory=$true, Position=3)][string] $DestinationServer,
[Parameter(Mandatory=$true, Position=4)][string] $DestinationZone,
[string[]] $RRtypes = @("MicrosoftDNS_AType"),
[switch] $Copy,
[switch] $Clean,
[switch] $Help
)
# script variables
$nl = [Environment]::NewLine
If ($Help){
Write-Host -ForegroundColor Green "
NAME
DNS_Functions
SYNOPSIS
Copies and/or cleans DNS records from one forward zone to another
SYNTAX
.\\DNS_Functions SourceServer SourceZone DestinationServer DestinationZone Switches
EXAMPLES
Forward zone comparison report only:
.\\DNS_Functions $SourceServer $SourceZone $DestinationServer $DestinationZone
Forward source zone clean up for CNAME records:
.\\DNS_Functions.ps1 source_dnsserver source_zone.local destination_dnsserver destination_zone.local -RRtypes `"MicrosoftDNS_AType`",`"MicrosoftDNS_CNAMEType`" -Clean
DESCRIPTION
This script can both copy and clean DNS records by comparing any 2 DNS zones, either same or different FQDN
"
break
}
function GetDNSrecords($DNSserver, $DNSzone, $RRtype){
if ($RRtype -eq $null){$RRtype = "MicrosoftDNS_ResourceRecord"}
$DNSrecords = Get-WMIObject -Computer $DNSserver -Namespace "root\\MicrosoftDNS" -Class $RRtype -Filter "ContainerName='$DNSzone'"
if ($DNSrecords){
Switch ($RRtype){
MicrosoftDNS_AType {
foreach ($rec in $DNSrecords){
# add simple name of dns record as extra property for comparison routine
Add-Member -InputObject $rec -MemberType NoteProperty -Name SimpleVal -Value $rec.OwnerName.Replace(".$DNSzone","")
}
}
MicrosoftDNS_CNAMEType {
foreach ($rec in $DNSrecords){
# add simple name of dns record as extra property for comparison routine
Add-Member -InputObject $rec -MemberType NoteProperty -Name SimpleVal -Value $rec.OwnerName.Replace(".$DNSzone","")
}
}
MicrosoftDNS_ResourceRecord {
# to be implemented
}
}
}
return $DNSrecords
}
function GetDNSrecord ($DNSserver, $DNSzone, $name, $RRtype){
$DnSrecord = Get-WMIObject -Computer $DNSserver -Namespace "root\\MicrosoftDNS" -Class $RRtype -Filter "OwnerName='$name.$DNSzone'"
return $DNSrecord # returns the actual object for further processing
}
function GetDNSzones($DNSserver){
# server side filtering
$DNSzones = Get-WmiObject -ComputerName $DNSserver -Class MicrosoftDNS_Zone -Namespace root\\microsoftDNS -Filter "ZoneType = 1 or ZoneType = 2"
# client side filtering
#$destDNSzone = Get-WmiObject -ComputerName $destServer -Class MicrosoftDNS_Zone -Namespace root\\microsoftDNS | Where {$_.ZoneType -eq '1' -or $_.ZoneType -eq '2'}
return $DNSzones
}
function GetDNSzone ($DNSserver, $name){
$DnSzone = Get-WMIObject -Computer $DNSserver -Namespace "root\\MicrosoftDNS" -Class MicrosoftDNS_Zone -Filter "Name='$name'"
return $DnSzone # returns the actual object for further processing
}
# just for debugging and reference
function DNSrecordInfo($DNSrecord){
$objOutput = New-Object PSObject -Property @{
$class = $DNSrecord.__CLASS # A, CNAME, PTR, etc.
$ownerName = $DNSrecord.OwnerName # Name column in DNS GUI, FQDN
$containerName = $DNSrecord.ContainerName # Zone FQDN
$domainName = $DNSrecord.DomainName # Zone FQDN
$ttl = $DNSrecord.TTL # TTL
$recordClass = $DNSrecord.RecordClass # Usually 1 (IN)
$recordData = $DNSrecord.RecordData # Data column in DNS GUI, value
$simpleval = $ownerName.Replace(".$domainName","")
}
return $objOutput
}
function CopyRecords($DNSrecords){
Write-Output "$($nl)$('Copying') $($DNSrecords.count) $('records to') $($DestinationServer)$($nl)"
$Succ = $Fail = 0
foreach ($DnSrecord in $DNSrecords){
Switch ($DNSrecord.__CLASS) {
MicrosoftDNS_AType {
$destRec = [WmiClass]"\\\\$DestinationServer\\root\\MicrosoftDNS:MicrosoftDNS_AType"
if ($Copy){
if ($DnSrecord.SimpleVal -eq $SourceZone){
# skip (same as parent) A records
Write-Output "$('copy of A:') $($DNSrecord) $('skipped')"
break
}
try{
$newrec = $DNSrecord.SimpleVal + "." + $DestinationZone
$destRec.CreateInstanceFromPropertyData($DestinationServer, $DestinationZone, $newrec, 1, $DNSrecord.TTL, $DNSrecord.RecordData) | out-null
$Succ ++
Write-Output "$('copy of A:') $($newrec) $('on') $($DestinationServer)"
}
catch{
Write-Output "$('copy of A:') $($newrec) $('failed')"
Write-Output "$($error[0])"
$Fail ++
}
}
}
MicrosoftDNS_CNAMEType {
$destRec = [WmiClass]"\\\\$DestinationServer\\root\\MicrosoftDNS:MicrosoftDNS_CNAMEType"
if ($Copy){
try{
$newrec = $DNSrecord.SimpleVal + "." + $DestinationZone
$crec = $DNSrecord.RecordData.Replace(".$SourceZone",".$DestinationZone")
$destRec.CreateInstanceFromPropertyData($DestinationServer, $DestinationZone, $newrec, 1, $DNSrecord.TTL, $crec ) | out-null
$Succ ++
Write-Output "$('copy of CNAME:') $($newrec) $('on') $($DestinationServer)"
}
catch{
Write-Output "$('copy of CNAME') $($newrec) $('failed')"
Write-Output "$($error[0])"
$Fail ++
}
}
}
default{
Write-Output "$('copy of:') $($DNSrecord.SimpleVal) $('failed') $('due to unknown record class')"
$Fail ++
}
}
}
Write-Output "$($nl)$($Succ) $('records copied')"
Write-Output "$($Fail) $('records failed')$($nl)"
}
function ScavengeRecords($DNSrecords){
$Deleted = $Dead = $Live = 0
foreach ($DnSrecord in $DNSrecords){
if (Test-Connection -ComputerName $DNSrecord.OwnerName -count 1 -ea silentlycontinue) {
write-output "$($DNSrecord.SimpleVal) $('is still alive')"
$Live ++
}
else{
write-output "$($DNSrecord.SimpleVal) $('cannot be reached')"
$Dead ++
if ($Clean){
try{
$DNSrecord.delete()
$Deleted ++
}
catch{}
}
}
}
Write-Output "$($nl)$($Deleted) $('records scavenged')"
Write-Output "$($Live) $('records were live')"
Write-Output "$($Dead) $('records were dead')$($nl)"
}
function DedupDNSzone ($srcRecords, $dstRecords){
# return only records from reference (= source zone) found in both DNS zones
$Records2Dedup = compare-object $srcRecords $dstRecords -IncludeEqual -ExcludeDifferent -Property SimpleVal -PassThru
Write-Output "$($nl)$('deleting duplicate records from') $($SourceZone)"
try{
$Records2Dedup | %{ $_.delete() }
Write-Output "$($Records2Dedup.count) $('duplicate records processed')$($nl)"
}
catch{
Write-Output "$('failure deleting record(s)')$($nl)"
}
}
function CleanDNSzone($srcRecords, $dstRecords){
# return unique records in source zone only
$Records2Clean = compare-object $srcRecords $dstRecords -Property SimpleVal -PassThru | Where-Object { $_.SideIndicator -eq '<=' }
ScavengeRecords $Records2Clean
}
function CopyDNSzone ($srcRecords, $dstRecords){
# return unique records in source zone only
$Records2Copy = compare-object $srcRecords $dstRecords -Property SimpleVal -PassThru | Where-Object { $_.SideIndicator -eq '<=' }
CopyRecords $Records2Copy
}
function CompareDNSservers($srcDNSzone ,$destDNSzone){
$dest = $src = $equ = 0
$zones = compare-object $srcDNSzone $destDNSzone -Property name -IncludeEqual
if ($zones -ne $null){
foreach ($zone in $zones){
switch ($zone.SideIndicator){
'=>' {
write-output "$($zone.Name) $('only exists on destination:') $($DestinationServer)"
$dest ++
}
'<=' {
write-output "$($zone.Name) $('only exists on source:') $($SourceServer)"
$src ++
}
'==' {
write-output "$($zone.Name) $('exists on both source and destination')"
$equ ++
}
}
}
write-output "$($nl)$($dest) $('zones on') $($DestinationServer) $('only')"
write-output "$($src) $('zones on') $($SourceServer) $('only')"
write-output "$($equ) $('zones on both source and destination')$($nl)"
}
}
function CompareDNSzone($srcRecords, $dstRecords){
$dest = $src = $equ = 0
$records = compare-object $srcRecords $dstRecords -IncludeEqual -Property SimpleVal
if ($records -ne $null){
foreach ($record in $records){
switch ($record.SideIndicator){
'=>' {
write-output "$($record.SimpleVal) $('exists only in:') $($DestinationZone)"
$dest ++
}
'<=' {
write-output "$($record.SimpleVal) $('exists only in:') $($SourceZone)"
$src ++
}
'==' {
write-output "$($record.SimpleVal) $('exists in both zones')"
$equ ++
}
}
}
write-output "$($nl)$($dest) $('records in') $($DestinationZone) $('on') $($DestinationServer) $('only')"
write-output "$($src) $('records in') $($SourceZone) $('on') $($SourceServer) $('only')"
write-output "$($equ) $('records in both source and destination')$($nl)"
}
}
function GetRecordType($Class){
# return human readable record type :-)
Switch ($Class) {
MicrosoftDNS_AAAAType {return "AAAA"}
MicrosoftDNS_AFSDBType {return "AFSDB"}
MicrosoftDNS_ATMAType {return "ATMA"}
MicrosoftDNS_AType {return "A"}
MicrosoftDNS_CNAMEType {return "Cname"}
MicrosoftDNS_HINFOType {return "H Info"}
MicrosoftDNS_ISDNType {return "ISDN"}
MicrosoftDNS_KEYType {return "Key"}
MicrosoftDNS_MBType {return "MB"}
MicrosoftDNS_MDType {return "MD"}
MicrosoftDNS_MFType {return "MF"}
MicrosoftDNS_MGType {return "MG"}
MicrosoftDNS_MINFOType {return "M Info"}
MicrosoftDNS_MRType {return "MR"}
MicrosoftDNS_MXType {return "MX"}
MicrosoftDNS_NSType {return "NS"}
MicrosoftDNS_NXTType {return "NXT"}
MicrosoftDNS_PTRType {return "PTR"}
MicrosoftDNS_RPType {return "RP"}
MicrosoftDNS_RTType {return "RT"}
MicrosoftDNS_SIGType {return "SIG"}
MicrosoftDNS_SOAType {return "SOA"}
MicrosoftDNS_SRVType {return "SRV"}
MicrosoftDNS_TXTType {return "Text"}
MicrosoftDNS_WINSRType {return "Wins R"}
MicrosoftDNS_WINSType {return "Wins"}
MicrosoftDNS_WKSType {return "WKS"}
MicrosoftDNS_X25Type {return "X25"}
}
}
# actual script execution
write-output "$('Comparison between') $($SourceServer) $('and') $($DestinationServer) $('for all regular DNS zones')$($nl)"
if ($SourceServer -ne $DestinationServer){
# arrays of DNS zones to compare
$srcZones = GetDNSzones $SourceServer
$destZones = GetDNSzones $DestinationServer
# output of DNS zones found on both servers
CompareDNSservers $srcZones $destZones
}
else{write-output "$('Source and Destination server are the same')$($nl)"}
# run thru loop for all DNS record types in script parameter
foreach ($RRtype in $RRtypes){
if (!(GetRecordType $RRtype)){write-warning "$RRtype is not a valid DNS resource type";continue}
write-output "$('Comparison between') $($SourceZone) $('on') $($SourceServer) $('and') $($DestinationZone) $('on') $($DestinationServer) $('for') $(GetRecordType $RRtype) $('records')$($nl)"
# arrays of DNS records to compare
$sourceRecords = (GetDNSrecords $SourceServer $SourceZone $RRtype)
$destinRecords = (GetDNSrecords $DestinationServer $DestinationZone $RRtype)
# check for empty array(s)
if ($sourceRecords -and $destinRecords){
# output of DNS records found in both zones
CompareDNSzone $sourceRecords $destinRecords
# clean duplicate records on the source server
DedupDNSzone $sourceRecords $destinRecords
# copy unique records from source to destination server
CopyDNSzone $sourceRecords $destinRecords
#CleanDNSzone $sourceRecords $destinRecords
}
else{write-output "$('no') $(GetRecordType $RRtype) $('records in either DNS zone')$($nl)"}
}
write-output "$('end script')$($nl)"
|
PowerShellCorpus/PoshCode/Select-CLSCompliant.ps1
|
Select-CLSCompliant.ps1
|
function Select-CLSCompliant {
#.Synopsis
# Outputs the same as "Select-Object *" with basic error handling for properties that are not CLS Compliant
[CmdletBinding()]
param([Parameter(ValueFromPipeline=$true)]$InputObject)
process {
foreach($in in $InputObject) {
$In | Select-Object *
trap [System.Management.Automation.ExtendedTypeSystemException] {
$m = $_.Exception.Message
$matches = [regex]::Matches($m, 'The field/property: \\"(?<field>.*)\\" for type: \\"(?<Type>[^"]+)\\" .* Failed to use non CLS compliant type.')
$type = $matches[0].Groups["Type"].Value -as [Type]
$properties = $type.GetProperties()
$output = @{}
$properties | %{ $Output.($_.Name) = $_.GetValue( $In, $null ) }
new-Object PSObject -Property $Output
continue
}
}
}}
|
PowerShellCorpus/PoshCode/The Old Dogs ExcelCookBo_1.ps1
|
The Old Dogs ExcelCookBo_1.ps1
|
#
# DATE : 6/21/2010
# COMMENT: This is an updated Version of my Cook Book from Augest of 2008
#
#
#===============================================================
# All errors and mistakes are my own. Thanks to all who have helped
# along the way.
#
# One thing I would add is that if you are using anything but a US locale version of Excel some of
# these scripts won't work, especially adding and saving workbooks.
#
# Here is a function that helps with this problem:
#
# From: http://blogs.msdn.com/powershell/archive/2006/04/25/583235.aspx
#
# ======================================================
Function Using-Culture (
[System.Globalization.CultureInfo]$culture,
[ScriptBlock]$script)
{
$OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
trap
{
[System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}
[System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
$ExecutionContext.InvokeCommand.InvokeScript($script)
[System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
} # End Function
Using-Culture en-us {
$xl= New-Object -COM Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$xl.Workbooks.Open("C:\\Scripts\\PowerShell\\test.xls")
#$xl.Quit()
#[System.Runtime.InteropServices.Marshal]::ReleaseComObject($xl)
}
# ======================================================
#_______________________________________________________________________
# How do I create an Excel object?
$xl = new-object -comobject excel.application
# ________________________________________________________________________
#How do I make Excel visible?
$xl.Visible = $true
# ________________________________________________________________________
#
# How do I add a workbook?
$wb = $xl.Workbooks.Add()
# By default this adds three empty worksheets
# ________________________________________________________________________
#
#
# How do I open an existing Workbook ?
#
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\\Scripts\\powershell\\test.xls")
# ________________________________________________________________________
#
#
#How do I add a worksheet to an existing workbook?
$xl = new-object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\\Scripts\\test.xls")
$ws = $xl.Sheets.Add()
#
# ________________________________________________________________________
#
# How do I activate a a worksheet?
# Create Excel.Application object
$xl = New-Object -comobject Excel.Application
# Show Excel
$xl.visible = $true
$xl.DisplayAlerts = $False
# Open a workbook
$wb = $xl.workbooks.open("C:\\Scripts\\PowerShell\\test.xls")
# Get sheets
$ws1 = $wb.worksheets | where {$_.name -eq "sheet1"} #<------- Selects sheet 1
$ws2 = $wb.worksheets | where {$_.name -eq "sheet2"} #<------- Selects sheet 2
$ws3 = $wb.worksheets | where {$_.name -eq "sheet3"} #<------- Selects sheet 3
# Activate sheet 1
$ws1.activate()
Start-Sleep 1
# Activate sheet 2
$ws2.activate()
Start-Sleep 1
# Activate sheet 3
$ws3.activate()
# _________________________________________________________________
# How do I change the value of a cell?
$ws1.cells.Item(1,1).Value() = "x"
# ________________________________________________________________________
#
# How do I Find a specified cell?
#
$xlCellTypeLastCell = 11
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$row = $lastCell.row
for ($i = 1; $i -le $row; $i++) {
If ($ws1.cells.Item(1,2).Value() = "y") {
# "do something"
}
}
# And another way:
#
$mainRng = $ws.usedRange
$mainRng.Select()
$objSearch = $mainRng.Find("Grand Total")
$objSearch.Select()
# ________________________________________________________________________
#
# How do I find and delete empty rows in Excel?
#
Function DeleteEmptyRows {
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$row = $lastCell.row
for ($i = 1; $i -le $row; $i++) {
If ($ws.Cells.Item($i, 1).Value() -eq $Null) {
$Range = $ws.Cells.Item($i, 1).EntireRow
$Range.Delete()
}
}
}
$xlCellTypeLastCell = 11
$xl = New-Object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\\Scripts\\Test.xls") # <-- Change as required!
$ws = $wb.worksheets | where {$_.name -eq "Servers" } # <-- Or Sheet1 or Whatever
DeleteEmptyRows # <—Call Function
# ________________________________________________________________________
#
#
# How do I set a range with variables?
$ws1.range("a${Sumrow}:b$Sumrow").font.bold = "true"
# separate the : from the $ with {} on the left hand side
# ________________________________________________________________________
#
# How do I Set range to a value?
$range4=$ws.range("3:3")
$range4.cells="Row 3"
# ________________________________________________________________________
#
# How do I list the workbook's name?
$wb.Name
# ______________________________________________________________
#
# How do I find the last used row number?
$xlCellTypeLastCell = 11
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$lastrow = $lastCell.row
# Or
$mainRng = $ws1.UsedRange.Cells
$RowCount = $mainRng.Rows.Count
$R = $RowCount
# ________________________________________________________________________
#
# How do I find the last used column number?
#This works for columns and rows
$mainRng = $ws1.UsedRange.Cells
$ColCount = $mainRng.Columns.Count
$RowCount = $mainRng.Rows.Count
$xRow = $RowCount
$xCol = $ColCount
# ________________________________________________________________________
#
# How do I loop through a range of cells by row number?
$xl = New-Object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
for ($row = 1; $row -lt 11; $row++)
{
$ws.Cells.Item($row,1) = $row
}
# ________________________________________________________________________
#
# How do I get today's date and format it as a string?
$m = (get-date).month
$d = (get-date).day
$y = [string] (get-date).year
$y = $y.substring($y.length - 2, 2)
$f = "C:\\Scripts\\" + $m + "-" + $d + "-" + $y + ".xlsx"
$wb.SaveAs($F) # C:\\Scripts\\6-18-10.xlsx
#
# ________________________________________________________________________
#
# How do I write a list of files to Excel?
$xl = new-object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$row = 1
$s = dir Z:\\MBSA_Report\\ScanData\\*.mbsa
$s | foreach -process {
$ws.Cells.Item($row,1) = $_;
$row++
}
#
# this takes a long file name with spaces and splits it up,
# It then picks out the 3rd element and writes it out.
# The 3rd element is [2] because the first one is [0].
# sample file name: AD-Dom - 3IDCT001 (5-21-2010 4-28 PM).mbsa
$xl = new-object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$row = 1
dir Z:\\MBSA_Report\\ScanData\\*.mbsa |
ForEach-Object {
$FileName = $_.name
$N = $FileName.tostring()
$E = $N.split()
$F = $E[2]
$ws.Cells.Item($row,1) = $F;
$row++
}
#Or for the whole file name
$ws.Cells.Item($row,1) = $_;
# ________________________________________________________________________
#
# How do I write a list of processes to Excel?
function Release-Ref ($ref) {
#[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($ref)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
# -----------------------------------------------------
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$range = $ws.Cells.Item(1,1)
$row = 1
$s = Get-Process | Select-Object name
$s | foreach -process {
$range = $ws.Cells.Item($row,1);
$range.Value = $_.Name;
$row++ }
$wb.SaveAs("C:\\Scripts\\Get_Process.xls")
Release-Ref $range
Release-Ref $ws
Release-Ref $wb
$xl.Quit()
Release-Ref $xl
#***For a remote machine try
$strComputer = (remote machine name)
$P = gwmi win32_process -comp $strComputer
# ________________________________________________________________________
#
# How do I write the command history to Excel?
function Release-Ref ($ref) {
#[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($ref)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $excel.Workbooks.Add()
$ws = $workbook.Worksheets.Item(1)
$range = $worksheet.Cells.Item(1,1)
$row = 1
$s = Get-History | Select-Object CommandLine $s | foreach -process { `
$range = $worksheet.Cells.Item($row,1); `
$range.Value = $_.CommandLine; `
$row++ }
$xl.DisplayAlerts = $False
$wb.SaveAs("C:\\Scripts\\Get_CommandLine.xls")
Release-Ref $range
Release-Ref $ws
Release-Ref $wb
$xl.Quit()
Release-Ref $xl
# ________________________________________________________________________
#
# How Can I Convert a Tilde-Delimited File to Microsoft Excel Format?
# Script name: ConvertTilde.ps1
# Created on: 2007-01-06
# Author: Kent Finkle
# Purpose: How Can I Convert a Tilde-Delimited File to Microsoft Excel Format?
$s = gc C:\\Scripts\\Test.txt
$s = $s -replace("~","`t")
$s | sc C:\\Scripts\\Test.txt
$xl = new-object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\\Scripts\\Test.txt")
# ________________________________________________________________________
#
# How can I add Validation to an Excel Worksheet?
#
# $comments = @'
# Script name: Add-Validation.ps1
# Created on: Wednesday, September 19, 2007
# Author: Kent Finkle
# Purpose: How can I use Windows Powershell to Add Validation to an
# Excel Worksheet?
# '@
#-----------------------------------------------------
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
} # End Function
$xlValidateWholeNumber = 1
$xlValidAlertStop = 1
$xlBetween = 1
$xl = new-object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$r = $ws.Range("e5")
$r.Validation.Add($xlValidateWholeNumber,$xlValidAlertStop, $xlBetween, "5", "10")
$r.Validation.InputTitle = "Integers"
$r.Validation.ErrorTitle = "Integers"
$r.Validation.InputMessage = "Enter an integer from five to ten"
$r.Validation.ErrorMessage = "You must enter a number from five to ten"
$a = Release-Ref $r
$a = Release-Ref $ws
$a = Release-Ref $wb
$a = Release-Ref $xl
# ________________________________________________________________________
#
# How do I add a Chart to an Excel Worksheet?
$xrow = 1
$yrow = 8
$xl = New-Object -c excel.application
$xl.visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.workbooks.add()
$ws = $wb.sheets.item(1)
1..8 | % { $ws.Cells.Item(1,$_) = $_ }
1..8 | % { $ws.Cells.Item(2,$_) = 9-$_ }
$range = $ws.range("a${xrow}:h$yrow")
$range.activate
# create and assign the chart to a variable
$ch = $xl.charts.add() # This will open a new sheet
$ch = $ws.shapes.addChart().chart # This will put the Chart in the selected WorkSheet
$ch.chartType = 58
$ch.setSourceData($range)
$ch.export("C:\\test.jpg")
$xl.quit()
# excel has 48 chart styles, you can cycle through all
1..48 | % {$ch.chartStyle = $_; $xl.speech.speak("Style $_"); sleep 1}
$ch.chartStyle = 27 # <-- use the one you like
# And another Chart sample:
Function XLcharts {
$xlColumnClustered = 51
$xlColumns = 2
$xlLocationAsObject = 2
$xlCategory = 1
$xlPrimary = 1
$xlValue = 2
$xlRows = 1
$xlLocationAsNewSheet = 1
$xlRight = -4152
$xlBuiltIn =21
$xlCategory = 1
$xl = New-Object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws = $wb.Sheets.Add()
$ws.Cells.Item(1, 2) = "Jan"
$ws.Cells.Item(1, 3) = "Feb"
$ws.Cells.Item(1, 4) = "Mar"
$ws.Cells.Item(2, 1) = "John"
$ws.Cells.Item(3, 1) = "Mae"
$ws.Cells.Item(4, 1) = "Al"
$ws.Cells.Item(2, 2) = 100
$ws.Cells.Item(2, 3) = 200
$ws.Cells.Item(2, 4) = 300
$ws.Cells.Item(3, 2) = 400
$ws.Cells.Item(3, 3) = 500
$ws.Cells.Item(3, 4) = 600
$ws.Cells.Item(4, 2) = 900
$ws.Cells.Item(4, 3) = 800
$ws.Cells.Item(4, 4) = 700
$Range = $ws.range("A1:D4")
$ch = $xl.charts.add()
$ch.chartType = 58
$ch.name ="Bar Chart"
$ch.Tab.ColorIndex = 3
$ch.setSourceData($Range)
[void]$ch.Location, $xlLocationAsObject, "Bar Chart"
$ch.HasTitle = $False
$ch.Axes($xlCategory, $xlPrimary).HasTitle = $False
$ch.Axes($xlValue, $xlPrimary).HasTitle = $False
$ch2 = $xl.Charts.Add() | Out-Null
$ch2.HasTitle = $true
$ch2.ChartTitle.Text = "Sales"
$ch2.Axes($xlCategory).HasTitle = $true
$ch2.Axes($xlCategory).AxisTitle.Text = "1st Quarter"
$ch2.Axes($xlValue).HasTitle = $True
$ch2.Axes($xlValue).AxisTitle.Text = "Dollars"
[void]$ch2.Axes($xlValue).Select
$ch2.name ="Columns with Depth"
$ch2.Tab.ColorIndex = 5
[void]$ws.cells.entireColumn.Autofit()
} # End Function
# ________________________________________________________________________
#
# How do I Move and resize a chart in an Excel Worksheet?
$xl = New-Object -comobject Excel.Application # Opens Excel and 3 empty Worksheets
# Show Excel
$xl.visible = $true
$xl.DisplayAlerts = $False
# Open a workbook
$wb = $xl.workbooks.add()
#Create Worksheets
$ws = $wb.Worksheets.Item(1)
1..8 | % { $ws.Cells.Item(1,$_) = $_ } # adds some data
1..8 | % { $ws.Cells.Item(2,$_) = 9-$_ } # adds some data
# < ----- This is the good part ------------------------------------------------------->
$range = $ws.range("a${xrow}:h$yrow") # sets the Data range we want to chart
# create and assign the chart to a variable
#$ch = $xl.charts.add() # This will open a new sheet
$ch = $ws.shapes.addChart().chart # This will put the Chart in the selected WorkSheet
$ch.chartType = 58 # Select Chart Type
$ch.setSourceData($range) # Create the Chart
$RngToCover = $ws.Range("D5:J19") # This is where we want the chart
$ChtOb = $ch.Parent # This selects the curent Chart
$ChtOb.Top = $RngToCover.Top # This moves it up to row 5
$ChtOb.Left = $RngToCover.Left # and to column D
$ChtOb.Height = $RngToCover.Height # resize This sets the height of your chart to Rows 5 - 19
$ChtOb.Width = $RngToCover.Width # resize This sets the width to Columns D - J
# ________________________________________________________________________
#
# How do I sort a column in an Excel Worksheet?
$xlSummaryAbove = 0
$xlSortValues = $xlPinYin = 1
$xlAscending = 1
$xlDescending = 2
$xlYes = 1
$xl = New-Object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
# one-column sort
$r = $ws.UsedRange
$r2 = $ws.Range("B2") # Sorts on Column B and leaves Header alone
$a = $r.sort($r2, $xlAscending)
# two-column sort
$r = $ws.UsedRange
$r2 = $ws.Range("B2")
$r3 = $ws.Range("E2")
$a = $r.sort($r2, $xlAscending, $r3,$null, $xlAscending)
# three-column sort
$r = $ws1.UsedRange
$r2 = $ws1.Range("B2")
$r3 = $ws1.Range("E2")
$r4 = $ws1.Range("C2")
$a = $r.Sort($r2,$xlDescending,$r3,$null,$xlAscending, `
$r4,$xlAscending,$xlYes)
#-----------------------------------------------------
# How do I use xlConstants?
$xlAutomatic=-4105
$xlBottom = -4107
$xlCenter = -4108
$xlContext = -5002
$xlContinuous=1
$xlDiagonalDown=5
$xlDiagonalUp=6
$xlEdgeBottom=9
$xlEdgeLeft=7
$xlEdgeRight=10
$xlEdgeTop=8
$xlInsideHorizontal=12
$xlInsideVertical=11
$xlNone=-4142
$xlThin=2
$xl = new-object -com excel.application
$xl.visible=$true
$wb = $xl.workbooks.open("d:\\book1.xls")
$ws = $wb.worksheets | where {$_.name -eq "sheet1"}
$selection = $ws.range("A1:D1")
$selection.select()
$selection.HorizontalAlignment = $xlCenter
$selection.VerticalAlignment = $xlBottom
$selection.WrapText = $false
$selection.Orientation = 0
$selection.AddIndent = $false
$selection.IndentLevel = 0
$selection.ShrinkToFit = $false
$selection.ReadingOrder = $xlContext
$selection.MergeCells = $false
$selection.Borders.Item($xlInsideHorizontal).Weight = $xlThin
## You can also try this to center a column:
[reflection.assembly]::loadWithPartialname("Microsoft.Office.Interop.Excel") |
Out-Null
$xlConstants = "microsoft.office.interop.excel.Constants" -as [type]
$ws.columns.item("F").HorizontalAlignment = $xlConstants::xlCenter
$ws.columns.item("K").HorizontalAlignment = $xlConstants::xlCenter
# The next four lines of code create four enumeration types.
# Enumeration types are used to tell Excel which values are allowed
# for specific types of options. As an example, xlLineStyle enumeration
# is used to determine the kind of line to draw: double, dashed, and so on.
# These enumeration values are documented on MSDN.
# To make the code easier to read, we create shortcut aliases for each
# of the four enumeration types we will be using.
# Essentially, we're casting a string that represents the name of the
# enumeration to a [type]. This technique is actually a pretty cool trick:
# http://technet.microsoft.com/en-us/magazine/2009.01.heyscriptingguy.aspx
$lineStyle = "microsoft.office.interop.excel.xlLineStyle" -as [type]
$colorIndex = "microsoft.office.interop.excel.xlColorIndex" -as [type]
$borderWeight = "microsoft.office.interop.excel.xlBorderWeight" -as [type]
$chartType = "microsoft.office.interop.excel.xlChartType" -as [type]
For($b = 1 ; $b -le 2 ; $b++)
{
$ws.cells.item(1,$b).font.bold = $true
$ws.cells.item(1,$b).borders.LineStyle = $lineStyle::xlDashDot
$ws.cells.item(1,$b).borders.ColorIndex = $colorIndex::xlColorIndexAutomatic
$ws.cells.item(1,$b).borders.weight = $borderWeight::xlMedium
}
$workbook.ActiveChart.chartType = $chartType::xl3DPieExploded
$workbook.ActiveChart.SetSourceData($range)
# ________________________________________________________________________
#
# How do I use autofill in excel?
$xlFillWeekdays = 6
$xl = New-Object -com excel.application
$xl.visible=$true
$wb = $xl.workbooks.add()
$ws = $wb.worksheets | where {$_.name -eq "sheet1"}
$range1= $ws.range("A1")
$range1.value() = (get-date).toString("d")
$range2 = $ws.range("A1:A25")
$range1.AutoFill($range2,$xlFillWeekdays)
$range1.entireColumn.Autofit()
# Another example:
$xlCellTypeLastCell = 11
$xl = new-object -com excel.application
$xl.visible=$true
$wb = $xl.workbooks.add()
$ws = $wb.worksheets | where {$_.name -eq "sheet1"}
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$lastrow = $lastCell.row
$ws.Cells.Item(2,1).FormulaR1C1 = "=CONCATENATE(C[+1],C[+2],C[+3])"
$range1= $ws.range("A2")
$r = $ws.Range("A2:A$lastrow")
$range1.AutoFill($r) | Out-Null
[void]$range1.entireColumn.Autofit()
$wb.close()
$xl.quit()
# ________________________________________________________________________
#
# How to get a range and format it in excel?
# get-excelrange.ps1
# opens an existing workbook in Excel 2007, using PowerShell
# and turns a range bold # Thomas Lee - t...@psp.co.uk
# Create base object
$xl = new-object -comobject Excel.Application
# make Excel visible
$xl.visible = $true
$xl.DisplayAlerts = $False
# open a workbook
$wb = $xl.workbooks.open("C:\\Scripts\\powershell\\test.xls")
# Get sheet1
$ws = $wb.worksheets | where {$_.name -eq "sheet1"}
# Make A1-B1 bold
$range = $ws.range("A1:B1")
$range.font.bold = "true"
# Make A2-B2 italic
$range2 = $ws.range("A2:B2")
$range2.font.italic = "true"
# Set range to a value
$range4=$ws.range("3:3")
$range4.cells="Row 3"
# Set range to a Font size
$range3=$ws.range("A2:B2")
$Range3.font.size=24
# now format an entire row
$range4=$ws.range("3:3")
$range4.font.italic="$true"
$range4.font.bold=$true
$range4.font.size=10
$range4.font.name="Comic Sans MS"
# now format a Range of cells
$ws.Range("D1:F5").NumberFormat = "#,##0.00"
# ______________________________________________________________________
#
# How do I add a comment to a cell in Excel?
$xl = New-Object -com Excel.Application
$xl.visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.Cells.Item(1,1) = “A value in cell A1.”
[void]$ws.Range("A1").AddComment()
[void]$ws.Range("A1").comment.Visible = $False
[void]$ws.Range("A1").Comment.text("OldDog: `r this is a comment")
[void]$ws.Range("A2").Select
# The 'r adds a line feed after the comment's author. This is required!
# ________________________________________________________________________
#
# How do I copy and Paste in Excel (special)?
$xl = New-Object -comobject Excel.Application
# Show Excel
$xl.visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$xlPasteValues = -4163 # Values only, not formulas
$xlCellTypeLastCell = 11 # to find last used cell
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$row = $lastCell.row
$range = $ws.UsedRange
[void]$ws.Range("A8:F$row").Copy()
[void]$ws.Range("A8").PasteSpecial(-4163)
# __________________________________________________________________________
#
# How do I Add Worksheets, name them and save as today's date?
#******************************************
# get today's date and format it as a string.
$m = (get-date).month
$d = (get-date).day
$y = [string] (get-date).year
$y = $y.substring($y.length - 2, 2)
$f = "C:\\Scripts\\" + $m + "-" + $d + "-" + $y + ".xlsx"
# Create Excel.Application object
$xl = New-Object -comobject Excel.Application
# Show Excel
$xl.visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
# this will add 9 sheets to the default 3 for a total of 12 sheets
for ($i = 0; $i -le 8; $i++) {
$ws = $wb.Sheets.Add() }
# Now we name our new sheets
$xl.Worksheets.item(1).name = "Jan"
$xl.Worksheets.item(2).name = "Feb"
$xl.Worksheets.item(3).name = "Mar"
$xl.Worksheets.item(4).name = "Apr"
$xl.Worksheets.item(5).name = "May"
$xl.Worksheets.item(6).name = "June"
$xl.Worksheets.item(7).name = "July"
$xl.Worksheets.item(8).name = "Aug"
$xl.Worksheets.item(9).name = "Sept"
$xl.Worksheets.item(10).name = "Oct"
$xl.Worksheets.item(11).name = "Nov"
$xl.Worksheets.item(12).name = "Dec"
# and here we save it
$wb.SaveAs($F)
#*******************************************
# How do I find duplicate entries in Excel?
# This Function creates a spreadsheet with some
# duplicate names and then highlights the Dups in Blue
Function XLFindDups {
$xlExpression = 2
$xlPasteFormats = -4122
$xlNone = -4142
$xlToRight = -4161
$xlToLeft = -4159
$xlDown = -4121
$xlShiftToRight = -4161
$xlFillDefault = 0
$xlSummaryAbove = 0
$xlSortValues = $xlPinYin = 1
$xlAscending = 1
$xlDescending = 2
$xlYes = 1
$xlTopToBottom = 1
$xlPasteValues = -4163 # Values only, not formulas
$xlCellTypeLastCell = 11 # to find last used cell
$xl = new-object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.name = "Concatenate"
$ws.Tab.ColorIndex = 4
$ws.Cells.Item(1,1) = "FirstName"
$ws.Cells.Item(1,2) = "MI"
$ws.Cells.Item(1,3) = "LastName"
$ws.Cells.Item(2,1) = "Jesse"
$ws.Cells.Item(2,2) = "L"
$ws.Cells.Item(2,3) = "Roberts"
$ws.Cells.Item(3,1) = "Mary"
$ws.Cells.Item(3,2) = "S"
$ws.Cells.Item(3,3) = "Talbert"
$ws.Cells.Item(4,1) = "Ben"
$ws.Cells.Item(4,2) = "N"
$ws.Cells.Item(4,3) = "Smith"
$ws.Cells.Item(5,1) = "Ed"
$ws.Cells.Item(5,2) = "S"
$ws.Cells.Item(5,3) = "Turner"
$ws.Cells.Item(6,1) = "Mary"
$ws.Cells.Item(6,2) = "S"
$ws.Cells.Item(6,3) = "Talbert"
$ws.Cells.Item(7,1) = "Jesse"
$ws.Cells.Item(7,2) = "L"
$ws.Cells.Item(7,3) = "Roberts"
$ws.Cells.Item(8,1) = "Joe"
$ws.Cells.Item(8,2) = "L"
$ws.Cells.Item(8,3) = "Smith"
$ws.Cells.Item(9,1) = "Ben"
$ws.Cells.Item(9,2) = "A"
$ws.Cells.Item(9,3) = "Smith"
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$lastrow = $lastCell.row
$range4=$ws.range("2:2")
$range4.Select() | Out-Null
$xl.ActiveWindow.FreezePanes = $true
$ws.cells.EntireColumn.AutoFit() | Out-Null
$range1 = $ws.Range("A1").EntireColumn
$range1.Insert($xlShiftToRight) | Out-Null
$range1.Select() | Out-Null
$ws.Cells.Item(1, 1) = "Concat"
$r2 = $ws.Range("A2")
$r2.Select() | Out-Null
$ws.Cells.Item(2,1).FormulaR1C1 = "=CONCATENATE(C[+1],C[+2],C[+3])"
$range1= $ws.range("A2")
$r = $ws.Range("A2:A$lastrow")
$range1.AutoFill($r) | Out-Null
$range.EntireColumn.AutoFit() | Out-Null
$select = $range1.SpecialCells(11).Select() | Out-Null
$ws.Range("A2:A$lastrow").Copy()| Out-Null
$ws1 = $wb.Sheets.Add()
$ws1.name = "FindDups"
$ws1 = $wb.worksheets | where {$_.name -eq "FindDups"}
$ws1.Tab.ColorIndex = 5
$ws1.Select() | Out-Null
[void]$ws1.Range("A2").PasteSpecial(-4163)
$ws1.Range("A1").Select() | Out-Null
$objRange = $xl.Range("B1").EntireColumn
[void] $objRange.Insert($xlShiftToRight)
$ws1.Cells.Item(1, 2) = "Dups"
$range = $ws.range("B1:D$lastrow")
$range.copy() | Out-Null
[void]$ws1.Range("C1").PasteSpecial(-4163)
$ws1.Cells.Item(2,2).FormulaR1C1 = "=COUNTIF(C[-1],RC[-1])>1"
$range1= $ws1.range("B2")
$range2 = $ws1.range("B2:B$lastrow")
[void]$range1.AutoFill($range2,$xlFillDefault)
# Thnaks to Wolfgang Kais for the following:
$xl.Range("B2").Select() | Out-Null
$xl.Selection.FormatConditions.Delete()
$xl.Selection.FormatConditions.Add(2, 0, "=COUNTIF(A:A,A2)>1") | Out-Null
$xl.Selection.FormatConditions.Item(1).Interior.ColorIndex = 8
$xl.Selection.Copy() | Out-Null
$xl.Columns.Item("B:B").Select() | Out-Null
$xl.Range("B2").Activate() | Out-Null
$xl.Selection.PasteSpecial(-4122, -4142, $false, $false) | Out-Null
$r = $ws1.UsedRange
$r2 = $ws1.Range("B2")
$r3 = $ws1.Range("E2")
$r4 = $ws1.Range("C2")
$a = $r.Sort($r2,$xlDescending,$r3,$null,$xlAscending, `
$r4,$xlAscending,$xlYes)
$ws1.Application.ActiveWindow.FreezePanes=$true
[void]$ws1.cells.entireColumn.Autofit()
$s = $xl.Range("A1").EntireColumn
$s.Hidden = $true
$ws1.Range("B2").Select() | Out-Null
}
# ==============================================================================================
# How do I show all 57 Colors in Excel?
$xl = new-object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$row = 1
$i = 1
For($i = 1; $i -lt 57; $i++){
$ws.Cells.Item($row, 1) = "'$'ws.Cells.Item($row, 2).Font.ColorIndex = " + $row
$ws.Cells.Item($row, 2).Font.ColorIndex = $row
$ws.Cells.Item($row, 2) = "test " + $row
$row++
}
[void]$ws.cells.entireColumn.Autofit()
# ==============================================================================================
# How do I insert a Hyperlink into an Excel Spreadsheet?
function Release-Ref ($info) {
foreach ( $p in $args ) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$p) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
} # End Function
Function XLHyperlinks {
$link = "http://www.microsoft.com/technet/scriptcenter"
$xl = new-object -comobject excel.application
$xl.Visible = $true
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.Cells.Item(1, 1).Value() = "Script Center"
$r = $ws.Range("A1")
$objLink = $ws.Hyperlinks.Add($r, $link)
$a = Release-Ref $r $ws $wb $xl
} # End Function
# ________________________________________________________________________
#
# How do I sum a column in Excel?
#
Function xlSum {
$range = $ws1.usedRange
$row = $range.rows.count # Takes you to the last used row
$Sumrow = $row + 1
$r = $ws1.Range("A2:A$row") # select the column to Add up
$functions = $xl.WorkSheetfunction
$ws.cells.item($Sumrow,1) = $functions.sum($r) # this uses the Excel sum function
$rangeString = $r.address().tostring() -replace "\\$",'' # convert formula to Text
$ws.cells.item($Sumrow,2) = "Sum $rangeString" # Print formula in Cell B & last row + 1
$ws1.cells.item($Sumrow,1).Select()
$ws1.range("a${Sumrow}:b$Sumrow").font.bold = "true" # seperate the : from the $ with {}
$ws1.range("a${Sumrow}:b$Sumrow").font.size=12 # Changes the font size to 12 points
[void]$range.entireColumn.Autofit()
} # End Function
# ________________________________________________________________________
#
# How do I SubTotal a column in an Excel Worksheet?
#
#
# Sample Spreadsheet
# mon tue wed
# eggs 1 1 1
# ham 5 5 5
# spam 1 4 7
# spam 2 5 8
# spam 3 6 9
#
# Code to sub total
$xlSum = -4157
$range = $xl.range("A1:D6")
$range.Subtotal(1,-4157,(2,3,4),$true,$False,$true)
# Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(4), _
# Replace:=True, PageBreaks:=False, SummaryBelowData:=True
# ________________________________________________________________________
#
# In this example Subtotals are sums grouped by each change in field 1 "Salesperson"
# with Subtotals of field 2 "Amount".
# Details of Subtotal function
# SubTotal GroupBy =2, Function =XLSum, TotalList =Array(1),
# Replace =False, PageBreaks =False, SummaryBelowData =$True
Function XLSubtotals {
$xlExpression = 2
$xlPasteFormats = -4122
$xlNone = -4142
$xlToRight = -4161
$xlToLeft = -4159
$xlDown = -4121
$xlShiftToRight = -4161
$xlFillDefault = 0
$xlSummaryAbove = 0
$xlSortValues = $xlPinYin = 1
$xlAscending = 1
$xlDescending = 2
$xlYes = 1
$xlTopToBottom = 1
$xlPasteValues = -4163 # Values only, not formulas
$xlCellTypeLastCell = 11 # to find last used cell
$xlSum = -4157
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws = $wb.Sheets.Add()
$xl.Worksheets.item(1).name = "Detail"
$xl.Worksheets.item(2).name = "ShowLevels1"
$xl.Worksheets.item(3).name = "ShowLevels2"
$xl.Worksheets.item(4).name = "ShowLevels3"
$ws1 = $wb.worksheets | where {$_.name -eq "Detail"}
$ws2 = $wb.worksheets | where {$_.name -eq "ShowLevels1"} #<------- Selects sheet 6
$ws3 = $wb.worksheets | where {$_.name -eq "ShowLevels2"} #<------- Selects sheet 5
$ws4 = $wb.worksheets | where {$_.name -eq "ShowLevels3"} #<------- Selects sheet 4
$ws1.Tab.ColorIndex = 8
$ws1.Tab.ColorIndex = 5
$ws2.Tab.ColorIndex = 6
$ws3.Tab.ColorIndex = 7
$ws1.Cells.Item(1,2) = "Amount"
$ws1.Cells.Item(1,1) = "SalesPerson"
$ws1.Cells.Item(2,2) = 7324
$ws1.Cells.Item(2,1) = "Jack"
$ws1.Cells.Item(3,2) = 294
$ws1.Cells.Item(3,1) = "Elizabeth"
$ws1.Cells.Item(4,2) = 41472
$ws1.Cells.Item(4,1) = "Renee"
$ws1.Cells.Item(5,2) = 25406
$ws1.Cells.Item(5,1) = "Elizabeth"
$ws1.Cells.Item(6,2) = 20480
$ws1.Cells.Item(6,1) = "Jack"
$ws1.Cells.Item(7,2) = 11294
$ws1.Cells.Item(7,1)= "Renee"
$ws1.Cells.Item(8,2) = 982040
$ws1.Cells.Item(8,1) = "Elizabeth"
$ws1.Cells.Item(9,2) = 2622368
$ws1.Cells.Item(9,1) = "Jack"
$ws1.Cells.Item(10,2) = 884144
$ws1.Cells.Item(10,1) = "Renee"
$ws1.Range("B2").Select() | Out-Null
$ws1.Application.ActiveWindow.FreezePanes=$true
[void]$ws1.cells.entireColumn.Autofit()
$ws1.Range("A1").Select() | Out-Null
$r = $ws.Range("A2:A10")
$r2 = $ws.Range("A2") # Sorts on Column B and leaves Header alone
$a = $r.sort($r2, $xlAscending)
$range1 = $ws1.Range("A1:B1").EntireColumn
$Range1.Select() | Out-Null
#$ws.Range.SpecialCells(11)).Select()
$Range1.Copy()
$ws1.Range("A1").Select() | Out-Null
$ws2.Select() | Out-Null
[void]$ws2.Range("A1").PasteSpecial(-4163)
$ws3.Select() | Out-Null
[void]$ws3.Range("A1").PasteSpecial(-4163)
$ws4.Select() | Out-Null
[void]$ws4.Range("A1").PasteSpecial(-4163)
$ws2.Select() | Out-Null
$range = $xl.range("A1:B10")
$range.Subtotal(1,-4157,(2),$true,$False,$true)
$ws2.Outline.ShowLevels(1)
[void]$ws1.cells.entireColumn.Autofit()
$ws2.Range("A1").Select() | Out-Null
$ws3.Select() | Out-Null
$range = $xl.range("A1:B10")
$range.Subtotal(1,-4157,(2),$true,$False,$true)
$ws3.Outline.ShowLevels(2)
[void]$ws1.cells.entireColumn.Autofit()
$ws3.Range("A1").Select() | Out-Null
$ws4.Select() | Out-Null
$range = $xl.range("A1:B10")
$range.Subtotal(1,-4157,(2),$true,$False,$true)
$ws4.Outline.ShowLevels(3)
$ws1.Select() | Out-Null
[void]$ws1.cells.entireColumn.Autofit()
$ws1.Range("A1").Select() | Out-Null
} # End Function
#---------------------------------------------------
#
#How do I set up Auto Filters in Excel?
#This function sets up a spreadsheet and then sets Auto filters
Function XLAutoFilter {
$xlTop10Items = 3
$xlTop10Percent = 5
$xlBottom10Percent = 6
$xlBottom10Items = 4
$xlAnd = 1
$xlOr = 2
$xlNormal = -4143
$xlPasteValues = -4163 # Values only, not formulas
$xlCellTypeLastCell = 11 # to find last used cell
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws = $wb.Sheets.Add()
$ws = $wb.Sheets.Add()
$ws1 = $wb.worksheets | where {$_.name -eq "Sheet1"} #<------- Selects sheet 1
$ws2 = $wb.worksheets | where {$_.name -eq "Sheet2"} #<------- Selects sheet 2
$ws3 = $wb.worksheets | where {$_.name -eq "Sheet3"} #<------- Selects sheet 3
$ws4 = $wb.worksheets | where {$_.name -eq "Sheet4"} #<------- Selects sheet 4
$ws5 = $wb.worksheets | where {$_.name -eq "Sheet5"} #<------- Selects sheet 5
$ws1.Tab.ColorIndex = 8
$ws2.Tab.ColorIndex = 7
$ws3.Tab.ColorIndex = 6
$ws4.Tab.ColorIndex = 5
$ws5.Tab.ColorIndex = 4
$ws1.name = "Detail"
$ws2.name = "JackOnly"
$ws3.name = "Top2"
$ws4.name = "LowestHighest"
$ws5.name = "Top25Percent"
$ws1.cells.Item(1,1) = "Amount"
$ws1.cells.Item(1,2) = "SalesPerson"
$ws1.cells.Item(2,1) = 1
$ws1.cells.Item(2,2) = "Jack"
$ws1.cells.Item(3,1) = 2
$ws1.cells.Item(3,2) = "Elizabeth"
$ws1.cells.Item(4,1) = 3
$ws1.cells.Item(4,2) = "Renee"
$ws1.cells.Item(5,1) = 4
$ws1.cells.Item(5,2) = "Elizabeth"
$ws1.cells.Item(6,1) = 5
$ws1.cells.Item(6,2) = "Jack"
$ws1.cells.Item(7,1) = 6
$ws1.cells.Item(7,2) = "Renee"
$ws1.cells.Item(8,1) = 7
$ws1.cells.Item(8,2) = "Elizabeth"
$ws1.cells.Item(9,1) = 8
$ws1.cells.Item(9,2) = "Jack"
$ws1.cells.Item(10,1) = 9
$ws1.cells.Item(10,2) = "Renee"
$ws1.cells.Item(11,1) = 10
$ws1.cells.Item(11,2) = "Jack"
$ws1.cells.Item(12,1) = 11
$ws1.cells.Item(12,2) = "Jack"
$ws1.cells.Item(13,1) = 12
$ws1.cells.Item(13,2) = "Elizabeth"
$ws1.cells.Item(14,1) = 13
$ws1.cells.Item(14,2) = "Renee"
$ws1.cells.Item(15,1) = 14
$ws1.cells.Item(15,2) = "Elizabeth"
$ws1.cells.Item(16,1) = 15
$ws1.cells.Item(16,2) = "Jack"
$ws1.cells.Item(17,1) = 16
$ws1.cells.Item(17,2) = "Renee"
$ws1.cells.Item(18,1) = 17
$ws1.cells.Item(18,2) = "Elizabeth"
$ws1.cells.Item(19,1) = 18
$ws1.cells.Item(19,2) = "Jack"
$ws1.cells.Item(20,1) = 19
$ws1.cells.Item(20,2) = "Renee"
$ws1.cells.Item(21,1) = 20
$ws1.cells.Item(21,2) = "Renee"
$used = $ws1.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$lastrow = $lastCell.row
$r = $ws1.Range("A1:B$lastrow")
$ws1.Range("A1:B$lastrow").Copy()
$ws2.Select() | Out-Null
[void]$ws2.Range("A1").PasteSpecial(-4163)
$ws3.Select() | Out-Null
[void]$ws3.Range("A1").PasteSpecial(-4163)
$ws4.Select() | Out-Null
[void]$ws4.Range("A1").PasteSpecial(-4163)
$ws5.Select() | Out-Null
[void]$ws5.Range("A1").PasteSpecial(-4163)
#
$ws5.Range("A1").Select()
# AutoFilter structure - Field, Criteria, Operator
#$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10
$xl.Range("A1").Select() | Out-Null
$xl.Selection.AutoFilter(1, "2", $xlTop10Items) #top 2
#$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent
#$xl.Selection.AutoFilter 1, "25", $$xlTop10Percent #top 25 percent
#$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items
#$xl.Selection.AutoFilter 1, "10", $$xlBottom10Percent #Bottom 10 percent
#$xl.Selection.AutoFilter 1, ">15" #size greater 15
#$xl.Selection.AutoFilter 1, ">19",XLOr , "<2" #Lowest and Highest
#$xl.Selection.AutoFilter 2, "Jack" #Jack items only
$ws5.cells.Item.EntireColumn.AutoFit
$ws2.Select()
$ws2.Range("A1").Select()
# AutoFilter structure - Field, Criteria, Operator
#$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10
#$xl.Selection.AutoFilter 1, "2", $xlTop10Items #top 2
#$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent
#$xl.Selection.AutoFilter 1, "25", $xlTop10Percent #top 25 percent
#$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items
#$xl.Selection.AutoFilter 1, "10", $xlBottom10Percent #Bottom 10 percent
#$xl.Selection.AutoFilter 1, ">15" #size greater 15
#$xl.Selection.AutoFilter 1, ">19",XLOr , "<2" #Lowest and Highest
$xl.Selection.AutoFilter(2, "Jack") #Jack items only
$ws2.cells.Item.EntireColumn.AutoFit
$ws4.Select()
$ws4.Range("A1").Select()
# AutoFilter structure - Field, Criteria, Operator
#$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10
#$xl.Selection.AutoFilter 1, "2", $xlTop10Items #top 2
#$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent
#$xl.Selection.AutoFilter 1, "25", $xlTop10Percent #top 25 percent
#$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items
#$xl.Selection.AutoFilter 1, "10", $xlBottom10Percent #Bottom 10 percent
#$xl.Selection.AutoFilter 1, ">15" #size greater 15
$xl.Selection.AutoFilter(1, ">19",$xlOr , "<2") #Lowest and Highest
#$xl.Selection.AutoFilter 2, "Jack" #Jack items only
$ws4.cells.Item.EntireColumn.AutoFit
# "Top25Percent"
$ws5.Select()
$ws5.Range("A1").Select()
# AutoFilter structure - Field, Criteria, Operator
#$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10
#$xl.Selection.AutoFilter 1, "2", $xlTop10Items #top 2
#$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent
$xl.Range("A1").Select() | Out-Null
$xl.Selection.AutoFilter(1,"25",$xlTop10Percent) #top 25 percent
#$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items
#$xl.Selection.AutoFilter 1, "10", $xlBottom10Percent #Bottom 10 percent
#$xl.Selection.AutoFilter 1, ">15" #size greater 15
#$xl.Selection.AutoFilter 1, ">19",XLOr , "<2" #Lowest and Highest
#$xl.Selection.AutoFilter 2, "Jack" #Jack items only
$ws5.cells.Item.EntireColumn.AutoFit
} # End Function
#---------------------------------------------------
#
#
# How do I set up a complex Formula in Excel?
# Here is one that creates a Complex Formula and executes it
Function XLFormula1 {
$xl = New-Object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.name = "ComplexFormula"
$ws.Tab.ColorIndex = 9
$row = 2
$lastrow = $row
$Col = 3
$Off = $Col - 1
$ws.Cells.Item(1, 1) = "FileName"
$ws.Cells.Item(1, 2) = "Folder"
$ws.Cells.Item(1, 3) = "FullPath"
$ws.Cells.Item(2, 3) = "c:\\Folder1\\FunctionFolder1\\FunctionFolder2\\File1.txt"
$ws.Cells.Item(3, 3) = "c:\\Folder1\\FunctionFolder1\\FunctionFolder2\\FunctionFolder3\\File2.txt"
$ws.Cells.Item(4, 3) = "c:\\Folder1\\FunctionFolder1\\FunctionFolder2\\FunctionFolder3\\FunctionFolder4\\File3.txt"
$lastrow = 4
#Filename
$Range1 = $ws.Range("A2")
$ws.Cells.Item(2,1).FormulaR1C1 = "=MID(C[2],FIND(CHAR(127),Substitute(C[2],""\\"",CHAR(127),LEN(C[2])-LEN(Substitute(C[2],""\\"",""""))))+1,254)"
# Note I used 254 as a hardcoded length. No filename should ever reach this length. However….
# You could get the length programatically with the following
# "=MID(C[2],FIND(CHAR(127),FunctionSubsTITUTE(C[2],""\\"",CHAR(127),LEN(C[2])-LEN(Substitute(C[2],""\\"",""""))))+1,LEN(C[2])-(FIND(CHAR(127),Substitute(C[2],""\\"",CHAR(127),LEN(C[2])-LEN(Substitute(C[2],""\\"",""""))))))"
$range2 = $ws.Range("A2:A$lastrow")
[void]$range1.AutoFill($range2,$xlFillDefault)
#Folder
$lastrow = 4
$ws.Range("B2").Select() | Out-Null
$ws.Cells.Item(2,2).FormulaR1C1 = "=LEFT(C[1],FIND(CHAR(127),Substitute(C[1],""\\"",CHAR(127),LEN(C[1])-LEN(Substitute(C[1],""\\"",""""))))-1)"
$R1 = $ws.Range("B2")
$r2 = $ws.Range("B2:B$lastrow")
[void]$R1.AutoFill($R2,$xlFillDefault)
$ws.Cells.Item.EntireColumn.AutoFit
$ws.Range("A2").Select() | Out-Null
} # End Function
#---------------------------------------------------
#
# How do I set up a Pivot Table in Excel?
# I was working with MBSA reports here.
#
Function Pivot {
$xlPivotTableVersion12 = 3
$xlPivotTableVersion10 = 1
$xlCount = -4112
$xlDescending = 2
$xlDatabase = 1
$xlHidden = 0
$xlRowField = 1
$xlColumnField = 2
$xlPageField = 3
$xlDataField = 4
# R1C1 means Row 1 Column 1 or "A1"
# R65536C5 means Row 65536 Column E or "E65536"
$PivotTable = $wb.PivotCaches().Create($xlDatabase,"Report!R1C1:R65536C5",$xlPivotTableVersion10)
$PivotTable.CreatePivotTable("Pivot!R1C1") | Out-Null
[void]$ws3.Select()
$ws3.Cells.Item(1,1).Select()
$wb.ShowPivotTableFieldList = $true
$PivotFields = $ws3.PivotTables("PivotTable1").PivotFields("Server") # Worksheet Name is Server
$PivotFields.Orientation = $xlRowField
$PivotFields.Position = 1
$PivotFields = $ws3.PivotTables("PivotTable1").PivotFields("KBID") # Column Header is KBID
$PivotFields.Orientation = $xlColumnField
$PivotFields.Position = 1
$PivotFields = $ws3.PivotTables("PivotTable1").PivotFields("KBID") # The data is in this column
$PivotFields.Orientation=$xlDataField
$mainRng = $ws3.UsedRange.Cells
$RowCount = $mainRng.Rows.Count
$R = $RowCount
$R = $R - 1
$mainRng.Select()
$objSearch = $mainRng.Find("Grand Total")
$objSearch.Select()
$C = $objSearch.Column
Write-Host $C $R # this is just so I can see what's happining
$xlSummaryAbove = 0
$xlSortValues = $xlPinYin = 1
$xlAscending = 1
$xlDescending = 2
$range1 = $ws3.UsedRange
$range2 = $ws3.Cells.Item(3, $C)
# one-column sort --> works
[void]$range2.sort($range2, $xlDescending) # puts the highest numbers at the top
} # End Function
|
PowerShellCorpus/PoshCode/NTFS ACLs Folder Tree_1.ps1
|
NTFS ACLs Folder Tree_1.ps1
|
#######################################
# TITLE: listACL.ps1 #
# AUTHOR: Santiago Fernandez Mu±oz #
# #
# DESC: This script generate a HTML #
# report show all ACLs asociated with #
# a Folder tree structure starting in #
# root specified by the user #
#######################################
param ([string] $computer = 'localhost',
[string] $path = $(if ($help -eq $false) {Throw "A path is needed."}),
[int] $level = 0,
[string] $scope = 'administrator',
[switch] $help = $false,
[switch] $debug = $false
)
#region Initializations and previous checkings
#region Initialization
$allowedLevels = 10
$Stamp = get-date -uformat "%Y%m%d"
$report = "$PWD\\$computer.html"
$comparison = ""
$UNCPath = "\\\\" + $computer + "\\" + $path + "\\"
#endregion
#region Previou chekings
if ($level -gt $allowedLevels -or $level -lt 0) {Throw "Level out of range."}
if ($computer -eq 'localhost' -or $computer -ieq $env:COMPUTERNAME) { $UNCPath = $path }
switch ($scope) {
micro {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*NT AUTHORITY*")'
}
user {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*IT*" -and $acl -notlike "*NT AUTHORITY*" -and $acl -notlike "*All*")'
}
}
#endregion
#endregion
#region Function definitions
function drawDirectory([ref] $directory) {
$dirHTML = '
<div class="'
if ($directory.value.level -eq 0) { $dirHTML += 'he0_expanded' } else { $dirHTML += 'he' + $directory.value.level }
$dirHTML += '"><span class="sectionTitle" tabindex="0">Folder ' + $directory.value.Folder.FullName + '</span></div>
<div class="container"><div class="he' + ($directory.value.level + 1) + '"><span class="sectionTitle" tabindex="0">Access Control List</span></div>
<div class="container">
<div class="heACL">
<table class="info3" cellpadding="0" cellspacing="0">
<thead>
<th scope="col"><b>Owner</b></th>
<th scope="col"><b>Privileges</b></th>
</thead>
<tbody>'
foreach ($itemACL in $directory.value.ACL) {
$acls = $null
if ($itemACL.AccessToString -ne $null) {
$acls = $itemACL.AccessToString.split("`n")
}
$dirHTML += '<tr><td>' + $itemACL.Owner + '</td>
<td>
<table>
<thead>
<th>User</th>
<th>Control</th>
<th>Privilege</th>
</thead>
<tbody>'
foreach ($acl in $acls) {
$temp = [regex]::split($acl, "(?<!(,|NT))\\s{1,}")
if ($debug) {
write-host "ACL(" $temp.gettype().name ")[" $temp.length "]: " $temp
}
if ($temp.count -eq 1) {
continue
}
if ($scope -ne 'administrator') {
if ( Invoke-Expression $comparison ) {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
} else {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
}
$dirHTML += '</tbody>
</table>
</td>
</tr>'
}
$dirHTML += '
</tbody>
</table>
</div>
</div>
</div>'
return $dirHTML
}
#endregion
#region Printing help message
if ($help) {
Write-Host @"
/ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ\\
Ę Script gather access control lists per directory Ę
\\ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ/
USAGE: ./listACL -computer <machine or IP>
-path <path>
-level <0-10>
-help:[$false]
PARAMETERS:
computer [OPTIONAL] - Computer name or IP addres where folder is hosted (Default: localhost)
path [REQUIRED] - Folder's path to query.
level [OPTIONAL] - Level of folders to go down in the query. Allowd values are between 0 and $allowedLevels.
0 show that there's no limit in the going down (Default: 0)
scope [OPTIONAL] - Sets the amount of information showd in the report. Allowd values are:
Ę user, show important information to the user.
Ę micro, show user scope information plus important information for the IT Department.
Ę administrator, show all information.
help [OPTIONAL] - This help.
"@
exit 0
}
#endregion
if (Test-Path $report)
{
Remove-item $report
}
#To normalize I check if last character in the path is the folder separator character
if ($path.Substring($path.Length - 1,1) -eq "\\") { $path = $path.Substring(0,$path.Length - 1) }
#region Header, style and javascript functions needed by the html report
@"
<html dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" gpmc_reportInitialized="false">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-16" />
<title>Access Control List for $path in $computer</title>
<!-- Styles -->
<style type="text/css">
body{ background-color:#FFFFFF; border:1px solid #666666; color:#000000; font-size:68%; font-family:MS Shell Dlg; margin:0px 0px 10px 0px; }
table{ font-size:100%; table-layout:fixed; width:100%; }
td,th{ overflow:visible; text-align:left; vertical-align:top; white-space:normal; }
.title{ background:#FFFFFF; border:none; color:#333333; display:block; height:24px; margin:0px 0px -1px 0px; padding-top:4px; position:relative; table-layout:fixed; width:100%; z-index:5; }
.he0_expanded{ background-color:#FEF7D6; border:1px solid #BBBBBB; color:#3333CC; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:0px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1_expanded{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he2{ background-color:#C0D2DE; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:20px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he3{ background-color:#D9E3EA; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:30px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:40px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-bottom:5px; padding-left:21px; padding-top:4px; position:relative; width:100%; }
.he5{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:50px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he5h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; padding-right:5em; padding-top:4px; margin-bottom:-1px; margin-left:55px; margin-right:0px; position:relative; width:100%; }
.he5i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:21px; padding-bottom:5px; padding-top: 4px; position:relative; width:100%; }
.he6{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he7{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:60px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he8{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:65px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he9{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:70px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he10{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:75px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he11{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:80px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.heACL { background-color:#ECFFD7; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:90px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
DIV .expando{ color:#000000; text-decoration:none; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:normal; position:absolute; right:10px; text-decoration:underline; z-index: 0; }
.he0 .expando{ font-size:100%; }
.info, .info3, .info4, .disalign{ line-height:1.6em; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; }
.disalign TD{ padding-bottom:5px; padding-right:10px; }
.info TD{ padding-right:10px; width:50%; }
.info3 TD{ padding-right:10px; width:33%; }
.info4 TD, .info4 TH{ padding-right:10px; width:25%; }
.info5 TD, .info5 TH{ padding-right:0px; width:20%; }
.info TH, .info3 TH, .info4 TH, .disalign TH{ border-bottom:1px solid #CCCCCC; padding-right:10px; }
.subtable, .subtable3{ border:1px solid #CCCCCC; margin-left:0px; background:#FFFFFF; margin-bottom:10px; }
.subtable TD, .subtable3 TD{ padding-left:10px; padding-right:5px; padding-top:3px; padding-bottom:3px; line-height:1.1em; width:10%; }
.subtable TH, .subtable3 TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable3 .footnote, .subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable_frame{ background:#D9E3EA; border:1px solid #CCCCCC; margin-bottom:10px; margin-left:15px; }
.subtable_frame TD{ line-height:1.1em; padding-bottom:3px; padding-left:10px; padding-right:15px; padding-top:3px; }
.subtable_frame TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtableInnerHead{ border-bottom:1px solid #CCCCCC; border-top:1px solid #CCCCCC; }
.explainlink{ color:#000000; text-decoration:none; cursor:pointer; }
.explainlink:hover{ color:#0000FF; text-decoration:underline; }
.spacer{ background:transparent; border:1px solid #BBBBBB; color:#FFFFFF; display:block; font-family:MS Shell Dlg; font-size:100%; height:10px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top: 4px; position:relative; }
.filler{ background:transparent; border:none; color:#FFFFFF; display:block; font:100% MS Shell Dlg; line-height:8px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top:4px; position:relative; }
.container{ display:block; position:relative; }
.rsopheader{ background-color:#A0BACB; border-bottom:1px solid black; color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-bottom:5px; text-align:center; }
.rsopname{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gponame{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gpotype{ color:#333333; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; padding-left:11px; }
#uri { color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; }
#dtstamp{ color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; text-align:left; width:30%; }
#objshowhide { color:#000000; cursor:pointer; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-right:0px; padding-right:10px; text-align:right; text-decoration:underline; z-index:2; }
#gposummary { display:block; }
#gpoinformation { display:block; }
</style>
</head>
<body>
<table class="title" cellpadding="0" cellspacing="0">
<tr><td colspan="2" class="gponame">Access Control List for $path on machine $computer</td></tr>
<tr>
<td id="dtstamp">Data obtained on: $(Get-Date)</td>
<td><div id="objshowhide" tabindex="0"></div></td>
</tr>
</table>
<div class="filler"></div>
"@ | Set-Content $report
#endregion
#region Information gathering
$colFiles = Get-ChildItem -path $UNCPath -Filter *. -Recurse -force -Verbose | Sort-Object FullName
$colACLs = @()
#We start going through the path pointed out by the user
foreach($file in $colFiles)
{
#To control the current level in the tree we are in it's needed to count the number of separator characters
#contained in the path. However in order to make the count correctly it's needed to delete the path
#provided by the user (the parent). Once the parent has been deleted, the rest of the full name will be
#string used to do the level count.
#It's needed to use a REGEX object to get ALL separator character matches.
$matches = (([regex]"\\\\").matches($file.FullName.substring($path.length, $file.FullName.length - $path.length))).count
if ($level -ne 0 -and ($matches - 1) -gt $level) {
continue
}
if ($debug) {
Write-Host $file.FullName "->" $file.Mode
}
if ($file.Mode -notlike "d*") {
continue
}
$myobj = "" | Select-Object Folder,ACL,level
$myobj.Folder = $file
$myobj.ACL = Get-Acl $file.FullName
$myobj.level = $matches - 1
$colACLs += $myobj
}
#endregion
#region Setting up the report
'<div class="gposummary">' | Add-Content $report
for ($i = 0; $i -lt $colACLs.count; $i++) {
drawDirectory ([ref] $colACLs[$i]) | Add-Content $report
}
'</div></body></html>' | Add-Content $report
#endregion
|
PowerShellCorpus/PoshCode/mstsc-Ac.ps1
|
mstsc-Ac.ps1
|
<#
.SYNOPSIS
mstsc-Ac.ps1 (Version 1.0, 7 Jan 2012)
The author may be contacted via zippy1981@gmail.com
The latest authoritative version of this script is always available at
http://bit.ly/mstsc-Ac
.DESCRIPTION
This script will see if a host is up and listening on a given port, and start a
remote desktop connection to it. The idea is you run this script after rebooting a windows server
.EXAMPLE
.\\mstsc-Ac.ps1 192.168.0.2
Starts an RDP connection on 192.168.0.2
.EXAMPLE
.\\mstsc-Ac.ps1 192.168.0.2 3390
Starts an RDP connection on 192.168.0.2 port 3390 .
.EXAMPLE
mstsc-Ac.ps1 192.168.0.2 -AdditionalParameters "/w:1000 /h:500"
Starts an RDP connection on 192.168.0.2 with a width of 1000 pixels and a height of 500 pixels.
.Notes
Copyright (c) 2012 Justin Dearing
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.
*****************************************************************************
NOTE: YOU MAY *ALSO* DISTRIBUTE THIS FILE UNDER ANY OF THE FOLLOWING...
PERMISSIVE LICENSES:
BSD: http://www.opensource.org/licenses/bsd-license.php
MIT: http://www.opensource.org/licenses/mit-license.html
RECIPROCAL LICENSES:
GPL 2: http://www.gnu.org/copyleft/gpl.html
*****************************************************************************
LASTLY: THIS IS NOT LICENSED UNDER GPL v3 (although the above are compatible)
#>
param(
[string] $HostOrIpAddress = "",
[int] $Port = 3389,
[string] $AdditionalParameters = "/f"
)
# TODO: It seems you can't specify the user name and password on the command line
<#
[string] $userName = $(Read-Host -Prompt "Username"),
[string] $password = $(
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR(
(Read-Host -Prompt "Password" -AsSecureString)
)
)
#>
if ([String]::IsNullOrEmpty($HostOrIpAddress)) {
# This is the first value in the drop down list of the remote desktop client
$lastHost = (Get-ItemProperty 'HKCU:\\Software\\Microsoft\\Terminal Server Client\\Default' 'MRU0').MRU0
$hostInput = (Read-Host -Prompt "Host (Default $($lastHost))").Split(':')
if ([String]::IsNullOrEmpty($hostInput)) { $hostInput = $lastHost }
$HostOrIpAddress = $hostInput[0];
if ($host.Length -gt 1) { $Port = $hostInput[1] }
}
$pingTimeout = 1000 # ping timeout in milllliseconds
$successfulConsecutivePingCount = 5
$sleepTime = 5 # Time to sleep in seconds
$ping = New-Object System.Net.NetworkInformation.Ping
$rdpPortListening = $false;
# Were looking for 5 consecutive pings that don't time out.
# Then were going to try to connect to the remote desktop port
while (-not $rdpPortListening) {
for ($i = 0; $i -lt $successfulConsecutivePingCount; $i++) {
$result = $ping.Send($HostOrIpAddress, $pingTimeout);
if ($result.Status -eq 'Success') {
Write-Host "Reply from $($result.Address) Round Trip Time $($result.RoundTripTime)"
} else {
Write-Host "Request Timed out. Sleeping for $($sleepTime) seconds."
$i = 0;
Start-Sleep $sleepTime
}
#$ping.Send('74.125.115.107', 500);
}
try {
$socket = New-Object Net.Sockets.TcpClient($HostOrIpAddress, $Port)
if ($socket.Connected) {
$rdpPortListening = $true
Write-Host "RDP Service appears to be up"
}
$socket.Close()
}
catch [System.Management.Automation.MethodInvocationException] {
if ($_.Exception.InnerException.GetType() -eq [System.Net.Sockets.SocketException]) {
Write-Host $_.Exception.InnerException.Message
Start-Sleep $sleepTime
}
else {
throw $_.Exception.InnerException
}
}
}
Invoke-Expression "mstsc /v $($HostOrIpAddress):$($Port) $($AdditionalParameters)"
|
PowerShellCorpus/PoshCode/powershell ise config_1.ps1
|
powershell ise config_1.ps1
|
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" />
<supportedRuntime version="v2.0" />
<process>
<rollForward enabled="false" />
</process>
</startup>
<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>
</configuration>
|
PowerShellCorpus/PoshCode/Write-ASCII-Letters.ps1
|
Write-ASCII-Letters.ps1
|
#
#.SYNOPSIS
# Svendsen Tech's PowerShell ASCII art script creates ASCII art characters
# from a subset of common letters, numbers and punctuation characters.
# You can add new characters by editing the XML and updating the
# $AcceptedChars regexp.
#
# Author: Joakim Svendsen, Svendsen Tech
#
#.DESCRIPTION
# This script reads characters (it started out as letters so the variable
# names are not precise) from an XML file. If you include new characters
# in the XML, you will need to add them to the regular expression assigned
# to the variable $AcceptedChars.
#
# It was written to be used in conjunction with a modified version of
# PowerBot (http://poshcode.org/2510), a simple IRC bot framework written
# using SmartIrc4Net; that's why it prepends an apostrophe by default
# because somewhere along the way the leading spaces get lost before it
# hits the IRC channel.
#
# Currently the XML only contains lowercase letters.
#
# Example:
# PS E:\\ASCII-letters> .\\Write-ASCII-Letters.ps1 -NoPrependChar "ASCII!"
# _ _ _
# __ _ ___ ___ (_)(_)| |
# / _` |/ __| / __|| || || |
# | (_| |\\__ \\| (__ | || ||_|
# \\__,_||___/ \\___||_||_|(_)
# PS E:\\ASCII-letters>
#
#.PARAMETER InputText
# String(s) to convert to ASCII.
#.PARAMETER NoPrependChar
# Makes the script not prepend an apostrophe.
#.PARAMETER TextColor
# Optional. Console only. Changes color of output.
#>
param(
[string[]] $InputText,
[switch] $NoPrependChar,
[string] $TextColor = 'Default'
#[int] $MaxChars = '25'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Populate the $Letters hashtable with character data from the XML.
Function Parse-LetterXML {
$LetterFile = '.\\letters.xml'
$Xml = [xml] (Get-Content $LetterFile)
$Xml.Letters.Letter | ForEach-Object {
$Letters.($_.Name) = New-Object PSObject -Property @{
'Lines' = $_.Lines
'ASCII' = $_.Data
'Width' = $_.Width
}
}
}
# Algorithm from hell... This was painful. I hope there's a better way.
function Create-ASCII-Text {
param([string] $Text)
$LetterArray = [char[]] $Text.ToLower()
#Write-Host -fore green $LetterArray
# Find the letter with the most lines.
$MaxLines = 0
$LetterArray | ForEach-Object { if ($Letters.([string] $_).Lines -gt $MaxLines ) { $MaxLines = $Letters.([string] $_).Lines } }
$LetterWidthArray = $LetterArray | ForEach-Object { $Letter = [string] $_; $Letters.$Letter.Width }
$LetterLinesArray = $LetterArray | ForEach-Object { $Letter = [string] $_; $Letters.$Letter.Lines }
#$LetterLinesArray
$Lines = @{
'1' = ''
'2' = ''
'3' = ''
'4' = ''
'5' = ''
'6' = ''
}
#$LineLengths = @(0, 0, 0, 0, 0, 0)
$LetterPos = 0
foreach ($Letter in $LetterArray) {
# We need to work with strings for indexing the hash by letter
$Letter = [string] $Letter
# Each ASCII letter can be from 4 to 6 lines.
# If the letter has the maximum of 6 lines, populate hash with all lines.
if ($LetterLinesArray[$LetterPos] -eq 6) {
foreach ($Num in 1..6) {
$StringNum = [string] $Num
$LineFragment = [string](($Letters.$Letter.ASCII).Split("`n"))[$Num-1]
if ($LineFragment.Length -lt $Letters.$Letter.Width) {
$LineFragment += ' ' * ($Letters.$Letter.Width - $LineFragment.Length)
}
$Lines.$StringNum += $LineFragment
}
}
# Add padding for line 6 for letters with 5 lines and populate lines 2-6.
elseif ($LetterLinesArray[$LetterPos] -eq 5) {
$Padding = ' ' * $LetterWidthArray[$LetterPos]
$Lines.'1' += $Padding
foreach ($Num in 2..6) {
$StringNum = [string] $Num
$LineFragment = [string](($Letters.$Letter.ASCII).Split("`n"))[$Num-2]
if ($LineFragment.Length -lt $Letters.$Letter.Width) {
$LineFragment += ' ' * ($Letters.$Letter.Width - $LineFragment.Length)
}
$Lines.$StringNum += $LineFragment
}
}
# Here we deal with letters with four lines.
# Dynamic algorithm that places four-line letters on the bottom line if there are
# 4 or 5 lines only in the letter with the most lines.
else {
# Default to putting the 4-liners at line 3-6
$StartRange, $EndRange, $IndexSubtract = 3, 6, 3
$Padding = ' ' * $LetterWidthArray[$LetterPos]
# If there are 4 or 5 lines...
if ($MaxLines -lt 6) {
$Lines.'2' += $Padding
}
# There are 6 lines maximum, put 4-line letters in the middle.
else {
$Lines.'1' += $Padding
$Lines.'6' += $Padding
$StartRange, $EndRange, $IndexSubtract = 2, 5, 2
}
# There will always be at least four lines. Populate lines 2-5 or 3-6 in the hash.
foreach ($Num in $StartRange..$EndRange) {
$StringNum = [string] $Num
$LineFragment = [string](($Letters.$Letter.ASCII).Split("`n"))[$Num-$IndexSubtract]
if ($LineFragment.Length -lt $Letters.$Letter.Width) {
$LineFragment += ' ' * ($Letters.$Letter.Width - $LineFragment.Length)
}
$Lines.$StringNum += $LineFragment
}
}
$LetterPos++
} # end of LetterArray foreach
# Return stuff
$Lines.GetEnumerator() | Sort Name | Select -ExpandProperty Value | ?{ $_ -match '\\S' } | %{ if ($NoPrependChar) { $_ } else { "'" + $_ } }
}
# Get ASCII art letters/characters and data from XML.
$Letters = @{}
Parse-LetterXML
# Turn the [string[]] into a [string] the only way I could figure out how... wtf
$Text = ''
$InputText | ForEach-Object { $Text += "$_ " }
# Limit to 30 characters
$MaxChars = 30
if ($Text.Length -gt $MaxChars) { "Too long text. There's a maximum of $MaxChars characters."; exit }
# Replace spaces with underscores.
$Text = $Text -replace ' ', '_'
# Define accepted characters (which are found in XML).
$AcceptedChars = '[^a-z0-9 _,!?./;:<>(){}\\[\\]''\\-\\\\"ćřĺ]' # ćřĺ only works when sent as UTF-8 on IRC
if ($Text -match $AcceptedChars) { "Unsupported character, using this 'accepted chars' regex: $AcceptedChars."; exit }
# Filthy workaround (now worked around in the foreach creating the string).
#if ($Text.Length -eq 1) { $Text += '_' }
$Lines = @()
$ASCII = Create-ASCII-Text $Text
if ($TextColor -ne 'Default') { Write-Host -ForegroundColor $TextColor ($ASCII -join "`n") }
else { $ASCII }
|
PowerShellCorpus/PoshCode/CSV Validator Framework_1.ps1
|
CSV Validator Framework_1.ps1
|
# --- begin test-csv.ps1 ---
param(
[string]$Path = $(throw "require CSV path!"),
[string]$RulesetPath = $(throw "require Ruleset path!")
)
$csvFiles = Resolve-Path -Path $Path
# load rules
if ((Test-Path (Resolve-Path $RulesetPath))) {
# ruleset is found, execute and assign result to variable (should be hashtable)
$ruleset = (& $RulesetPath)
write-host "Ruleset has $($ruleset.firstrow.keys.count) first row rule(s)"
write-host "Ruleset has $($ruleset.allrows.keys.count) all rows rule(s)"
if (-not ($ruleset.firstrow)) {
write-warning "ruleset $rulesetpath has no rules for first row (list/table validation)"
}
if (-not ($ruleset.allrows)) {
throw "ruleset $rulesetpath has no rules for allrows (row validation)"
}
} else {
throw "Could not find ruleset $rulesetpath"
}
write-verbose "Found $($csvfiles.length) file(s)"
$csvFiles | where-object {
# only pass on CSV files
[io.path]::GetExtension( $_.providerpath ) -eq ".csv"
} | foreach-object {
write-host "processing CSV $_"
# import csv files
$firstRow = $true
$rowcount = 0
import-csv $_.path | foreach-object {
write-host "row $rowcount"
$currentRow = $_
# process "first row only" rules, only on first row
if ($firstRow) {
$ruleset.FirstRow.Keys | % {
write-host -nonewline "Processing rule $_ ... "
# execute the scriptblock with the current row as an argument
# the scriptblock is the value of the imported hashtable
if ((& $ruleset.firstrow[$_] $currentRow)) {
write-host -fore green "passed"
} else {
# displays green in ISE (lol)
write-host -fore red "failed"
}
}
$firstRow = $false
}
# process "all rows" rules
$ruleset.AllRows.Keys | % {
write-host -nonewline "Processing rule $_ ... "
# execute the scriptblock with the current row as an argument
# the scriptblock is the value of the imported hashtable
if ((& $ruleset.AllRows[$_] $currentRow)) {
write-host -fore green "passed"
} else {
# displays green in ISE (lol)
write-host -fore red "failed"
}
}
$rowcount++
}
}
# --- end test-csv.ps1 ---
# --- begin ruleset-sample.ps1 ---
@{
FirstRow = @{
ruleVerifyColumns = {
param($row)
$columns = @("u_logon_name",
"u_user_security_password",
"g_user_id_changed_by",
"i_account_status",
"d_date_registered",
"d_date_last_changed",
"d_date_created")
$count = 0
$columns | ForEach-Object <# alias = % #> {
if ($row.psobject.members.Match($_)) { $count++ }
}
$count -eq $columns.length
};
};
AllRows = @{
ruleLogonNameLengthGreaterThan8 = {
param($row)
$row.u_logon_name -gt 8
};
ruleChangedByIsValidGuid = {
param($row)
try {
# try cast to guid and swallow result if successful
[guid]$row.g_user_id_changed_by > $null
$true
} catch { $false }
};
}
}
# --- end ruleset-sample.ps1 ---
|
PowerShellCorpus/PoshCode/Fridays thirteenth.ps1
|
Fridays thirteenth.ps1
|
function Get-FridaysThirteenth {
param (
[datetime]$end = "12/31/2010"
)
[DateTime]$begin = "02/13/2009"
for ($i = $begin; $i -lt $end; $i = $i.AddMonths(1)) {
if ($i.DayOfWeek -eq 'Friday') {
"{0:d}" -f $i
} #if
} #for
} #function
|
PowerShellCorpus/PoshCode/Findup_24.ps1
|
Findup_24.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
namespace Findup
{
public class FileLengthComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return (x.Length.CompareTo(y.Length));
}
}
class Findup
{
public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>>
{ {"-x", new List<string>()},{"-i",new List<string>()},{"-xf",new List<string>()},{"-if",new List<string>()},
{"-xd",new List<string>()},{"-id",new List<string>()},{"-paths",new List<string>()} };
public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>>
{ {"-xr", new List<Regex>()},{"-ir",new List<Regex>()},{"-xfr",new List<Regex>()},{"-ifr",new List<Regex>()},
{"-xdr",new List<Regex>()},{"-idr",new List<Regex>()} };
public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "-recurse", false }, { "-noerr", false }, {"-delete",false} };
public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files found, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes.
public static string delconfirm;
public static void Main(string[] args)
{
DateTime startTime = DateTime.Now;
Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012.");
Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files.");
Console.WriteLine(" ");
string optionskey = "-paths";
List<FileInfo> files = new List<FileInfo>();
int i = 0;
for (i = 0; i < args.Length; i++)
{
string argitem=args[i].ToLower();
if ((System.String.Compare(argitem, "-help", true) == 0) || (System.String.Compare(argitem, "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [-recurse] [-noerr] [-x/-i/-xd/-id/-xf/-if] <files/directories/regex> [-regex] [-delete]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help message.");
Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" -noerr - discards error messages.");
Console.WriteLine(" -delete - delete each duplicate file with confirmation.");
Console.WriteLine(" -x - eXcludes if full file path starts with (or RegEx matches if -xr) one of the items following this switch until another switch is used.");
Console.WriteLine(" -i - include if full file path starts with (or Regex matches if -ir) one of the items following this switch until another switch is used.");
Console.WriteLine(" -xd - eXcludes all directories - minus drive/files - (using RegEx if -xdr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -id - Include only directories - minus drive/files - (using RegEx if -idr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -xf - eXcludes all files - minus drive/directories - (using RegEx if -xfr) following this switch until another switch is used.");
Console.WriteLine(" -if - Include only files - minus drive/directories - (using RegEx if -ifr) following this switch until another switch is used.");
Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr.");
Console.WriteLine(" -paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr");
Console.WriteLine(" - Find dupes in c:\\\\finance.");
Console.WriteLine(" - recurse all subdirs of c:\\\\finance.");
Console.WriteLine(" - suppress error messages.");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics");
Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data");
Console.WriteLine(" - recurse subdirs in d:\\\\data.");
Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs.");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -xr \\"(jim)\\" -regex");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc");
Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\"");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc -xr \\"[bf]\\" -ir \\"(smith)\\" -regex");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc");
Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \\"[bf]\\",\\"(smith)\\"");
Console.WriteLine("Note: Exclude takes precedence over Include.");
return;
}
if (optionsbools.ContainsKey(argitem))
{
optionsbools[argitem] = true;
optionskey = "-paths";
continue;
}
if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem))
{
optionskey = argitem;
continue;
}
if (optionspaths.ContainsKey(optionskey))
optionspaths[optionskey].Add(argitem);
else
{
try {
Regex rgx = new Regex(argitem, RegexOptions.Compiled);
optionsregex[optionskey].Add(rgx);
}
catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);}
}
}
if (optionspaths["-paths"].Count == 0)
{
WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory.");
optionspaths["-paths"].Add(".");
}
Console.Write("Getting file info and sorting file list...");
getFiles(optionspaths["-paths"], "*.*", optionsbools["-recurse"], files);
if (files.Count < 2)
{
WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help");
Console.WriteLine("\\n");
return;
}
files.Sort(new FileLengthComparer());
Console.WriteLine("Completed!");
Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths...");
var SizeHashFile = new Dictionary<long, Dictionary<string,List<FileInfo>>>();
for (i = 0; i < (files.Count - 1); i++)
{
if (files[i].Length != files[i + 1].Length) { continue; }
var breakout = false;
while (true)
{
try
{
var _SHA512 = SHA512.Create();
using (var fstream = File.OpenRead(files[i].FullName))
{
_SHA512.ComputeHash(fstream);
}
string SHA512string = "";
foreach (var c in _SHA512.Hash)
{
SHA512string += String.Format("{0:x2}", c);
}
if (!SizeHashFile.ContainsKey(files[i].Length))
SizeHashFile.Add(files[i].Length, new Dictionary<string,List<FileInfo>>());
if (!SizeHashFile[files[i].Length].ContainsKey(SHA512string))
SizeHashFile[files[i].Length][SHA512string] = new List<FileInfo>() {};
SizeHashFile[files[i].Length][SHA512string].Add(files[i]);
}
catch (Exception e) { WriteErr("Hash error: " + e.Message); }
if (breakout == true) {break;}
i++;
if (i == (files.Count - 1)) { breakout = true; continue; }
breakout = (files[i].Length != files[i + 1].Length);
}
}
Console.WriteLine("Completed!");
foreach (var SizeGroup in SizeHashFile)
{
foreach (var HashGroup in SizeGroup.Value)
{
var SGK = (long)SizeGroup.Key;
var HGVC = (long)HashGroup.Value.Count;
if (HGVC > 1)
{
Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HGVC, SGK, SGK*HGVC);
foreach (var Filenfo in HashGroup.Value)
{
Console.WriteLine(Filenfo.FullName);
numOfDupes++;
dupeBytes += Filenfo.Length;
if (optionsbools["-delete"])
if (DeleteDupe(Filenfo)) { bytesrecovered += Filenfo.Length; deletedfiles++; }
}
}
}
}
Console.WriteLine("\\n ");
Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS.
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes);
Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles);
Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered);
Console.WriteLine("Execution time : " + (DateTime.Now - startTime));
}
private static void WriteErr(string Str)
{
if (!optionsbools["-noerr"])
Console.WriteLine(Str);
}
private static Boolean DeleteDupe(FileInfo Filenfo)
{
Console.Write("Delete this file <y/N> <ENTER>?");
delconfirm = Console.ReadLine();
if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y'))
{
try
{
Filenfo.Delete();
Console.WriteLine("File Successfully deleted.");
return true;
}
catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); }
}
return false;
}
private static Boolean CheckNames(string fullname)
{
var filePart = Path.GetFileName(fullname); // get file name only (e.g. "d:\\temp\\data.txt" -> "data.txt")
var dirPart = Path.GetDirectoryName(fullname).Substring(fullname.IndexOf(Path.VolumeSeparatorChar)+2); // remove drive & file (e.g. "d:\\temp\\data.txt" -> "temp")
if (CheckNamesWorker(fullname, "-x", "-xr", true))
return false;
if (CheckNamesWorker(filePart, "-xf", "-xfr", true))
return false;
if (CheckNamesWorker(dirPart, "-xd", "-xdr", true))
return false;
if (CheckNamesWorker(fullname, "-i", "-ir", false))
return false;
if (CheckNamesWorker(filePart, "-if", "-ifr", false))
return false;
if (CheckNamesWorker(dirPart, "-id", "-idr", false))
return false;
return true;
}
private static Boolean CheckNamesWorker(string filestr, string pathskey, string rgxkey, Boolean CheckType)
{
foreach (var filepath in optionspaths[pathskey])
{
if (filestr.ToLower().StartsWith(filepath) == CheckType)
return true;
}
foreach (var rgx in optionsregex[rgxkey])
{
if (rgx.IsMatch(filestr) == CheckType)
return true;
}
return false;
}
private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckNames(addf.FullName))
returnList.Add(addf);
}
catch (Exception e) { WriteErr("Add file error: " + e.Message); }
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckNames(addf.FullName))
returnList.Add(addf);
}
}
catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); }
if (recursiveFlag)
{
try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); }
catch (Exception e) { WriteErr("Add Directory error: " + e.Message); }
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
WriteErr("Parse error on: " + pathRec);
WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
WriteErr("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
getFiles(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/Create SP2010 Farm V_4.ps1
|
Create SP2010 Farm V_4.ps1
|
############################################################################
## Create-SPFarm
## V 0.3
## Jos.Verlinde
############################################################################
Param ( [String] $Farm = "SP2010",
[String] $SQLServer = $env:COMPUTERNAME,
[String] $Passphrase = "pass@word1",
[int] $CAPort = 26101 ,
[switch] $Force = $false )
# Disable the Loopback Check on stand alone demo servers.
# This setting usually kicks out a 401 error when you try to navigate to sites that resolve to a loopback address e.g. 127.0.0.1
New-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword
#region Process Input Parameters
$SecPhrase=ConvertTo-SecureString $Passphrase –AsPlaintext –Force
$Passphrase = $null
## get Farm Account
$cred_farm = $host.ui.PromptForCredential("FARM Setup", "SP Farm Account (SP_farm)", "contoso\\sp_farm", "NetBiosUserName" )
#Endregion
# Create a new farm
New-SPConfigurationDatabase –DatabaseName “$FARM-Config” –DatabaseServer $SQLServer –AdministrationContentDatabaseName “$FARM-Admin-Content” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm
# Create Central Admin
New-SPCentralAdministration -Port $CAPort -WindowsAuthProvider "NTLM"
#Install Help Files
Install-SPApplicationContent
#Secure resources
Initialize-SPResourceSecurity
#Install (all) features
If ( $Force ) {
$Features = Install-SPFeature –AllExistingFeatures -force
} else {
$Features = Install-SPFeature –AllExistingFeatures
}
## Report features installed
$Features
# Provision all Services works only on stand alone servers (ie one-click-install )
# Install-SPService -Provision
## Todo : Check for Errors in the evenlog
##
## Start Central Admin
Start-Process "http://$($env:COMPUTERNAME):$CAPort"
## Run Farm configuration Wizard
Start-Process "http://$($env:COMPUTERNAME):$CAPort/_admin/adminconfigintro.aspx?scenarioid=adminconfig&welcomestringid=farmconfigurationwizard_welcome"
##@@ Todo - Run Farm Wizard or better yet create required service applications (minimal - normal - all template)
|
PowerShellCorpus/PoshCode/WSUS Admin Module.ps1
|
WSUS Admin Module.ps1
|
Write-Host "`n"
Write-Host "`t`tWSUS Administrator Module 1.0"
Write-Host "`n"
Write-Host -nonewline "Make initial connection to WSUS Server:`t"
Write-Host -fore Yellow "Connect-WSUSServer"
Write-Host -nonewline "Disconnect from WSUS Server:`t`t"
Write-Host -fore Yellow "Disconnect-WSUSServer"
Write-Host -nonewline "List all available commands:`t`t"
Write-Host -fore Yellow "Get-WSUSCommands"
Write-Host "`n"
function Get-WSUSCommands {
<#
.SYNOPSIS
Lists all WSUS functions available from this module.
.DESCRIPTION
Lists all WSUS functions available from this module.
.NOTES
Name: Get-WSUSCommand
Author: Boe Prox
DateCreated: 18Oct2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSCommands
Description
-----------
This command lists all of the available WSUS commands in the module.
#>
[cmdletbinding()]
Param ()
#List all WSUS functions available
Get-Command *WSUS* -CommandType Function | Sort-Object Name
}
function Connect-WSUSServer {
<#
.SYNOPSIS
Retrieves the last check-in times of clients on WSUS.
.DESCRIPTION
Retrieves the last check-in times of clients on WSUS. You will need to run this on a machine that
has the WSUS Administrator console installed.
.PARAMETER WsusServer
Name of WSUS server to query against.
.PARAMETER Secure
Determines if a secure connection will be used to connect to the WSUS server. If not used, then a non-secure
connection will be used.
.NOTES
Name: Get-LastCheckIn
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Connect-WSUSServer -wsusserver "server1"
Description
-----------
This command will make the connection to the WSUS using an unsecure port (Default:80).
.EXAMPLE
Connect-WSUSServer -wsusserver "server1" -secure
Description
-----------
This command will make a secure connection (Default: 443) to a WSUS server.
#>
[cmdletbinding(
DefaultParameterSetName = 'wsus',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'wsus',
ValueFromPipeline = $True)]
[string]$WsusServer,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = 'wsus',
ValueFromPipeline = $False)]
[switch]$Secure
)
#Load required assemblies
[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
#Make connection to WSUS server
Write-Host -ForegroundColor Yellow "Attempting connection to WSUS Server: $($wsusserver)"
$ErrorActionPreference = 'stop'
Try {
If ($secure) {
$Global:wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($wsusserver,$True)
$Wsus | FT Name, Version,PortNumber
}
Else {
$Global:wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($wsusserver,$False)
$Wsus | FT Name, Version,PortNumber
}
}
Catch {
Write-Error "Unable to connect to $($wsusserver)!`n$($error[0])"
}
}
function Disconnect-WSUSServer {
<#
.SYNOPSIS
Disconnects session against WSUS server.
.DESCRIPTION
Disconnects session against WSUS server.
.NOTES
Name: Disconnect-WSUSServer
Author: Boe Prox
DateCreated: 27Oct2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Disconnect-WSUSServer
Description
-----------
This command will disconnect the session to the WSUS server.
#>
[cmdletbinding()]
Param ()
#Disconnect WSUS session by removing the variable
Remove-Variable -Name wsus -Force
}
function Get-WSUSClients {
<#
.SYNOPSIS
Retrieves a list of all of the clients in WSUS.
.DESCRIPTION
Retrieves a list of all of the clients in WSUS.
.NOTES
Name: Get-WSUSClients
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSClients
Description
-----------
This command will list every client in WSUS.
#>
[cmdletbinding()]
Param ()
#Gather all computers in WSUS
$wsus.GetComputerTargets()
}
function Start-WSUSSync {
<#
.SYNOPSIS
Start synchronization on WSUS server.
.DESCRIPTION
Start synchronization on WSUS server.
.PARAMETER Monitor
Starts a synchronization and runs a background job to monitor currently running content download and
notifies user when completed.
.NOTES
Name: Start-WSUSSync
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Start-WSUSSync
Description
-----------
This command will begin a manual sychronization on WSUS with the defined update source.
.EXAMPLE
Start-WSUSSync -monitor
Description
-----------
This command will begin a manual synchronization on WSUS and will begin a background job that will notifiy via
pop-up message when the synchronization has completed.
#>
[cmdletbinding(
DefaultParameterSetName = 'monitor',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param (
[Parameter(
Mandatory = $False,
Position = 0,
ParameterSetName = 'monitor',
ValueFromPipeline = $False)]
[switch]$Monitor
)
$sub = $wsus.GetSubscription()
$sync = $sub.GetSynchronizationProgress()
If ($monitor) {
#Stop and remove any jobs for SyncMonitoring
$jobs = Get-Job | ? {$_.Name -eq "WSUSSyncProgressMonitor"}
If ($jobs) {
$jobs | Stop-Job
$jobs | Remove-Job
}
#Start WSUS synchronization
If ($pscmdlet.ShouldProcess($($wsus.name))) {
$sub.StartSynchronization()
"Synchronization have been started."
Start-Sleep -Seconds 3
Start-Job -Name "WSUSSyncProgressMonitor" -ArgumentList $sync -ScriptBlock {
Param (
$sync
)
#Load required assemblies for message window
[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
While ($sync.Phase -ne "NotProcessing") {
$null
}
[System.Windows.Forms.MessageBox]::Show("Synchronization has been completed on WSUS",”Information”)
} | Out-Null
}
}
Else {
#Start WSUS synchronization
If ($pscmdlet.ShouldProcess($($wsus.name))) {
$sub.StartSynchronization()
"Synchronization have been started."
}
}
}
function Stop-WSUSSync {
<#
.SYNOPSIS
Stops a currently running WSUS sync.
.DESCRIPTION
Stops a currently running WSUS sync.
.NOTES
Name: Stop-WSUSSync
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Stop-WSUSSync
Description
-----------
This command will stop a currently running WSUS synchronization.
#>
[cmdletbinding(
DefaultParameterSetName = 'update',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param()
$sub = $wsus.GetSubscription()
#Cancel synchronization running on WSUS
If ($pscmdlet.ShouldProcess($($wsus.name))) {
$sub.StopSynchronization()
"Synchronization have been cancelled."
}
}
function Get-WSUSSyncHistory {
<#
.SYNOPSIS
Retrieves the synchronization history of the WSUS server.
.DESCRIPTION
Retrieves the synchronization history of the WSUS server.
.NOTES
Name: Get-WSUSSyncHistory
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSSyncHistory
Description
-----------
This command will list out the entire synchronization history of the WSUS server.
#>
[cmdletbinding()]
Param ()
$sub = $wsus.GetSubscription()
$sub.GetSynchronizationHistory()
}
function Get-WSUSSyncProgress {
<#
.SYNOPSIS
Displays the current progress of a WSUS synchronization.
.DESCRIPTION
Displays the current progress of a WSUS synchronization.
.PARAMETER Monitor
Runs a background job to monitor currently running synchonization and notifies user when completed.
.NOTES
Name: Get-WSUSSyncProgress
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSSyncProgress
Description
-----------
This command will show you the current status of the WSUS sync.
.EXAMPLE
Get-WSUSSyncProgress -monitor
Description
-----------
This command will begin a background job that will notify you when the WSUS synchronization
has been completed.
#>
[cmdletbinding()]
Param (
[Parameter(
Mandatory = $False,
Position = 0,
ParameterSetName = 'monitor',
ValueFromPipeline = $False)]
[switch]$Monitor
)
$sub = $wsus.GetSubscription()
If ($monitor) {
$job = Get-Job
If ($job) {
$job = Get-Job -Name "WSUSSyncProgressMonitor"
}
If ($job) {
Get-Job -Name "WSUSSyncProgressMonitor" | Stop-Job
Get-Job -Name "WSUSSyncProgressMonitor" | Remove-Job
}
Start-Job -Name "WSUSSyncProgressMonitor" -ArgumentList $sub -ScriptBlock {
Param (
$sub
)
#Load required assemblies for message window
[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
While (($sub.GetSynchronizationProgress()).Phase -ne "NotProcessing") {
$null
}
[System.Windows.Forms.MessageBox]::Show("Synchronization has been completed on WSUS",”Information”)
} | Out-Null
}
Else {
#Gather all child servers in WSUS
$sub.GetSynchronizationProgress()
}
}
function Get-WSUSEvents {
<#
.SYNOPSIS
Retrieves all WSUS events.
.DESCRIPTION
Retrieves all WSUS events from the WSUS server.
.NOTES
Name: Get-WSUSEvents
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSEvents
Description
-----------
This command will show you all of the WSUS events.
#>
[cmdletbinding()]
Param ()
$sub = $wsus.GetSubscription()
$sub.GetEventHistory()
}
function Get-WSUSGroups {
<#
.SYNOPSIS
Retrieves all of the WSUS Target Groups.
.DESCRIPTION
Retrieves all of the WSUS Target Groups.
.NOTES
Name: Get-WSUSGroups
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSGroups
Description
-----------
This command will list out all of the WSUS Target groups and their respective IDs.
#>
[cmdletbinding()]
Param ()
$wsus.GetComputerTargetGroups()
}
function Get-WSUSServer {
<#
.SYNOPSIS
Retrieves connection and configuration information from the WSUS server.
.DESCRIPTION
Retrieves connection and configuration information from the WSUS server.
.PARAMETER Configuration
Lists more configuration information from WSUS Server
.NOTES
Name: Get-WSUSServer
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSServer
Description
-----------
This command will display basic information regarding the WSUS server.
.EXAMPLE
Get-WSUSServer -configuration
Description
-----------
This command will list out more detailed information regarding the configuration of the WSUS server.
#>
[cmdletbinding(
DefaultParameterSetName = 'wsus',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $False,
Position = 0,
ParameterSetName = 'wsus',
ValueFromPipeline = $False)]
[switch]$Configuration
)
If ($configuration) {
$wsus.GetConfiguration()
}
Else {
$wsus
}
}
function Get-WSUSUpdates {
<#
.SYNOPSIS
Retrieves all of the updates from a WSUS server.
.DESCRIPTION
Retrieves all of the updates from a WSUS server.
.NOTES
Name: Get-WSUSUpdates
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSUpdates
Description
-----------
This command will list out every update that is in WSUS's database whether it has been approved or not.
#>
[cmdletbinding()]
Param ()
$wsus.GetUpdates()
}
function Get-WSUSEmailConfig {
<#
.SYNOPSIS
Retrieves the email notification configuration from WSUS.
.DESCRIPTION
Retrieves the email notification configuration from WSUS.
.PARAMETER SendTestEmail
Optional switch that will send a test email to the configured email addresses
.NOTES
Name: Get-WSUSEmailConfig
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSEmailConfig
Description
-----------
This command will display the configuration of the email notifications.
.EXAMPLE
Get-WSUSEmailConfig -SendTestEmail
Description
-----------
This command will send a test email to the address or addresses in the To field.
#>
[cmdletbinding(
DefaultParameterSetName = 'wsus',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $False,
Position = 0,
ParameterSetName = 'wsus',
ValueFromPipeline = $False)]
[switch]$SendTestEmail
)
$email = $wsus.GetEmailNotificationConfiguration()
If ($SendTestEmail) {
$email.SendTestEmail()
Write-Host -fore Green "Test email sent."
}
Else {
$email
}
}
function Get-WSUSUpdateCategories {
<#
.SYNOPSIS
Retrieves the list of Update categories available from WSUS.
.DESCRIPTION
Retrieves the list of Update categories available from WSUS.
.NOTES
Name: Get-WSUSUpdateCategories
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSUpdateCategories
Description
-----------
This command will list all of the categories for updates in WSUS.
#>
[cmdletbinding()]
Param ()
$wsus.GetUpdateCategories()
}
function Get-WSUSStatus {
<#
.SYNOPSIS
Retrieves a list of all updates and their statuses along with computer statuses.
.DESCRIPTION
Retrieves a list of all updates and their statuses along with computer statuses.
.NOTES
Name: Get-WSUSStatus
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSStatus
Description
-----------
This command will display the status of the WSUS server along with update statuses.
#>
[cmdletbinding()]
Param ()
$wsus.getstatus()
}
function Set-WSUSEmailConfig {
<#
.SYNOPSIS
Configures the email notifications on a WSUS server.
.DESCRIPTION
Configures the email notifications on a WSUS server. It is important to note that the email address to send
the emails to is Read-Only and can only be configured from the WSUS Admin Console. After the settings have been
changed, the new configuration will be displayed.
.PARAMETER EmailLanguage
What type of language to send the email in.
.PARAMETER SenderDisplayName
The friendly name of where the email is coming from.
.PARAMETER SenderEmailAddress
The senders email address
.PARAMETER SendStatusNotification
Determines if an email will be sent for a status notification
.PARAMETER SendSyncnotification
Determines if an email will be sent after a sync by WSUS
.PARAMETER SMTPHostname
Server name of the smtp server to send email from
.PARAMETER SMTPPort
Port number to be used to connect to smtp server to send email
.PARAMETER SmtpServerRequiresAuthentication
Used if smtp server requires authentication
.PARAMETER SmtpUserName
Username to submit if required by smtp server
.PARAMETER StatusNotificationFrequency
Frequency (Daily or Weekly) to send notifications
.PARAMETER StatusNotificationTimeOfDay
Date/Time to send notifications
.PARAMETER UpdateServer
Name of the WSUS update server
.PARAMETER SmtpPassword
Password to user for smtp server connection.
.NOTES
Name: Set-WSUSEmailConfig
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Set-WSUSEmailConfig -SenderDisplayName "WSUSAdmin" -SenderEmailAddress "wsusadmin@domain.com"
Description
-----------
This command will change the sender name and email address for email notifications and then display the new settings.
#>
[cmdletbinding(
DefaultParameterSetName = 'wsus',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $False, Position = 0,
ParameterSetName = '', ValueFromPipeline = $False)]
[string]$EmailLanguage,
[Parameter(
Mandatory = $False, Position = 1,
ParameterSetName = '', ValueFromPipeline = $False)]
[string]$SenderDisplayName,
[Parameter(
Mandatory = $False, Position = 2,
ParameterSetName = '', ValueFromPipeline = $False)]
[string]$SenderEmailAddress,
[Parameter(
Mandatory = $False, Position = 3,
ParameterSetName = '', ValueFromPipeline = $False)]
[string][ValidateSet("True","False")]$SendStatusNotification,
[Parameter(
Mandatory = $False, Position = 4,
ParameterSetName = '',ValueFromPipeline = $False)]
[string][ValidateSet("True","False")]$SendSyncnotification,
[Parameter(
Mandatory = $False, Position = 5,
ParameterSetName = '', ValueFromPipeline = $False)]
[string]$SMTPHostname,
[Parameter(
Mandatory = $False, Position = 6,
ParameterSetName = '', ValueFromPipeline = $False)]
[int]$SMTPPort,
[Parameter(
Mandatory = $False, Position = 7,
ParameterSetName = '', ValueFromPipeline = $False)]
[string][ValidateSet("True","False")]$SmtpServerRequiresAuthentication,
[Parameter(
Mandatory = $False, Position = 8,
ParameterSetName = 'account', ValueFromPipeline = $False)]
[string]$SmtpUserName,
[Parameter(
Mandatory = $False, Position = 9,
ParameterSetName = '', ValueFromPipeline = $False)]
[string][ValidateSet("Daily","Weekly")]$StatusNotificationFrequency,
[Parameter(
Mandatory = $False, Position = 10,
ParameterSetName = '', ValueFromPipeline = $False)]
[string]$StatusNotificationTimeOfDay,
[Parameter(
Mandatory = $False,Position = 11,
ParameterSetName = '',ValueFromPipeline = $False)]
[string]$UpdateServer,
[Parameter(
Mandatory = $False,Position = 12,
ParameterSetName = 'account',ValueFromPipeline = $False)]
[string]$SmtpPassword
)
#Configure Email Notifications
$email = $wsus.GetEmailNotificationConfiguration()
$ErrorActionPreference = 'stop'
Try {
If ($StatusNotificationTimeOfDay) {
#Validate Notification Time of Day Parameter
If (!([regex]::ismatch($StatusNotificationTimeOfDay,"^\\d{2}:\\d{2}$"))) {
Write-Error "$($StatusNotificationTimeOfDay) is not a valid time to use!`nMust be 'NN:NN'"
}
Else {
$email.StatusNotificationTimeOfDay = $StatusNotificationTimeOfDay
}
}
If ($UpdateServer) {$email.UpdateServer = $UpdateServer}
If ($EmailLanguage) {$email.EmailLanguage = $EmailLanguage}
If ($SenderDisplayName) {$email.SenderDisplayName = $SenderDisplayName}
If ($SenderEmailAddress) {
#Validate Email Address Parameter
If (!([regex]::ismatch($SenderEmailAddress,"^\\w+@\\w+\\.com|mil|org|net$"))) {
Write-Error "$($SenderEmailAddress) is not a valid email address!`nMust be 'xxxx@xxxxx.xxx'"
}
Else {
$email.SenderEmailAddress = $SenderEmailAddress
}
}
If ($SMTPHostname) {$email.SMTPHostname = $SMTPHostname}
If ($SMTPPort) {$email.SMTPPort = $SMTPPort}
If ($SmtpServerRequiresAuthentication) {$email.SmtpServerRequiresAuthentication = $SmtpServerRequiresAuthentication}
If ($SmtpUserName) {$email.SmtpUserName = $SmtpUserName}
If ($SmtpPassword) {$mail.SetSmtpUserPassword($SmtpPassword)}
Switch ($StatusNotificationFrequency) {
"Daily" {$email.StatusNotificationFrequency = [Microsoft.UpdateServices.Administration.EmailStatusNotificationFrequency]::Daily}
"Weekly" {$email.StatusNotificationFrequency = [Microsoft.UpdateServices.Administration.EmailStatusNotificationFrequency]::Weekly}
Default {$Null}
}
Switch ($SendStatusNotification) {
"True" {$email.SendStatusNotification = 1}
"False" {$email.SendStatusNotification = 0}
Default {$Null}
}
Switch ($SendSyncNotification) {
"True" {$email.SendSyncNotification = 1}
"False" {$email.SendSyncNotification = 0}
Default {$Null}
}
}
Catch {
Write-Error "$($error[0])"
}
#Save Configuration Changes
Try {
$email.Save()
Write-Host -fore Green "Email settings changed"
$email
}
Catch {
Write-Error "$($error[0])"
}
}
function Convert-WSUSTargetGroup {
<#
.SYNOPSIS
Converts the WSUS group from ID to Name or Name to ID.
.DESCRIPTION
Converts the WSUS group from ID to Name or Name to ID.
.PARAMETER Id
GUID of the group to be converted to friendly name
.PARAMETER Name
Name of the group to be converted to a guid
.NOTES
Name: Convert-WSUSTargetGroup
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Convert-WSUSTargetGroup -name "Domain Servers"
Description
-----------
This command will convert the group name "Domain Servers" into the GUID format.
.EXAMPLE
Convert-WSUSTargetGroup -ID "b73ca6ed-5727-47f3-84de-015e03f6a88a"
Description
-----------
This command will convert the given GUID into a friendly name.
#>
[cmdletbinding(
DefaultParameterSetName = 'name',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $False,
Position = 2,
ParameterSetName = 'id',
ValueFromPipeline = $False)]
[string]$Id,
[Parameter(
Mandatory = $False,
Position = 3,
ParameterSetName = 'name',
ValueFromPipeline = $False)]
[string]$Name
)
If ($name) {
Try {
$group = $wsus.GetComputerTargetGroups() | ? {$_.Name -eq $name}
$group | Select -ExpandProperty ID
}
Catch {
Write-Error "Unable to locate $($name)."
}
}
If ($id) {
Try {
$group = $wsus.GetComputerTargetGroups() | ? {$_.ID -eq $id}
$group | Select -ExpandProperty Name
}
Catch {
Write-Error "Unable to locate $($id)."
}
}
}
function Get-WSUSClientsInGroup {
<#
.SYNOPSIS
Retrieves a list of clients that are members of a group.
.DESCRIPTION
Retrieves a list of clients that are members of a group.
.PARAMETER Id
Retrieves list of clients in group by group guid.
.PARAMETER Name
Retrieves list of clients in group by group name.
.NOTES
Name: Get-WSUSClientsInGroup
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSClientsInGroup -name "Domain Servers"
Description
-----------
This command will list all clients that are members of the specified group via group name.
.EXAMPLE
Get-WSUSClientsInGroup -ID "b73ca6ed-5727-47f3-84de-015e03f6a88a"
Description
-----------
This command will list all clients that are members of the specified group via the group guid.
#>
[cmdletbinding(
DefaultParameterSetName = 'name',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $False,
Position = 2,
ParameterSetName = 'name',
ValueFromPipeline = $False)]
[string]$Name,
[Parameter(
Mandatory = $False,
Position = 3,
ParameterSetName = 'id',
ValueFromPipeline = $False)]
[string]$Id
)
If ($id) {
($wsus.GetComputerTargetGroups() | ? {$_.Id -eq $id}).GetComputerTargets()
}
If ($name) {
($wsus.GetComputerTargetGroups() | ? {$_.name -eq $name}).GetComputerTargets()
}
}
function Get-WSUSClient {
<#
.SYNOPSIS
Retrieves information about a WSUS client.
.DESCRIPTION
Retrieves information about a WSUS client.
.PARAMETER Computer
Name of the client to search for. Accepts a partial name.
.NOTES
Name: Get-WSUSClient
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSClient -computer "server1"
Description
-----------
This command will search for and display all computers matching the given input.
#>
[cmdletbinding(
DefaultParameterSetName = 'wsus',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'wsus',
ValueFromPipeline = $True)]
[string]$Computer
)
$ErrorActionPreference = 'stop'
#Retrieve computer in WSUS
Try {
$wsus.SearchComputerTargets($computer)
}
Catch {
Write-Error "Unable to retrieve $($computer) from database."
}
}
function New-WSUSGroup {
<#
.SYNOPSIS
Creates a new WSUS Target group.
.DESCRIPTION
Creates a new WSUS Target group.
.PARAMETER Group
Name of group being created.
.PARAMETER ParentGroupName
Name of group being created.
.PARAMETER ParentGroupId
Name of group being created.
.NOTES
Name: New-WSUSGroup
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
New-WSUSGroup -name "TestGroup"
Description
-----------
This command will create a new Target group called 'TestGroup'
.EXAMPLE
New-WSUSGroup -name "TestGroup" -parentgroupname "Domain Servers"
Description
-----------
This command will create a new Target group called 'TestGroup' under the parent group 'Domain Servers'
#>
[cmdletbinding(
DefaultParameterSetName = 'group',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string]$Group,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = 'parentgroup',
ValueFromPipeline = $True)]
[string]$ParentGroupName,
[Parameter(
Mandatory = $False,
Position = 2,
ParameterSetName = 'parentgroup',
ValueFromPipeline = $True)]
[string]$ParentGroupId
)
Process {
#Determine action based on Parameter Set Name
Switch ($pscmdlet.ParameterSetName) {
"group" {
Write-Verbose "Creating computer group"
If ($pscmdlet.ShouldProcess($group)) {
#Create the computer target group
$wsus.CreateComputerTargetGroup($group)
"$($group) has been created."
}
}
"parentgroup" {
If ($parentgroupname) {
#Retrieve group based off of name
Write-Verbose "Querying for parent group"
$parentgroup = Get-WSUSGroups | ? {$_.name -eq $parentgroupname}
If (!$parentgroup) {
Write-Error "Parent Group name `'$parentgroupname`' does not exist in WSUS!"
Break
}
}
If ($parentgroupid) {
#Retrieve group based off of guid
Write-Verbose "Querying for parent group"
$parentgroup = Get-WSUSGroups | ? {$_.id -eq $parentgroupid}
If (!$parentgroup) {
Write-Error "Parent Group id `'$parentgroupid`' does not exist in WSUS!"
Break
}
}
Write-Verbose "Creating computer group"
If ($pscmdlet.ShouldProcess($group)) {
#Create the computer target group
$wsus.CreateComputerTargetGroup($group,$parentgroup)
"$($group) has been created under $($parentgroup.Name)."
}
}
}
}
}
function Get-WSUSUpdate {
<#
.SYNOPSIS
Retrieves information from a wsus update.
.DESCRIPTION
Retrieves information from a wsus update. Depending on how the information is presented in the search, more
than one update may be returned.
.PARAMETER Update
String to search for. This can be any string for the update to include
KB article numbers, name of update, category, etc... Use of wildcards (*,%) not allowed in search!
.NOTES
Name: Get-WSUSUpdate
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSUpdate -update "Exchange"
Description
-----------
This command will list every update that has 'Exchange' in it.
.EXAMPLE
Get-WSUSUpdate -update "925474"
Description
-----------
This command will list every update that has '925474' in it.
#>
[cmdletbinding(
DefaultParameterSetName = 'wsus',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'wsus',
ValueFromPipeline = $True)]
[string]$Update
)
$ErrorActionPreference = 'stop'
#Retrieve computer in WSUS
Try {
$wsus.SearchUpdates($update)
}
Catch {
Write-Error "Unable to retrieve $($update) from database."
}
}
function Remove-WSUSGroup {
<#
.SYNOPSIS
Creates a new WSUS Target group.
.DESCRIPTION
Creates a new WSUS Target group.
.PARAMETER Name
Name of group being deleted.
.PARAMETER Id
Id of group being deleted.
.NOTES
Name: Remove-WSUSGroup
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Remove-WSUSGroup -name "Domain Servers"
Description
-----------
This command will remove the Domain Servers WSUS Target group.
.EXAMPLE
Remove-WSUSGroup -id "fc93e74e-ba59-4593-9ff7-690af1be695f"
Description
-----------
This command will remove the Target group with ID 'fc93e74e-ba59-4593-9ff7-690af1be695f' from WSUS.
#>
[cmdletbinding(
DefaultParameterSetName = 'name',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $False,
Position = 0,
ParameterSetName = 'name',
ValueFromPipeline = $True)]
[string]$Name,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = 'id',
ValueFromPipeline = $True)]
[string]$Id
)
Process {
#Determine action based on Parameter Set Name
Switch ($pscmdlet.ParameterSetName) {
"name" {
Write-Verbose "Querying for computer group"
$group = Get-WSUSGroup -name $name
If (!$group) {
Write-Error "Group $name does not exist in WSUS!"
Break
}
Else {
If ($pscmdlet.ShouldProcess($name)) {
#Create the computer target group
$group.Delete()
"$($name) has been deleted from WSUS."
}
}
}
"id" {
Write-Verbose "Querying for computer group"
$group = Get-WSUSGroup -id $id
If (!$group) {
Write-Error "Group $id does not exist in WSUS!"
Break
}
If ($pscmdlet.ShouldProcess($id)) {
#Create the computer target group
$group.Delete()
"$($id) has been deleted from WSUS."
}
}
}
}
}
function Add-WSUSClientToGroup {
<#
.SYNOPSIS
Adds a computer client to an existing WSUS group.
.DESCRIPTION
Adds a computer client to an existing WSUS group.
.PARAMETER Group
Name of group to add client to.
.PARAMETER Computer
Name of computer being added to group.
.NOTES
Name: Add-WSUSClientToGroup
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Add-WSUSClientToGroup -group "Domain Servers" -computer "server1"
Description
-----------
This command will add the client "server1" to the WSUS target group "Domain Servers".
#>
[cmdletbinding(
DefaultParameterSetName = 'group',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'group',
ValueFromPipeline = $True)]
[string]$Group,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = 'group',
ValueFromPipeline = $True)]
[string]$Computer
)
#Verify Computer is in WSUS
Write-Verbose "Validating client in WSUS"
$client = Get-WSUSClient -computer $computer
If ($client) {
#Get group object
Write-Verbose "Retrieving group"
$targetgroup = Get-WSUSGroup -name $group
If (!$targetgroup) {
Write-Error "Group $group does not exist in WSUS!"
Break
}
#Add client to group
Write-Verbose "Adding client to group"
If ($pscmdlet.ShouldProcess($($client.fulldomainname))) {
$targetgroup.AddComputerTarget($client)
"$($client.FullDomainName) has been added to $($group)"
}
}
Else {
Write-Error "Computer: $computer is not in WSUS!"
}
}
function Remove-WSUSClientFromGroup {
<#
.SYNOPSIS
Removes a computer client to an existing WSUS group.
.DESCRIPTION
Removes a computer client to an existing WSUS group.
.PARAMETER Group
Name of group to remove client from.
.PARAMETER Computer
Name of computer being removed from group.
.NOTES
Name: Remove-WSUSClientToGroup
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Remove-WSUSClientFromGroup -group "Domain Servers" -computer "server1"
Description
-----------
This command will remove the client "server1" from the WSUS target group "Domain Servers".
#>
[cmdletbinding(
DefaultParameterSetName = 'group',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'group',
ValueFromPipeline = $True)]
[string]$Group,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = 'group',
ValueFromPipeline = $True)]
[string]$Computer
)
#Verify Computer is in WSUS
$client = Get-WSUSClient -computer $computer
If ($client) {
#Get group object
Write-Verbose "Retrieving group"
$targetgroup = Get-WSUSGroup -name $group
If (!$targetgroup) {
Write-Error "Group $group does not exist in WSUS!"
Break
}
#Remove client from group
Write-Verbose "Removing client to group"
If ($pscmdlet.ShouldProcess($($client.fulldomainname))) {
$targetgroup.RemoveComputerTarget($client)
"$($client.fulldomainname) has been removed from $($group)"
}
}
Else {
Write-Error "Computer: $computer is not in WSUS!"
}
}
function Get-WSUSDatabaseConfig {
<#
.SYNOPSIS
Displays the current WSUS database configuration.
.DESCRIPTION
Displays the current WSUS database configuration.
.NOTES
Name: Get-WSUSDatabaseConfig
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSDatabaseConfig
Description
-----------
This command will display the configuration information for the WSUS connection to a database.
#>
[cmdletbinding()]
Param ()
$wsus.GetDatabaseConfiguration()
}
function Get-WSUSSubscription {
<#
.SYNOPSIS
Displays WSUS subscription information.
.DESCRIPTION
Displays WSUS subscription information. You can view the next synchronization time, who last modified the schedule, etc...
.NOTES
Name: Get-WSUSSubscription
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSSubscription
Description
-----------
This command will list out the various subscription information on the WSUS server.
#>
[cmdletbinding()]
Param ()
$wsus.GetSubscription()
}
function Deny-WSUSUpdate {
<#
.SYNOPSIS
Declines an update on WSUS.
.DESCRIPTION
Declines an update on WSUS. Use of the -whatif is advised to be sure you are declining the right patch or patches.
.PARAMETER InputObject
Collection of update/s being declined. This must be an object, otherwise it will fail.
.PARAMETER Update
Name of update/s being declined.
.NOTES
Name: Deny-WSUSUpdate
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSUpdate -update "Exchange 2010" | Deny-WSUSUpdate
Description
-----------
This command will decline all updates with 'Exchange 2010' in its metadata.
.EXAMPLE
Deny-WSUSUpdate -Update "Exchange 2010"
Description
-----------
This command will decline all updates with 'Exchange 2010' in its metadata.
.EXAMPLE
$updates = Get-WSUSUpdate -update "Exchange 2010"
Deny-WSUSUpdate -InputObject $updates
Description
-----------
This command will decline all updates with 'Exchange 2010' in its metadata.
.EXAMPLE
Get-WSUSUpdate -update "Exchange 2010" | Deny-WSUSUpdate
Description
-----------
This command will decline all updates with 'Exchange 2010' in its metadata via the pipeline.
#>
[cmdletbinding(
DefaultParameterSetName = 'collection',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'collection',
ValueFromPipeline = $True)]
[system.object]$InputObject,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = 'string',
ValueFromPipeline = $False)]
[string]$Update
)
Process {
Switch ($pscmdlet.ParameterSetName) {
"Collection" {
Write-Verbose "Using 'Collection' set name"
#Change the collection to patches for use in loop
$patches = $inputobject
}
"String" {
Write-Verbose "Using 'String' set name"
#Gather all updates from given information
Write-Verbose "Searching for updates"
$patches = Get-WSUSUpdate -update $update
}
}
ForEach ($patch in $patches) {
#Decline the update
Write-Verbose "Declining update"
If ($pscmdlet.ShouldProcess($($patch.title))) {
$patch.Decline($True) | out-null
#Print out report of what was declined
New-Object PSObject -Property @{
Patch = $patch.title
ApprovalAction = "Declined"
}
}
}
}
}
function Approve-WSUSUpdate {
<#
.SYNOPSIS
Approves a WSUS update for a specific group with an optional deadline.
.DESCRIPTION
Approves a WSUS update for a specific group with an optional deadline.
.PARAMETER InputObject
Update object that is being approved.
.PARAMETER Update
Name of update being approved.
.PARAMETER Group
Name of group which will receive the update.
.PARAMETER Deadline
Optional deadline for client to install patch.
.PARAMETER Action
Type of approval action to take on update. Accepted values are Install, Approve, Uninstall and NotApproved
.NOTES
Name: Approve-WSUSUpdate
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Approve-WSUSUpdate -update "KB979906" -Group "Domain Servers" -Action Install
Description
-----------
This command will approve all updates with the KnowledgeBase number of KB979906 for the 'Domain Servers' group and
the action command of 'Install'.
.EXAMPLE
Approve-WSUSUpdate -update "KB979906" -Group "Domain Servers" -Action Install -Deadline (get-Date).AddDays(3)
Description
-----------
This command will approve all updates with the KnowledgeBase number of KB979906 for the 'Domain Servers' group and
the action command of 'Install' and sets a deadline for 3 days from when this command is run.
.EXAMPLE
Get-WSUSUpdate -Update "KB979906" | Approve-WSUSUpdate -Group "Domain Servers" -Action Install
Description
-----------
This command will take the collection of objects from the Get-WSUSUpdate command and then approve all updates for
the 'Domain Servers' group and the action command of 'Install'.
#>
[cmdletbinding(
DefaultParameterSetName = 'string',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'collection',
ValueFromPipeline = $True)]
[system.object]
[ValidateNotNullOrEmpty()]
$InputObject,
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'string',
ValueFromPipeline = $False)]
[string]$Update,
[Parameter(
Mandatory = $True,
Position = 1,
ParameterSetName = '',
ValueFromPipeline = $False)]
[string]
[ValidateSet("Install", "All", "NotApproved","Uninstall")]
$Action,
[Parameter(
Mandatory = $True,
Position = 2,
ParameterSetName = '',
ValueFromPipeline = $False)]
[string]$Group,
[Parameter(
Mandatory = $False,
Position = 3,
ParameterSetName = '',
ValueFromPipeline = $False)]
[datetime]$Deadline
)
Begin {
#Define the actions available
Write-Verbose "Defining available approval actions"
$Install = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::Install
$All = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::All
$NotApproved = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::NotApproved
$Uninstall = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::Uninstall
#Search for group specified
Write-Verbose "Searching for group"
$targetgroup = Get-WSUSGroup -name $group
If (!$targetgroup) {
Write-Error "Group $group does not exist in WSUS!"
Break
}
}
Process {
#Perform appropriate action based on Parameter set name
Switch ($pscmdlet.ParameterSetName) {
"collection" {
Write-Verbose "Using 'Collection' set name"
#Change the variable that will hold the objects
$patches = $inputobject
}
"string" {
Write-Verbose "Using 'String' set name"
#Search for updates
Write-Verbose "Searching for update/s"
$patches = Get-WSUSUpdate -update $update
If (!$patches) {
Write-Error "Update $update could not be found in WSUS!"
Break
}
}
}
ForEach ($patch in $patches) {
#Determine if Deadline is required
If ($deadline) {
Write-Verbose "Approving update with a deadline."
If ($pscmdlet.ShouldProcess($($patch.title))) {
#Create the computer target group
$patch.Approve($action,$targetgroup,$deadline) | out-null
#Print out report of what was approved
New-Object PSObject -Property @{
Patch = $patch.title
TargetGroup = $group
ApprovalAction = $action
Deadline = "$($deadline)"
}
}
}
Else {
#Approve the patch
Write-Verbose "Approving update without a deadline."
If ($pscmdlet.ShouldProcess($($patch.title))) {
#Create the computer target group
$patch.Approve($action,$targetgroup) | out-null
#Print out report of what was approved
New-Object PSObject -Property @{
Patch = $patch.title
TargetGroup = $group
ApprovalAction = $action
}
}
}
}
}
}
function Get-WSUSGroup {
<#
.SYNOPSIS
Retrieves specific WSUS target group.
.DESCRIPTION
Retrieves specific WSUS target group.
.PARAMETER Name
Name of group to search for. No wildcards allowed.
.PARAMETER Id
GUID of group to search for. No wildcards allowed.
.NOTES
Name: Get-WSUSGroups
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSGroup -name "Domain Servers"
Description
-----------
This command will search for the group and display the information for Domain Servers"
.EXAMPLE
Get-WSUSGroup -ID "0b5ba818-021e-4238-8098-7245b0f90557"
Description
-----------
This command will search for the group and display the information for the WSUS
group guid 0b5ba818-021e-4238-8098-7245b0f90557"
#>
[cmdletbinding(
DefaultParameterSetName = 'name',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'name',
ValueFromPipeline = $False)]
[string]$Name,
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'id',
ValueFromPipeline = $False)]
[string]$Id
)
Switch ($pscmdlet.ParameterSetName) {
"name" {$wsus.GetComputerTargetGroups() | ? {$_.name -eq $name}}
"id" {$wsus.GetComputerTargetGroups() | ? {$_.id -eq $id}}
}
}
function Remove-WSUSUpdate {
<#
.SYNOPSIS
Removes an update on WSUS.
.DESCRIPTION
Removes an update on WSUS. Use of the -whatif is advised to be sure you are declining the right patch or patches.
.PARAMETER Update
Name of update being removed.
.NOTES
Name: Remove-WSUSUpdate
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Remove-WSUSUpdate -update "KB986569"
Description
-----------
This command will remove all instances of KB986569 from WSUS.
#>
[cmdletbinding(
DefaultParameterSetName = 'update',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'update',
ValueFromPipeline = $True)]
[string]$Update
)
Begin {
#Gather all updates from given information
Write-Verbose "Searching for updates"
$patches = Get-WSUSUpdate -update $update
}
Process {
ForEach ($patch in $patches) {
#Storing update guid
$guid = ($patch.id).updateid
If ($pscmdlet.ShouldProcess($($patch.title))) {
$wsus.DeleteUpdate($id,$True)
"$($patch.title) has been deleted from WSUS"
}
}
}
}
function Stop-WSUSDownloads {
<#
.SYNOPSIS
Cancels all current WSUS downloads.
.DESCRIPTION
Cancels all current WSUS downloads.
.NOTES
Name: Stop-WSUSDownloads
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Stop-WSUSDownloads
Description
-----------
This command will stop all updates being downloaded to the WSUS server.
#>
[cmdletbinding(
DefaultParameterSetName = 'update',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param()
#Cancel all downloads running on WSUS
If ($pscmdlet.ShouldProcess($($wsus.name))) {
$wsus.CancelAllDownloads()
"Downloads have been cancelled."
}
}
function Resume-WSUSDownloads {
<#
.SYNOPSIS
Resumes all current WSUS downloads.
.DESCRIPTION
Resumes all current WSUS downloads that had been cancelled.
.NOTES
Name: Resume-WSUSDownloads
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Resume-WSUSDownloads
Description
-----------
This command will resume the downloading of updates to the WSUS server.
#>
[cmdletbinding(
DefaultParameterSetName = 'update',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param()
#Cancel all downloads running on WSUS
If ($pscmdlet.ShouldProcess($($wsus.name))) {
$wsus.ResumeAllDownloads()
"Downloads have been resumed."
}
}
function Stop-WSUSUpdateDownload {
<#
.SYNOPSIS
Stops update download after approval.
.DESCRIPTION
Stops update download after approval.
.PARAMETER update
Name of update to cancel download.
.NOTES
Name: Stop-WSUSUpdateDownload
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Stop-WSUSUpdateDownload -update "KB965896"
Description
-----------
This command will cancel the download of update KB956896.
#>
[cmdletbinding(
DefaultParameterSetName = 'update',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'update',
ValueFromPipeline = $True)]
[string]$update
)
Begin {
#Gather all updates from given information
Write-Verbose "Searching for updates"
$patches = Get-WSUSUpdate -update $update
}
Process {
If ($patches) {
ForEach ($patch in $patches) {
Write-Verbose "Cancelling update download"
If ($pscmdlet.ShouldProcess($($patch.title))) {
$patch.CancelDownload()
"$($patch.title) download has been cancelled."
}
}
}
Else {
Write-Warning "No patches found that need downloading cancelled."
}
}
}
function Resume-WSUSUpdateDownload {
<#
.SYNOPSIS
Resumes previously cancelled update download after approval.
.DESCRIPTION
Resumes previously cancelled update download after approval.
.PARAMETER Update
Name of cancelled update download to resume download.
.NOTES
Name: Resume-WSUSUpdateDownload
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Resume-WSUSUpdateDownload -update "KB965896"
Description
-----------
This command will resume the download of update KB956896 that was previously cancelled.
#>
[cmdletbinding(
DefaultParameterSetName = 'update',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'update',
ValueFromPipeline = $True)]
[string]$Update
)
Begin {
#Gather all updates from given information
Write-Verbose "Searching for updates"
$patches = Get-WSUSUpdate -update $update
}
Process {
If ($patches) {
ForEach ($patch in $patches) {
Write-Verbose "Resuming update download"
If ($pscmdlet.ShouldProcess($($patch.title))) {
$patch.ResumeDownload()
"$($patch.title) download has been resumed."
}
}
}
Else {
Write-Warning "No patches found needing to resume download!"
}
}
}
function Start-WSUSCleanup {
<#
.SYNOPSIS
Performs a cleanup on WSUS based on user inputs.
.DESCRIPTION
Performs a cleanup on WSUS based on user inputs.
.PARAMETER DeclineSupersededUpdates
Declined Superseded Updates will be removed.
.PARAMETER DeclineExpiredUpdates
Expired updates should be declined.
.PARAMETER CleanupObsoleteUpdates
Delete obsolete updates from the database.
.PARAMETER CompressUpdates
Obsolete revisions to updates should be deleted from the database.
.PARAMETER CleanupObsoleteComputers
Delete obsolete computers from the database.
.PARAMETER CleanupUnneededContentFiles
Delete unneeded update files.
.NOTES
Name: Start-WSUSCleanup
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Start-WSUSCleanup -CompressUpdates -CleanupObsoleteComputers
Description
-----------
This command will run the WSUS cleanup wizard and delete obsolete computers from the database and delete obsolete update
revisions from the database.
.EXAMPLE
Start-WSUSCleanup -CompressUpdates -CleanupObsoleteComputers -DeclineExpiredUpdates -CleanupObsoleteUpdates -CleanupUnneededContentFiles
Description
-----------
This command performs a full WSUS cleanup against the database.
#>
[cmdletbinding(
DefaultParameterSetName = 'cleanup',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $False,
Position = 0,
ParameterSetName = 'cleanup',
ValueFromPipeline = $False)]
[switch]$DeclineSupersededUpdates,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = 'cleanup',
ValueFromPipeline = $False)]
[switch]$DeclineExpiredUpdates,
[Parameter(
Mandatory = $False,
Position = 2,
ParameterSetName = 'cleanup',
ValueFromPipeline = $False)]
[switch]$CleanupObsoleteUpdates,
[Parameter(
Mandatory = $False,
Position = 3,
ParameterSetName = 'cleanup',
ValueFromPipeline = $False)]
[switch]$CompressUpdates,
[Parameter(
Mandatory = $False,
Position = 4,
ParameterSetName = 'cleanup',
ValueFromPipeline = $False)]
[switch]$CleanupObsoleteComputers,
[Parameter(
Mandatory = $False,
Position = 5,
ParameterSetName = 'cleanup',
ValueFromPipeline = $False)]
[switch]$CleanupUnneededContentFiles
)
Begin {
#Create cleanup scope
$cleanScope = new-object Microsoft.UpdateServices.Administration.CleanupScope
#Create cleanup manager object
$cleanup = $wsus.GetCleanupManager()
#Determine what will be in the scope
If ($DeclineSupersededUpdates) {
$cleanScope.DeclineSupersededUpdates = $True
}
If ($DeclineExpiredUpdates) {
$cleanScope.DeclineExpiredUpdates = $True
}
If ($CleanupObsoleteUpdates) {
$cleanScope.CleanupObsoleteUpdates = $True
}
If ($CompressUpdates) {
$cleanScope.CompressUpdates = $True
}
If ($CleanupObsoleteComputers) {
$cleanScope.CleanupObsoleteComputers = $True
}
If ($CleanupUnneededContentFiles) {
$cleanScope.CleanupUnneededContentFiles = $True
}
}
Process {
Write-Host "Beginning cleanup"
If ($pscmdlet.ShouldProcess($($wsus.name))) {
$cleanup.PerformCleanup($cleanScope)
}
}
}
function Get-WSUSChildServers {
<#
.SYNOPSIS
Retrieves all WSUS child servers.
.DESCRIPTION
Retrieves all WSUS child servers.
.NOTES
Name: Get-WSUSChildServers
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSChildServers
Description
-----------
This command will display all of the Child WSUS servers.
#>
[cmdletbinding()]
Param ()
#Gather all child servers in WSUS
$wsus.GetChildServers()
}
function Get-WSUSDownstreamServers {
<#
.SYNOPSIS
Retrieves all WSUS downstream servers.
.DESCRIPTION
Retrieves all WSUS downstream servers.
.NOTES
Name: Get-WSUSDownstreamServers
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSDownstreamServers
Description
-----------
This command will display a list of all of the downstream WSUS servers.
#>
[cmdletbinding()]
Param ()
#Gather all child servers in WSUS
$wsus.GetDownstreamServers()
}
function Get-WSUSContentDownloadProgress {
<#
.SYNOPSIS
Retrieves the progress of currently downloading updates. Displayed in bytes downloaded.
.DESCRIPTION
Retrieves the progress of currently downloading updates. Displayed in bytes downloaded.
.PARAMETER Monitor
Runs a background job to monitor currently running content download and notifies user when completed.
.NOTES
Name: Get-WSUSContentDownloadProgress
Author: Boe Prox
DateCreated: 24SEPT2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Get-WSUSContentDownloadProgress
Description
-----------
This command will display the current progress of the content download.
.EXAMPLE
Get-WSUSContentDownloadProgress -monitor
Description
-----------
This command will create a background job that will monitor the progress and alert the user via pop-up message that
the download has been completed.
#>
[cmdletbinding()]
Param (
[Parameter(
Mandatory = $False,
Position = 0,
ParameterSetName = 'monitor',
ValueFromPipeline = $False)]
[switch]$Monitor
)
If ($monitor) {
#Stop and remove same jobs if existing
$job = Get-Job
If ($job) {
$job = Get-Job -Name "WSUSSyncProgressMonitor"
}
If ($job) {
Get-Job -Name "WSUSContentProgressMonitor" | Stop-Job
Get-Job -Name "WSUSContentProgressMonitor" | Remove-Job
}
Start-Job -Name "WSUSContentProgressMonitor" -ArgumentList $wsus -ScriptBlock {
Param (
$wsus
)
#Load required assemblies for message window
[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
$progress = $wsus.GetContentDownloadProgress()
While ($progress.TotalBytesToDownload -ne $progress.DownloadedBytes) {
$null
}
[System.Windows.Forms.MessageBox]::Show("Content download has been completed on WSUS",”Information”)
} | Out-Null
}
Else {
#Gather all child servers in WSUS
$wsus.GetContentDownloadProgress()
}
}
function Remove-WSUSClient {
<#
.SYNOPSIS
Removes client from WSUS.
.DESCRIPTION
Removes client from WSUS.
.PARAMETER Computer
Name of the client to remove from WSUS.
.PARAMETER InputObject
Computer object that is being removed.
.NOTES
Name: Remove-WSUSClient
Author: Boe Prox
DateCreated: 12NOV2010
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Remove-WSUSClient -computer "server1"
Description
-----------
This command will remove 'server1' from WSUS.
.EXAMPLE
Get-WSUSClient -computer "server1" | Remove-WSUSClient
Description
-----------
This command will remove 'server1' from WSUS.
.EXAMPLE
Get-WSUSClient -computer "servers" | % {Remove-WSUSClient -inputobject $_}
Description
-----------
This command will remove multiple servers from WSUS.
#>
[cmdletbinding(
DefaultParameterSetName = 'collection',
ConfirmImpact = 'low',
SupportsShouldProcess = $True
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = 'string',
ValueFromPipeline = $True)]
[string]$Computer,
[Parameter(
|
PowerShellCorpus/PoshCode/Empty working set.ps1
|
Empty working set.ps1
|
# use it as follows:
# PS C:\\> ps explorer | trim
add-type -Namespace Win32 -Name Psapi -MemberDefinition @"
[DllImport("psapi", SetLastError=true)]
public static extern bool EmptyWorkingSet(IntPtr hProcess);
"@
filter Reset-WorkingSet {
[Win32.Psapi]::EmptyWorkingSet($_.Handle)
}
sal trim Reset-WorkingSet
|
PowerShellCorpus/PoshCode/Coloring text in RichTex.ps1
|
Coloring text in RichTex.ps1
|
#code showing in RichTextBox
$code = @'
using System;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
[assembly: AssemblyVersion("3.5.0.0")]
namespace ProcessesSortedWithStartTime {
internal sealed class Program {
static DateTime Started(Process p) {
try {
return p.StartTime;
}
catch {
return DateTime.MinValue;
}
}
static void Main() {
Process[] procs = Process.GetProcesses();
try {
var sorted = from p in procs orderby Started(p), p.Id select p;
foreach (Process p in sorted)
Console.WriteLine("{0, 5} {1}", p.Id, p.ProcessName);
}
finally {
foreach (Process p in procs)
p.Dispose();
}
}
}
}
'@
#reserved words
$res = @(
"using", "namespace", "internal", "sealed", "class", "static", "try", "return", "catch",
"void", "finally", "var", "from", "in", "orderby", "select", "foreach"
)
#invoke coloring
$frmMain_Load= {
$res | % { Invoke-TextColoring $_ -col "Cyan" }
#operation
@("=") | % { Invoke-TextColoring $_ -col "Red" }
#brackets
"{", "}" | % { Invoke-TextColoring $_ -col "Orange" }
}
#coloring
function Invoke-TextColoring {
param(
[string]$Match,
[int32]$Position = 0,
[Windows.Forms.RichTextBoxFinds]$Options = "WholeWord",
[Drawing.Color]$Color = "Blue"
)
$chk = $txtEdit.Find($match, $position, $options)
while ($chk -ge 0) {
$txtEdit.SelectionStart = $chk
$txtEdit.SelectionLength = $match.Length
$txtEdit.SelectionColor = $color
$cur = $chk + $match.Length
if ($cur -lt $txtEdit.TextLength) {
$chk = $txtEdit.Find($match, $cur, $options)
}
else { break } #go out from cycle if there are not matches any more
}
$txtEdit.DeselectAll()
}
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$frmMain = New-Object Windows.Forms.Form
$txtEdit = New-Object Windows.Forms.RichTextBox
#
#txtEdit
#
$txtEdit.BackColor = [Drawing.Color]::FromArgb(1, 36, 86)
$txtEdit.Dock = "Fill"
$txtEdit.Font = New-Object Drawing.Font("Courier New", 10, [Drawing.FontStyle]::Bold)
$txtEdit.ForeColor = [Drawing.Color]::Linen
$txtEdit.Text = $code
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(590, 570)
$frmMain.Controls.Add($txtEdit)
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Form1"
$frmMain.Add_Load($frmMain_Load)
[void]$frmMain.ShowDialog()
}
frmMain_Show
|
PowerShellCorpus/PoshCode/2c605667-d02a-4251-bacb-0dae618c9f87.ps1
|
2c605667-d02a-4251-bacb-0dae618c9f87.ps1
|
function Update-Scopes($siteUrl)
{
[void][reflection.assembly]::Loadwithpartialname("Microsoft.SharePoint") | out-null
[void][reflection.assembly]::Loadwithpartialname("Microsoft.office.server.search") | out-null
$s = [microsoft.sharepoint.spsite]$siteUrl
$sc = [microsoft.office.server.servercontext]::GetContext($s)
$search = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($sc)
$scopes = [microsoft.office.server.search.administration.scopes]$search
$scopes.StartCompilation()
while ($scopes.CompilationPercentComplete -lt 100) { sleep -seconds 3; write-host "$($scopes.CompilationPercentComplete)% complete" }
}
@@#usage: paste this text into your PowerShell window, then call the "Update-Scopes" function as noted below
@@Update-Scopes -siteUrl "http://dev/sites/MySPSite/"
|
PowerShellCorpus/PoshCode/format-custom_1.ps1
|
format-custom_1.ps1
|
## UI Automation v 1.8 -- REQUIRES the Reflection module (current version: http://poshcode.org/3174 )
##
# WASP 2.0 is getting closer, but this is still just a preview:
# -- a lot of the commands have weird names still because they're being generated ignorantly
# -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke
# v 1.7 - Fixes using multiple checks like: Select-UIElement Red: Edit
# v 1.8 - Fixes .Net version problems: specifying CSharpVersion3 when in PowerShell 2
# IF your PowerShell is running in .Net 4
if($PSVersionTable.CLRVersion -gt "4.0") {
$Language = "CSharp" # Version 4
Add-Type -AssemblyName "UIAutomationClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
} else {
# In PowerShell 2, we need to use the .Net 3 version
$Language = "CSharpVersion3"
Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
}
$SWA = "System.Windows.Automation"
# Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue
# Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue
# Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue
# Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue
# Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue
# Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue
# This is what requires the Reflection module:
Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue
Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue
Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue
##### Conditions
Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue
Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue
Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue
Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue
Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue
##### IDentifiers
Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue
Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue
##### Patterns:
$patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern
#| Where { $_ -ne [System.Windows.Automation.InvokePattern] }
Add-Type -Language $Language -ReferencedAssemblies UIAutomationClient, UIAutomationTypes -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Automation;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class StaticFieldAttribute : ArgumentTransformationAttribute {
private Type _class;
public override string ToString() {
return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName);
}
public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) {
if(inputData is string && !string.IsNullOrEmpty(inputData as string)) {
System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public);
if(field != null) {
return field.GetValue(null);
}
}
return inputData;
}
public StaticFieldAttribute( Type ofClass ) {
OfClass = ofClass;
}
public Type OfClass {
get { return _class; }
set { _class = value; }
}
}
public static class UIAutomationHelper {
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr FindWindow (string lpClassName, string lpWindowName);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern bool AttachThreadInput (int idAttach, int idAttachTo, bool fAttach);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowThreadProcessId (IntPtr hWnd, IntPtr lpdwProcessId);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SetForegroundWindow (IntPtr hWnd);
public static AutomationElement RootElement {
get { return AutomationElement.RootElement; }
}
///<synopsis>Using Win32 to set foreground window because AutomationElement.SetFocus() is unreliable</synopsis>
public static bool SetForeground(this AutomationElement element)
{
if(element == null) {
throw new ArgumentNullException("element");
}
// Get handle to the element
IntPtr other = FindWindow (null, element.Current.Name);
// // Get the Process ID for the element we are trying to
// // set as the foreground element
// int other_id = GetWindowThreadProcessId (other, IntPtr.Zero);
//
// // Get the Process ID for the current process
// int this_id = GetWindowThreadProcessId (Process.GetCurrentProcess().Handle, IntPtr.Zero);
//
// // Attach the current process's input to that of the
// // given element. We have to do this otherwise the
// // WM_SETFOCUS message will be ignored by the element.
// bool success = AttachThreadInput(this_id, other_id, true);
// Make the Win32 call
IntPtr previous = SetForegroundWindow(other);
return !IntPtr.Zero.Equals(previous);
}
}
"@
## TODO: Write Get-SupportedPatterns or rather ...
## Get-SupportedFunctions (to return the names of the functions for the supported patterns)
## TODO: Support all the "Properties" too
## TODO: Figure out why Notepad doesn't support SetValue
## TODO: Figure out where the menus support went
ForEach($pattern in $patterns){
$pattern | Add-Accelerator
$PatternFullName = $pattern.FullName
$PatternName = $Pattern.Name -Replace "Pattern","."
$newline = "`n`t`t"
New-Item "Function:ConvertTo-$($Pattern.Name)" -Value "
param(
[Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject
)
process {
trap {
if(`$_.Exception.Message -like '*Unsupported Pattern.*') {
Write-Error `"Cannot get ```"$($Pattern.Name)```" from that AutomationElement, `$(`$_)` You should try one of: `$(`$InputObject.GetSupportedPatterns()|%{```"'```" + (`$_.ProgrammaticName.Replace(```"PatternIdentifiers.Pattern```",```"```")) + ```"Pattern'```"})`"; continue;
}
}
Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current
}"
$pattern.GetMethods() |
Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } |
ForEach {
$FunctionName = "Function:Invoke-$PatternName$($_.Name)"
$Position = 1
if (test-path $FunctionName) { remove-item $FunctionName }
$Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+
"$newline[Alias('Parent','Element','Root','AutomationElement')]"+
"$newline[AutomationElement]`$InputObject"
) +
@(
"[Parameter()]$newline[Switch]`$Passthru"
) +
@($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" })
$Parameters = $Parameters -Join "$newline,$newline"
$ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $')
$definition = @"
param(
$Parameters
)
process {
## trap { Write-Warning "`$(`$_)"; break }
`$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues }))
}
if(`$passthru) {
`$InputObject
}
}
"@
trap {
Write-Warning $_
Write-Host $definition -fore cyan
}
New-Item $FunctionName -value $definition
}
$pattern.GetProperties() |
Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} |
ForEach {
$FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.')
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$pattern.'$($_.Name)'
}
}"
}
## So far this seems to be restricted to Text (DocumentRange) elements
$pattern.GetFields() |
Where { $_.FieldType.Name -like "*TextAttribute"} |
ForEach {
$FunctionName = "Function:Get-Text$($_.Name -replace 'Attribute')"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name))
}"
}
$pattern.GetFields() | Where { $_.FieldType -eq [System.Windows.Automation.AutomationEvent] } |
ForEach {
$Name = $_.Name -replace 'Event$'
$FunctionName = "Function:Register-$($PatternName.Trim('.'))$Name"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
,
[System.Windows.Automation.TreeScope]`$TreeScope = 'Element'
,
[ScriptBlock]`$EventHandler
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
[Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler )
}"
}
}
$FalseCondition = [Condition]::FalseCondition
$TrueCondition = [Condition]::TrueCondition
Add-Type -AssemblyName System.Windows.Forms
Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue
$AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties()
Set-Alias Invoke-UIElement Invoke-Invoke.Invoke
function formatter { END {
$input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto
}}
function Get-ClickablePoint {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
)
process {
$InputObject.GetClickablePoint()
}
}
function Show-Window {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
Set-UIFocus $InputObject
if($passthru) {
$InputObject
}
}
}
function Set-UIFocus {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
try {
[UIAutomationHelper]::SetForeground( $InputObject )
$InputObject.SetFocus()
} catch {
Write-Verbose "SetFocus fail, trying SetForeground"
}
if($passthru) {
$InputObject
}
}
}
function Send-UIKeys {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Keys
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
,
[Parameter()]
[Switch]$Async
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
Set-UIFocus $InputObject
if($Async) {
[SendKeys]::Send( $Keys )
} else {
[SendKeys]::SendWait( $Keys )
}
if($passthru) {
$InputObject
}
}
}
function Set-UIText {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Text
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
$valuePattern = $null
if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) {
Write-Verbose "Set via ValuePattern!"
$valuePattern.SetValue( $Text )
}
elseif($InputObject.Current.IsKeyboardFocusable)
{
Set-UIFocus $InputObject
[SendKeys]::SendWait("^{HOME}");
[SendKeys]::SendWait("^+{END}");
[SendKeys]::SendWait("{DEL}");
[SendKeys]::SendWait( $Text )
}
if($passthru) {
$InputObject
}
}
}
function Select-UIElement {
[CmdletBinding(DefaultParameterSetName="FromParent")]
PARAM (
[Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)]
[Alias("MainWindowHandle","hWnd","Handle","Wh")]
[IntPtr[]]$WindowHandle=[IntPtr]::Zero
,
[Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)]
[System.Windows.Point[]]$Point
,
[Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)]
[System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement
,
[Parameter(ParameterSetName="FromParent", Position="0")]
[Alias("WindowName")]
[String[]]$Name
,
[Parameter(ParameterSetName="FromParent", Position="1")]
[Alias("Type","Ct")]
[System.Windows.Automation.ControlType]
[StaticField(([System.Windows.Automation.ControlType]))]$ControlType
,
[Parameter(ParameterSetName="FromParent")]
[Alias("UId")]
[String[]]$AutomationId
,
## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle
[Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )]
[Alias("Id")]
[Int[]]$PID
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Pn")]
[String[]]$ProcessName
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Cn")]
[String[]]$ClassName
,
[switch]$Recurse
,
[switch]$Bare
)
process {
Write-Debug "Parameters Found"
Write-Debug ($PSBoundParameters | Format-Table | Out-String)
$search = "Children"
if($Recurse) { $search = "Descendants" }
$condition = [System.Windows.Automation.Condition]::TrueCondition
Write-Verbose $PSCmdlet.ParameterSetName
switch -regex ($PSCmdlet.ParameterSetName) {
"FromWindowHandle" {
Write-Verbose "Finding from Window Handle $HWnd"
$Element = $(
foreach($hWnd in $WindowHandle) {
[System.Windows.Automation.AutomationElement]::FromHandle( $hWnd )
}
)
continue
}
"FromPoint" {
Write-Verbose "Finding from Point $Point"
$Element = $(
foreach($pt in $Point) {
[System.Windows.Automation.AutomationElement]::FromPoint( $pt )
}
)
continue
}
"FromParent" {
Write-Verbose "Finding from Parent!"
## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition
[ScriptBlock[]]$filters = @()
if($AutomationId) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($aid in $AutomationId) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::AutomationIdProperty), $aid
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($PID) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in $PID) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($ProcessName) {
if($ProcessName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in Get-Process -Name $ProcessName) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($Name) {
Write-Verbose "Name: $Name"
if($Name -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($n in $Name){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ClassName) {
if($ClassName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ClassName){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ControlType) {
if($ControlType -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ControlType){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($conditions.Length -gt 1) {
[System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions
} elseif($conditions) {
[System.Windows.Automation.Condition]$condition = $conditions[0]
} else {
[System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition
}
If($VerbosePreference -gt "SilentlyContinue") {
function Write-Condition {
param([Parameter(ValueFromPipeline=$true)]$condition, $indent = 0)
process {
Write-Debug ($Condition | fl * | Out-String)
if($condition -is [System.Windows.Automation.AndCondition] -or $condition -is [System.Windows.Automation.OrCondition]) {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name )
$condition.GetConditions().GetEnumerator() | Write-Condition -Indent ($Indent+4)
} elseif($condition -is [System.Windows.Automation.PropertyCondition]) {
Write-Verbose ((" "*$indent) + $Condition.Property.ProgrammaticName + " = '" + $Condition.Value + "' (" + $Condition.Flags + ")")
} else {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name + " where '" + $Condition.Value + "' (" + $Condition.Flags + ")")
}
}
}
Write-Verbose "CONDITIONS ============="
$global:LastCondition = $condition
foreach($c in $condition) {
Write-Condition $c
}
Write-Verbose "============= CONDITIONS"
}
if($filters.Count -gt 0) {
$Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item }
} else {
$Element = $Parent.FindAll( $search, $condition )
}
}
}
Write-Verbose "Element Count: $(@($Element).Count)"
if($Element) {
foreach($el in $Element) {
if($Bare) {
Write-Output $el
} else {
$e = New-Object PSObject $el
foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName)
{
## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property
$propName = [System.Windows.Automation.Automation]::PropertyName($prop)
Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0
}
foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName)
{
Add-Member -InputObject $e -Type ScriptProperty -Name ($patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") + "Pattern") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0
}
Write-Output $e
}
}
}
}
}
# [Cmdlet(VerbsCommon.Add, "UIAHandler")]
# public class AddUIAHandlerCommand : PSCmdlet
# {
# private AutomationElement _parent = AutomationElement.RootElement;
# private AutomationEvent _event = WindowPattern.WindowOpenedEvent;
# private TreeScope _scope = TreeScope.Children;
#
# [Parameter(ValueFromPipeline = true)]
# [Alias("Parent", "Element", "Root")]
# public AutomationElement InputObject { set { _parent = value; } get { return _parent; } }
#
# [Parameter()]
# public AutomationEvent Event { set { _event = value; } get { return _event; } }
#
# [Parameter()]
# public AutomationEventHandler ScriptBlock { set; get; }
#
# [Parameter()]
# public SwitchParameter Passthru { set; get; }
#
# [Parameter()]
# public TreeScope Scope { set { _scope = value; } get { return _scope; } }
#
# protected override void ProcessRecord()
# {
# Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock);
#
# if (Passthru.ToBool())
# {
# WriteObject(InputObject);
# }
#
# base.ProcessRecord();
# }
# }
Export-ModuleMember -cmdlet * -Function * -Alias *
|
PowerShellCorpus/PoshCode/Get-ChildItemRecurse_2.ps1
|
Get-ChildItemRecurse_2.ps1
|
function Get-ChildItemRecurse {
<#
.Synopsis
Does a recursive search through a PSDrive up to n levels.
.Description
Does a recursive directory search, allowing the user to specify the number of
levels to search.
.Parameter path
The starting path.
.Parameter fileglob
(optional) the search string for matching files
.Parameter levels
The numer of levels to recurse.
.Example
# Get up to three levels of files
PS> Get-ChildItemRecurse *.* -levels 3
.Notes
NAME: Get-ChildItemRecurse
AUTHOR: tojo2000
#Requires -Version 2.0
#>
Param([Parameter(Mandatory = $true,
ValueFromPipeLine = $false,
Position = 0)]
[string]$path = '.',
[Parameter(Mandatory = $false,
Position = 1,
ValueFromPipeLine = $false)]
[string]$fileglob = '*.*',
[Parameter(Mandatory = $false,
Position = 2,
ValueFromPipeLine = $false)]
[int]$levels = 0)
if (-not (Test-Path $path)) {
Write-Error "$path is an invalid path."
return $false
}
$files = @(Get-ChildItem $path)
foreach ($file in $files) {
if ($file -like $fileglob) {
Write-Output $file
}
@@ #if ($file.GetType().FullName -eq 'System.IO.DirectoryInfo') {
if ($file.PSIsContainer) {
if ($levels -gt 0) {
Get-ChildItemRecurse -path $file.FullName `
-fileglob $fileglob `
-levels ($levels - 1)
}
}
}
}
|
PowerShellCorpus/PoshCode/Draw with PowerShell.ps1
|
Draw with PowerShell.ps1
|
Add-Type -Assembly PresentationFramework
[xml]$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="423"
Height="370"
ResizeMode="NoResize"
WindowStartupLocation="CenterScreen"
Title="Butterfly">
<Path
Fill="Red"
Data="M204.33 139.83 C196.33 133.33 206.68 132.82 206.58 132.58
C192.33 97.08 169.35 81.41 167.58 80.58 C162.12 78.02
159.48 78.26 160.45 76.97 C161.41 75.68 167.72 79.72
168.58 80.33 C193.83 98.33 207.58 132.33 207.58 132.33
C207.58 132.33 209.33 133.33 209.58 132.58 C219.58 103.08
239.58 87.58 246.33 81.33 C253.08 75.08 256.63 74.47
247.33 81.58 C218.58 103.58 210.34 132.23 210.83 132.33
C222.33 134.83 211.33 140.33 211.83 139.83 C214.85 136.81
214.83 145.83 214.83 145.83 C214.83 145.83 231.83 110.83
298.33 66.33 C302.43 63.59 445.83 -14.67 395.83 80.83
C393.24 85.79 375.83 105.83 375.83 105.83 C375.83 105.83
377.33 114.33 371.33 121.33 C370.3 122.53 367.83 134.33
361.83 140.83 C360.14 142.67 361.81 139.25 361.83 140.83
C362.33 170.83 337.76 170.17 339.33 170.33 C348.83 171.33
350.19 183.66 350.33 183.83 C355.83 190.33 353.83 191.83
355.83 194.83 C366.63 211.02 355.24 210.05 356.83 212.83
C360.83 219.83 355.99 222.72 357.33 224.83 C360.83 230.33
354.75 233.84 354.83 235.33 C355.33 243.83 349.67 240.73
349.83 244.33 C350.33 255.33 346.33 250.83 343.83 254.83
C336.33 266.83 333.46 262.38 332.83 263.83 C329.83 270.83
325.81 269.15 324.33 270.83 C320.83 274.83 317.33 274.83
315.83 276.33 C308.83 283.33 304.86 278.39 303.83 278.83
C287.83 285.83 280.33 280.17 277.83 280.33 C270.33 280.83
271.48 279.67 269.33 277.83 C237.83 250.83 219.33 211.83
215.83 206.83 C214.4 204.79 211.35 193.12 212.33 195.83
C214.33 201.33 213.33 250.33 207.83 250.33 C202.33 250.33
201.83 204.33 205.33 195.83 C206.43 193.16 204.4 203.72
201.79 206.83 C196.33 213.33 179.5 250.83 147.59 277.83
C145.42 279.67 146.58 280.83 138.98 280.33 C136.46 280.17
128.85 285.83 112.65 278.83 C111.61 278.39 107.58 283.33
100.49 276.33 C98.97 274.83 95.43 274.83 91.88 270.83
C90.39 269.15 86.31 270.83 83.27 263.83 C82.64 262.38
79.73 266.83 72.13 254.83 C69.6 250.83 65.54 255.33 66.05
244.33 C66.22 240.73 60.48 243.83 60.99 235.33 C61.08
233.84 54.91 230.33 58.45 224.83 C59.81 222.72 54.91
219.83 58.96 212.83 C60.57 210.05 49.04 211.02 59.97
194.83 C62 191.83 59.97 190.33 65.54 183.83 C65.69 183.66
67.06 171.33 76.69 170.33 C78.28 170.17 53.39 170.83 53.9
140.83 C53.92 139.25 55.61 142.67 53.9 140.83 C47.82
134.33 45.32 122.53 44.27 121.33 C38.19 114.33 39.71
105.83 39.71 105.83 C39.71 105.83 22.08 85.79 19.46 80.83
C-31.19 -14.67 114.07 63.59 118.22 66.33 C185.58 110.83
202 145.83 202 145.83 C202 145.83 202.36 143.28 203
141.83 C203.64 140.39 204.56 140.02 204.33 139.83 z" />
</Window>
'@
$read = New-Object Xml.XmlNodeReader $xaml
$base = [Windows.Markup.XamlReader]::Load($read)
[void]$base.ShowDialog()
|
PowerShellCorpus/PoshCode/ConvertTo-PseudoType_1.ps1
|
ConvertTo-PseudoType_1.ps1
|
function ConvertTo-PseudoType {
<#
.Synopsis
Converts objects to custom PSObjects with robust type support
.Parameter TypeName
The name(s) of the PseudoType(s) to be inserted into the objects for the sake of formatting
.Parameter Mapping
A Hashtable of property names to types (or conversion scripts)
.Parameter InputObject
An object to convert.
.Example
Get-ChildItem | Where { !$_.PsIsContainer } | Export-CSV files.csv
## Given that a CSV file of file information exists,
## And we want to rehydrate it and be able to compare things...
## We need to create a mapping of properties to types
## Optionally, we can provide scriptblocks to convert instances
$Mapping = @{
Attributes = [System.IO.FileAttributes]
CreationTime = [System.DateTime]
CreationTimeUtc = [System.DateTime]
Directory = [System.IO.DirectoryInfo]
DirectoryName = [System.String]
Exists = [System.Boolean]
Extension = [System.String]
FullName = [System.String]
IsReadOnly = [System.Boolean]
LastAccessTime = [System.DateTime]
LastAccessTimeUtc = [System.DateTime]
LastWriteTime = [System.DateTime]
LastWriteTimeUtc = [System.DateTime]
Length = [System.Int64]
Name = [System.String]
PSChildName = [System.String]
PSDrive = [System.Management.Automation.PSDriveInfo]
PSIsContainer = [System.Boolean]
PSParentPath = [System.String]
PSPath = [System.String]
PSProvider = { Get-PSProvider $_ }
ReparsePoint = [System.Management.Automation.PSCustomObject]
VersionInfo = [System.Diagnostics.FileVersionInfo]
}
## When we import, we the Selected.System.IO.FileInfo, which is what you'd get from | Select *
Import-CSV | ConvertTo-PseudoType Selected.System.IO.FileInfo $Mapping
## That way, the output will look as though you had run:
Get-ChildItem | Where { !$_.PsIsContainer } | Select *
NOTE: Not all types are rehydrateable from CSV output -- the "VersionInfo" will be hydrated as a string...
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[Alias("Name","Tn")]
[String]$TypeName
,
[Parameter(Mandatory=$true, Position=1)]
[Hashtable]$Mapping
,
[Parameter(Mandatory=$true, Position=99, ValueFromPipeline=$true)]
[PSObject[]]$InputObject
)
begin {
$MappingFunction = @{}
foreach($key in $($Mapping.Keys)) {
$MappingFunction.$Key = {$_.$Key -as $Mapping.$Key}
}
}
process {
foreach($IO in $InputObject) {
$Properties = @{}
foreach($key in $($Mapping.Keys)) {
if($Mapping.$Key -is [ScriptBlock]) {
$Properties.$Key = $IO.$Key | ForEach-Object $Mapping.$Key
} elseif($Mapping.$Key -is [Type]) {
if($Value = $IO.$Key -as $Mapping.$Key) {
$Properties.$Key = $Value
} else {
$Properties.$Key = $IO.$Key
}
} else {
$Properties.$Key = [PSObject]$IO.$Key
}
}
New-Object PSObject -Property $Properties | %{ $_.PSTypeNames.Insert(0, $TypeName); $_ }
}
}
}
|
PowerShellCorpus/PoshCode/Out-Working.ps1
|
Out-Working.ps1
|
## You'll want to dot-source this into your script
## To change colors, specify the parameters:
## . Scripts\\OutWorkingScript.ps1 "Yellow" "Blue"
##
## Then you can show progress like this:
##
## $x = 1..50 | out-working 50
##
## Notice that the $wait parameter is only needed if there will not
## be enough of a delay already (it just slows the loop down)
##
param($fore="White",$back="red")
$work = @( $Host.UI.RawUI.NewBufferCellArray(@("|"),$fore,$back),
$Host.UI.RawUI.NewBufferCellArray(@("/"),$fore,$back),
$Host.UI.RawUI.NewBufferCellArray(@("-"),$fore,$back),
$Host.UI.RawUI.NewBufferCellArray(@("\\"),$fore,$back) );
[int]$script:w = 0;
filter out-working($wait=0) {
$cur = $Host.UI.RawUI.Get_CursorPosition();
$cur.X = 0; $cur.Y -=1;
$Host.UI.RawUI.SetBufferContents($cur,$work[$script:w++]);
if($script:w -gt 3) {$script:w = 0 }
Start-Sleep -milli $wait
$_
}
|
PowerShellCorpus/PoshCode/Set-IPAddress_1.ps1
|
Set-IPAddress_1.ps1
|
function Set-IPAddress {
param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"),
[string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"),
[string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"),
[string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"),
[string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"),
[string]$dns2,
[string]$registerDns = "TRUE"
)
$dns = $dns1
if($dns2){$dns ="$dns1,$dns2"}
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
$NetInterface.EnableStatic($ip, $subnetmask)
$NetInterface.SetGateways($gateway)
$NetInterface.SetDNSServerSearchOrder($dns)
$NetInterface.SetDynamicDNSRegistration($registerDns)
}
|
PowerShellCorpus/PoshCode/ScheduleGPOBackups_1.ps1
|
ScheduleGPOBackups_1.ps1
|
Import-Module grouppolicy
#region ConfigBlock
# What domain are we going to backup GPOs for?
$domain = "mydomain.com"
# Where are we going to store the backups?
$gpoBackupRootDir = "c:\\gpoBackups"
# As I plan to do a new backup set each month I'll setup the directory names to reflect
# the year and month in a nice sortable way.
# Set this up and format to your liking, I prefer $gpoBackupRootDir\\yyyy-MM
$backupDir = "$gpoBackupRootDir\\{0:yyyy-MM}" -f (Get-Date)
# Perform a full backup how often? Day/Week/Month/Year?
#$fullBackupFrequency = "Day"
#$fullBackupFrequency = "Week"
$fullBackupFrequency = "Month"
#$fullBackupFrequency = "Year"
# Perform Incremental backups how often? Hour/Day/Week/Month?
$IncBackupFreqency = "Hour"
# $IncBackupFreqency = "Day"
# $IncBackupFreqency = "Week"
# $IncBackupFreqency = "Month"
# How many full sets to keep?
# Alternatively, how far back do we keep our backup sets?
$numKeepBackupSets = 12
# On what day do we want to consider the start of Week?
#$startOfWeek = "Sunday"
$startOfWeek = "Monday"
#$startOfWeek = "Tuesday"
#$startOfWeek = "Wednesday"
#$startOfWeek = "Thursday"
#$startOfWeek = "Friday"
#$startOfWeek = "Saturday"
# On what day do we want to consider the start of Month?
$startOfMonth = 1
# On what day do we want to consider the start of Year?
$startOfYear = 1
#endregion
$currentDateTime = Get-Date
$doFull = $false
$doInc = $false
# Does our backup directory exist?
# If not attempt to create it and fail the script with an approprate error
if (-not (Test-Path $backupDir))
{
try
{
New-Item -ItemType Directory -Path $backupDir
}
catch
{
Throw $("Could not create directory $backupDir")
}
}
# If we're here then our backup directory is in good shape
# Check if we need to run a full backup or not
# if we do, then run it
if ( Test-Path $backupDir\\LastFullTimestamp.xml )
{
# Import the timestamp from the last recorded complete full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
# check to see if the timestamp is valid, if not then delete it and run a full
if ( $lastFullTimestamp -isnot [datetime] )
{
$doFull = $true
Remove-Item $backupDir\\LastFullTimestamp.xml
}
else # $lastfulltimestamp is or can be boxed/cast into [datetime]
{
# determine how long it has been since the last recorded full
$fullDelta = $currentDateTime - $lastFullTimestamp
switch ($fullBackupFrequency)
{
Day
{
if ( $fullDelta.days -gt 0 )
{
$doFull = $true
}
}
Week
{
if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) `
-or ($fullDelta.days -gt 7) )
{
$doFull = $true
}
}
Month
{
if ( ($currentDateTime.day -eq $startOfMonth) `
-or ($fullDelta.days -gt 30) )
{
$doFull = $true
}
}
Year
{
if ( ($currentDateTime.dayofyear -eq $startOfYear) `
-or ($fullDelta.days -gt 365) )
{
$doFull = $true
}
}
}
}
}
else # There is no recorded last completed full so we want to run one
{
$doFull = $true
}
if ($doFull)
{
# Run Backup of All GPOs in domain
$GPOs = Get-GPO -domain $domain -All
foreach ($GPO in $GPOs)
{
$GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir
# First build the Report path, then generate a report of the backed up settings.
$ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html"
Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML
}
Export-Clixml -Path $backupDir\\LastFullTimestamp.xml -InputObject ($currentDateTime)
}
else # If we're not running a full check if we need to run an incremental backup
{
if ( Test-Path $backupDir\\LastIncTimestamp.xml )
{
# Import the timestamp from the last recorded complete Incremental
$lastIncTimestamp = Import-Clixml $backupDir\\LastIncTimestamp.xml
# check to see if the timestamp is valid, if not then delete it and run an inc
if ( $lastIncTimestamp -isnot [datetime] )
{
# Import the timestamp from the last recorded complete full
# If we're here then the timestamp is valid. It is checked earlier and if it fails
# or doesn't exist then we run a full and will never get here.
# determine how long it has been since the last recorded full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
$IncDelta = $currentDateTime - $lastFullTimestamp
$doInc = $true
Remove-Item $backupDir\\LastIncTimestamp.xml
}
else # $lastIncTimestamp is or can be boxed/cast into [datetime]
{
# determine how long it has been since the last recorded full
$IncDelta = $currentDateTime - $lastIncTimestamp
}
}
else # There is no recorded last Incremental
{
# Import the timestamp from the last recorded complete full
# If we're here then the timestamp is valid. It is checked earlier and if it fails
# or doesn't exist then we run a full and will never get here.
# determine how long it has been since the last recorded full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
$IncDelta = $currentDateTime - $lastFullTimestamp
}
# If we have already determined to run an Inc we want to skip this part
if ($doInc = $false)
{
switch ($IncBackupFreqency)
{
Hour
{
if ($IncDelta.hours -gt 0)
{
$doInc = $true
}
}
Day
{
if ($IncDelta.days -gt 0)
{
$doInc = $true
}
}
Week
{
if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) `
-or ($IncDelta.days -gt 7) )
{
$doInc = $true
}
}
Month
{
if ( ($currentDateTime.day -eq $startOfMonth) `
-or ($IncDelta.days -gt 30) )
{
$doInc = $true
}
}
}
}
# Time to check our Incremental flag and run the backup if we need to
if ($doInc)
{
# Run Incremental Backup
$GPOs = Get-GPO -domain $domain -All | Where-Object { $_.modificationTime -gt ($currentDateTime - $incDelta) }
foreach ($GPO in $GPOs)
{
$GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir
# First build the Report path, then generate a report of the backed up settings.
$ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + ".html"
Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML
}
Export-Clixml -Path $backupDir\\LastIncTimestamp.xml -InputObject ($currentDateTime)
}
}
#TODO: Cleanup old backup sets
|
PowerShellCorpus/PoshCode/Quest Dynamic Group 002.ps1
|
Quest Dynamic Group 002.ps1
|
<#
2012.07.06
Information will be uploaded shortly.
#>
|
PowerShellCorpus/PoshCode/ConvertTo-Hex_5.ps1
|
ConvertTo-Hex_5.ps1
|
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx
param ( [string]$SidString )
# Create SID .NET object using SID string provided
$sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring
# Create a byte array of the proper length
$sidBytes = New-Object byte[] $sid.BinaryLength
#Convert to bytes
$sid.GetBinaryForm( $sidBytes, 0 )
# Iterate through bytes, converting each to the hexidecimal equivalent
$hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") }
# Join the hex array into a single string for output
$hexArr -join ''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.