full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Search-Network.ps1
Search-Network.ps1
#Define PreReqs $timeStamp = Get-Date -UFormat "%m-%d-%Y-%H-%M" $systemVars = Gwmi Win32_ComputerSystem -Comp "." $userName = $systemVars.UserName $compName = $systemVars.Name #User Vars $serviceName = "Spooler" # Spooler will check the Print Spooler <<< Change To Suit Your needs $errorLog = "C:\\Temp\\Log_"+$serviceName+"_"+$timeStamp+"_Errors.txt" #Service Not Installed $fullLog = "C:\\Temp\\Log_"+$serviceName+"_"+$timeStamp+"_All.txt" #Services Needed To Be Started / Running #Write Some Info To Logs "Check Service: " + $serviceName > $errorLog; Get-Date >> $errorLog; $compName >> $errorLog; $userName >> $errorLog; "_____________" >> $errorLog; "" >> $errorLog; "Check Service: " + $serviceName > $fullLog; Get-Date >> $fullLog; $compName >> $fullLog; $userName >> $fullLog; "_____________" >> $fullLog; "" >> $fullLog; # Define Functions function Get-NetView { switch -regex (NET.EXE VIEW) { "^\\\\\\\\(?<Name>\\S+)\\s+" {$matches.Name}} } function Process-PCs ($currentName) { $olStatus = Ping-Address $currentName If ($olStatus -eq "True") { Check-Service $currentName } #Else {Write-Host "PC Not Online"} Write-Host " " } function Ping-Address ($pingAddress) { $ping = new-object system.net.networkinformation.ping $pingReply = $ping.send($pingAddress) If ($pingReply.status -eq "Success") { Return "True" } Else { Return "False" } } function Check-Service ($currentName) { $currentService = Get-Service -ComputerName $currentName -Name $serviceName -ErrorAction SilentlyContinue If ($currentService.Status -eq $Null){ $currentServiceStatus = "Not Installed" $currentName >> $errorLog } ElseIf ($currentService.Status -eq "Running"){ $currentServiceStatus = "Running" } ElseIf ($currentService.Status -eq "Stopped"){ $currentServiceStatus = "Stopped" } Else { $currentServiceStatus = "Unknown" } Write-Host $serviceName " is " $currentServiceStatus " on " $currentName $serviceName + " was " + $currentServiceStatus + " on " + $currentName >> $fullLog If ($currentService.Status -eq "Stopped"){ Write-Host "Service was stoppped, trying to start it . . ." $currentService | Start-Service -ErrorAction SilentlyContinue If ($currentService.Status -eq "Running"){ " Service Successfully Started" >> $fullLog } Else { " Service Could Not Be Started" >> $fullLog } } } #Run Everything cls Get-NetView | %{Process-PCs $_} # Test a single PC, Uncomment line below change pc name and comment line above # Process-PCs "localhost" | %{Process-PCs $_}
PowerShellCorpus/PoshCode/Get-Link.ps1
Get-Link.ps1
param([Parameter(ValueFromPipelineByPropertyName=$true)][Alias("PSPath")][string]$Path) begin { Add-Type -TypeDef @" using System; using System.IO; using System.Text; using System.Drawing; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace Huddled.Interop { [Flags()] // SHELL_LINK_DATA_FLAGS public enum ShellLinkFlags : uint { Default = 0x00000000, HasIdList = 0x00000001, HasLinkInfo = 0x00000002, HasName = 0x00000004, HasRelpath = 0x00000008, HasWorkingdir = 0x00000010, HasArgs = 0x00000020, HasIconLocation = 0x00000040, Unicode = 0x00000080, ForceNoLinkInfo = 0x00000100, HasExpSz = 0x00000200, RunInSeparate = 0x00000400, HasLogo3Id = 0x00000800, HasDarwinId = 0x00001000, RunasUser = 0x00002000, HasExpIconSz = 0x00004000, NoPidlAlias = 0x00008000, ForceUncname = 0x00010000, RunWithShimlayer = 0x00020000, ForceNoLinktrack = 0x00040000, EnableTargetMetadata = 0x00080000, DisableLinkPathTracking = 0x00100000, DisableKnownfolderRelativeTracking = 0x00200000, NoKFAlias = 0x00400000, AllowLinkToLink = 0x00800000, UnaliasOnSave = 0x01000000, PreferEnvironmentPath = 0x02000000, KeepLocalIdListForUncTarget = 0x04000000, Valid = 0x07fff7ff, Reserved = (uint)0x80000000 } // IShellLink.ShowCmd fFlags [Flags()] public enum ShowCmd { Normal = 1, Maximized = 3, Minnoactive = 7 } // IShellLink.Resolve fFlags SLR_FLAGS [Flags()] public enum ResolveFlags { NoUI = 0x1, AnyMatch = 0x2, Update = 0x4, NoUpdate = 0x8, NoSearch = 0x10, NoTrack = 0x20, NoLinkInfo = 0x40, InvokeMsi = 0x80 } // IShellLink.GetPath fFlags SLGP_FLAGS [Flags()] public enum GetPathFlags { ShortPath = 0x1, UncPriority = 0x2, RawPath = 0x4 } // Win32 COORD [StructLayout(LayoutKind.Sequential)] public struct COORD { public short X; public short Y; } // IShellDataLink NT_CONSOLE_PROPS [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct NT_CONSOLE_PROPS { public int cbSize; // Size of this extra data block public uint dwSignature; // signature of this extra data block public ushort wFillAttribute; // fill attribute for console public ushort wPopupFillAttribute; // fill attribute for console popups public COORD dwScreenBufferSize; // screen buffer size for console public COORD dwWindowSize; // window size for console public COORD dwWindowOrigin; // window origin for console public int nFont; public int nInputBufferSize; public COORD dwFontSize; public uint uFontFamily; public uint uFontWeight; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string FaceName; public uint uCursorSize; public bool bFullScreen; public bool bQuickEdit; public bool bInsertMode; public bool bAutoPosition; public uint uHistoryBufferSize; public uint uNumberOfHistoryBuffers; public bool bHistoryNoDup; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public uint[] ColorTable; } // The CharSet must match the CharSet of the corresponding PInvoke signature [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] public struct WIN32_FIND_DATA { public uint dwFileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)] public string cAlternateFileName; } [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("0000010B-0000-0000-C000-000000000046")] public interface IPersistFile { #region Methods inherited from IPersist void GetClassID( out Guid pClassID); #endregion [PreserveSig()] int IsDirty(); void Load( [MarshalAs(UnmanagedType.LPWStr)] string pszFileName, int dwMode); void Save( [MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [MarshalAs(UnmanagedType.Bool)] bool fRemember); void SaveCompleted( [MarshalAs(UnmanagedType.LPWStr)] string pszFileName); void GetCurFile( out IntPtr ppszFileName); } [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")] public interface IShellLinkW { void GetPath( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATA pfd, GetPathFlags fFlags); void GetIDList( out IntPtr ppidl); void SetIDList( IntPtr pidl); void GetDescription( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName); void SetDescription( [MarshalAs(UnmanagedType.LPWStr)] string pszName); void GetWorkingDirectory( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); void SetWorkingDirectory( [MarshalAs(UnmanagedType.LPWStr)] string pszDir); void GetArguments( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); void SetArguments( [MarshalAs(UnmanagedType.LPWStr)] string pszArgs); void GetHotkey( out short pwHotkey); void SetHotkey( short wHotkey); void GetShowCmd( out int piShowCmd); void SetShowCmd( int iShowCmd); void GetIconLocation( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon); void SetIconLocation( [MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); void SetRelativePath( [MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved); void Resolve( IntPtr hwnd, ResolveFlags fFlags); void SetPath( [MarshalAs(UnmanagedType.LPWStr)] string pszFile); } [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("45E2b4AE-B1C3-11D0-B92F-00A0C90312E1")] public interface IShellLinkDataList { void AddDataBlock(IntPtr pDataBlock); void CopyDataBlock(uint dwSig, out IntPtr ppDataBlock); void RemoveDataBlock(uint dwSig); void GetFlags(out uint dwFlags); void SetFlags(uint dwFlags); } public class ShellLink { private IShellLinkW _ShellLink; private NT_CONSOLE_PROPS _ConsoleProperties; private ushort _ScreenFill; private ushort _PopUpFill; public Color[] ConsoleColors = new Color[16]; public ShellLink(string Path) { _ShellLink = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"))) as IShellLinkW; if (File.Exists(Path)) { IntPtr pConsoleProperties = IntPtr.Zero; ((IPersistFile)_ShellLink).Load(Path, 0); try { // TODO: Fix memory leak here ((IShellLinkDataList)_ShellLink).CopyDataBlock(0xA0000002, out pConsoleProperties); _ConsoleProperties = (NT_CONSOLE_PROPS)Marshal.PtrToStructure(pConsoleProperties, typeof(NT_CONSOLE_PROPS)); _ScreenFill = _ConsoleProperties.wFillAttribute; _PopUpFill = _ConsoleProperties.wPopupFillAttribute; for (int i = 0; i < 16; i++) { ConsoleColors[i] = ColorTranslator.FromWin32((int)_ConsoleProperties.ColorTable[i]); } } catch (Exception) { } } else { ((IPersistFile)_ShellLink).Save(Path, true); } // Initialize default Console Properties (TODO: Fix this bug too) if (_ConsoleProperties.dwSignature != 0xA0000002) { _ConsoleProperties = new NT_CONSOLE_PROPS(); _ConsoleProperties.cbSize = Marshal.SizeOf(_ConsoleProperties); _ConsoleProperties.dwSignature = 0xA0000002; _ConsoleProperties.ColorTable = new uint[16]; for (int i = 0; i < 16; i++) { _ConsoleProperties.ColorTable[i] = 0xffffffff; } } } public ShellLinkFlags Flags { get { uint flags; ((IShellLinkDataList)_ShellLink).GetFlags( out flags ); return (ShellLinkFlags)flags; } set { ((IShellLinkDataList)_ShellLink).SetFlags( (uint)value ); } } public void Save(string Path) { SetConsoleColors(); ((IPersistFile)_ShellLink).Save(Path, true); } public void Save() { SetConsoleColors(); ((IPersistFile)_ShellLink).Save(null, true); } public IShellLinkW GetShellLink() { return _ShellLink; } public string Path { get { StringBuilder sb = new StringBuilder(260); WIN32_FIND_DATA pfd = new WIN32_FIND_DATA(); _ShellLink.GetPath(sb, 259, out pfd, GetPathFlags.RawPath); return sb.ToString(); } set { _ShellLink.SetPath(value); } } public string Description { get { StringBuilder sb = new StringBuilder(2048); _ShellLink.GetDescription(sb, 2048); return sb.ToString(); } set { _ShellLink.SetDescription(value); } } public string WorkingDirectory { get { StringBuilder sb = new StringBuilder(260); _ShellLink.GetWorkingDirectory(sb, 260); return sb.ToString(); } set { _ShellLink.SetWorkingDirectory(value); } } public ShowCmd ShowCmd { get { int nShowCmd; _ShellLink.GetShowCmd(out nShowCmd); return (ShowCmd)Enum.ToObject(typeof(ShowCmd), nShowCmd); } set { _ShellLink.SetShowCmd((int)value); } } public bool QuickEditMode { get { return _ConsoleProperties.bQuickEdit; } set { _ConsoleProperties.bQuickEdit = value; } } public bool InsertMode { get { return _ConsoleProperties.bInsertMode; } set { _ConsoleProperties.bInsertMode = value; } } public bool AutoPosition { get { return _ConsoleProperties.bAutoPosition; } set { _ConsoleProperties.bAutoPosition = value; } } public void SetScreenBufferSize(short x, short y) { COORD c = new COORD(); c.X = x; c.Y = y; _ConsoleProperties.dwScreenBufferSize = c; } public void SetWindowSize(short x, short y) { COORD c = new COORD(); c.X = x; c.Y = y; _ConsoleProperties.dwWindowSize = c; } public uint CommandHistoryBufferSize { get { return _ConsoleProperties.uHistoryBufferSize; } set { _ConsoleProperties.uHistoryBufferSize = value; } } public uint CommandHistoryBufferCount { get { return _ConsoleProperties.uNumberOfHistoryBuffers; } set { _ConsoleProperties.uNumberOfHistoryBuffers = value; } } public byte ScreenBackgroundColor { set { _ScreenFill &= 0x00ff; _ScreenFill += (ushort)(value << 4); } } public byte ScreenTextColor { set { _ScreenFill &= 0xff00; _ScreenFill += value; } } public byte PopUpBackgroundColor { set { _PopUpFill &= 0x00ff; _PopUpFill += (ushort)(value << 4); } } public byte PopUpTextColor { set { _PopUpFill &= 0xff00; _PopUpFill += value; } } // This does more than console colors private void SetConsoleColors() { for (int i = 0; i < 16; i++) { _ConsoleProperties.ColorTable[i] = (uint)ColorTranslator.ToWin32(ConsoleColors[i]); } _ConsoleProperties.wFillAttribute = _ScreenFill; _ConsoleProperties.wPopupFillAttribute = _PopUpFill; ; IntPtr pConsoleProperties = Marshal.AllocCoTaskMem(_ConsoleProperties.cbSize); Marshal.StructureToPtr(_ConsoleProperties, pConsoleProperties, true); ((IShellLinkDataList)_ShellLink).RemoveDataBlock(0xA0000002); ((IShellLinkDataList)_ShellLink).AddDataBlock(pConsoleProperties); } } } "@ -ReferencedAssemblies System.Drawing function global:Get-Link { param([Parameter(ValueFromPipelineByPropertyName=$true)][Alias("PSPath")][string]$Path) process { New-Object Huddled.Interop.ShellLink (Convert-Path $Path) } } } process { Get-Link $Path }
PowerShellCorpus/PoshCode/Migrate UserFolder_2.ps1
Migrate UserFolder_2.ps1
param( $RootFolder = "\\\\server1\\users", $NewRootFolder = "\\\\server2\\users", $LogFolder = "C:\\Projects\\HomeDirs", $NewSubFolders = @("Documents","Favorites","Desktop","Links","Contacts"), $domain = "domain", [switch]$SetACL ) $UserFolders = gci -Path $RootFolder | ?{$_.PSIsContainer} $UserFolders | foreach-object -Process { #create new homedrive $NewUserFolder = $NewRootFolder + "\\" + $_.name New-Item -Path $NewUserFolder -ItemType "Directory" if ($SetACL){ #set ACL rules for new homedrive $acl = Get-Acl $NewUserFolder $Owner = New-Object System.Security.Principal.NTAccount($domain, $_.name) $acl.SetOwner($Owner) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Owner,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.SetAccessRule($rule) Set-Acl $NewUserFolder $acl } #create required subfolders per homedrive $NewSubFolders | foreach{New-Item -Path $($NewUserFolder + "\\" + $_) -type directory} #build robocopy job per homedrive $LogFile = $LogFolder + "\\" + $_.name + ".log" $JobName = $_.name + "_RCsync" $CommandString = "robocopy $($_.FullName) $($NewUserFolder + "\\Documents") /COPYALL /MIR /FFT /Z /Log+:$LogFile" start-job -Scriptblock {invoke-Expression $input} -name $JobName -InputObject $CommandString } #Wait for all jobs Get-Job | Wait-Job #Get all job results Get-Job | Receive-Job
PowerShellCorpus/PoshCode/Copy-FilePlus.ps1
Copy-FilePlus.ps1
<# .SYNOPSIS Copies a file from one location to another while displaying a GUI progress window. .PARAMETER Path Specifies the filename or FileInfo object representing file to be copied. Right now, this must be fully-qualified, relative paths will produce an error. Try it with Get-Item or Get-ChildItem, this works great. .PARAMETER Destination Specifies the filename including path for resulting copy operation. .EXAMPLE PS > Copy-FilePlus -Path c:\\tmp\\windows7.iso -Destination e:\\tmp\\windows7.iso .EXAMPLE PS > Get-Item c:\\tmp\\windows7.iso | Copy-FilePlus -Destination e:\\tmp\\windows7.iso #> #requires -version 2 param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )]$Path, [Parameter(Mandatory=$true)] [string] $Destination ) try { add-type -a microsoft.visualbasic [Microsoft.VisualBasic.FileIO.FileSystem]::CopyFile( $Path, $Destination, [Microsoft.VisualBasic.FileIO.UIOption]::AllDialogs, [Microsoft.VisualBasic.FileIO.UICancelOption]::ThrowException ) } catch { $_ }
PowerShellCorpus/PoshCode/Set-IPAddress_5.ps1
Set-IPAddress_5.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/ShowUI Text Converter_1.ps1
ShowUI Text Converter_1.ps1
#Import-Module showui $Windowparam = @{ Width = 500 Height = 400 Title = 'Fun Text Converter' Background = '#C4CBD8' WindowStartupLocation = 'CenterScreen' AsJob = $True } #Create Window New-Window @Windowparam { New-Grid -Rows *,Auto,*,Auto -Children { New-TextBox -Row 0 -Name InputBox -TextWrapping Wrap -VerticalScrollBarVisibility Auto New-Grid -Row 1 -Columns *,*,Auto,Auto,Auto,*,* -Children { New-Button -Column 2 -Name ConvertButton -Width 65 -Height 25 -Content Translate -On_Click { If ($ComboBox.Text -eq 'TextToBinary') { $OutputBox.Text = Convert-TextToBinary $InputBox.Text } ElseIf ($ComboBox.Text -eq 'BinaryToText') { $OutputBox.Text = Convert-BinaryToText $InputBox.Text } ElseIf ($ComboBox.Text -eq 'TextToHex') { $OutputBox.Text = Convert-TextToHex $InputBox.Text } ElseIf ($ComboBox.Text -eq 'HexToText') { $OutputBox.Text = Convert-HexToText $InputBox.Text } ElseIf ($ComboBox.Text -eq 'BinaryToHex') { $OutputBox.Text = Convert-BinaryToHex $InputBox.Text } ElseIf ($ComboBox.Text -eq 'HexToBinary') { $OutputBox.Text = Convert-HexToBinary $InputBox.Text } ElseIf ($ComboBox.Text -eq 'ReverseInput') { $OutputBox.Text = Convert-TextToReverseText $InputBox.Text } } New-Label -Column 3 New-ComboBox -Name ComboBox -Column 4 -IsReadOnly:$True -SelectedIndex 0 -Items { New-TextBlock -Text TextToBinary New-TextBlock -Text BinaryToText New-TextBlock -Text TextToHex New-TextBlock -Text HexToText New-TextBlock -Text BinaryToHex New-TextBlock -Text HexToBinary New-TextBlock -Text ReverseInput } } New-TextBox -Row 2 -Name OutputBox -IsReadOnly:$True -TextWrapping Wrap ` -VerticalScrollBarVisibility Auto New-StackPanel -Row 3 -Orientation Horizontal { New-Button -Name CopyTextButton -Width 65 -Height 25 -HorizontalAlignment Left -Content CopyText -On_Click { $OutputBox.text | clip } New-Label New-Button -Name ClearTextButton -Width 65 -Height 25 -HorizontalAlignment Left -Content ClearText -On_Click { $OutputBox.Text=$Null } } } } -On_Loaded { Function Convert-TextToBinary { [cmdletbinding()] Param ( [parameter(ValueFromPipeLine='True')] [string]$Text ) Begin { #Create binary empty collection [string[]]$BinaryArray = @() } Process { #Convert text to array $textarray = $text.ToCharArray() #Convert each item to binary ForEach ($a in $textarray) { $BinaryArray += ([convert]::ToString([int][char]$a,2)).PadLeft(8,"0") } } End { #Write out binary string $BinaryArray -Join " " } } Function Convert-BinaryToText { [cmdletbinding()] Param ( [parameter(ValueFromPipeLine='True')] [string]$Binary ) Begin { #Create binary empty collection [string[]]$TextArray = @() } Process { #Split Binary string into array $BinaryArray = $Binary -split "\\s" #Convert each item to Char ForEach ($a in $BinaryArray) { $TextArray += [char]([convert]::ToInt64($a,2)) } } End { #Write out text string $TextArray -Join "" } } Function Convert-TextToHex { [cmdletbinding()] Param ( [parameter(ValueFromPipeLine='True')] [string]$Text ) Begin { #Create hex empty collection [string[]]$HexArray = @() } Process { #Convert text to array $textarr = $text.ToCharArray() #Convert each item to binary ForEach ($a in $textarr) { $HexArray += "0x$(([convert]::ToString([int][char]$a,16)).PadLeft(8,'0'))" } } End { #Write out hex string $HexArray -Join " " } } Function Convert-HexToText { [cmdletbinding()] Param ( [parameter(ValueFromPipeLine='True')] [string]$Hex ) Begin { #Create text empty collection [string[]]$textarr = @() } Process { #Split Binary string into array $HexArray = $Hex -split "\\s" #Convert each item to Char ForEach ($a in $HexArray) { $textarr += [char]([convert]::ToInt64($a.TrimStart('x0'),16)) } } End { #Write out text string $textarr -join "" } } Function Convert-HexToBinary { [cmdletbinding()] Param ( [parameter(ValueFromPipeLine='True')] [string]$Hex ) Begin { #Create binary empty collection [string[]]$binarr = @() } Process { #Split Binary string into array $HexArray = $Hex -split "\\s" #Convert each item to Char ForEach ($a in $HexArray) { $a = ([char]([convert]::ToInt64($a.TrimStart('x0'),16))) $binarr += ([convert]::ToString([int][char]$a,2)).PadLeft(8,"0") } } End { #Write out binary string $binarr -join " " } } Function Convert-BinaryToHex { [cmdletbinding()] Param ( [parameter(ValueFromPipeLine='True')] [string]$Binary ) Begin { #Create binary empty collection [string[]]$TextArray = @() } Process { #Split Binary string into array $BinaryArray = $Binary -split "\\s" #Convert each item to Char ForEach ($a in $BinaryArray) { $a = [char]([convert]::ToInt64($a,2)) $TextArray += "0x$(([convert]::ToString([int][char]$a,16)).PadLeft(8,'0'))" } } End { #Write out hex string $TextArray -Join " " } } Function Convert-TextToReverseText { [cmdletbinding()] Param ( [parameter(ValueFromPipeLine='True')] [string]$InputString ) Begin { } Process { #Convert text to array $inputarray = $InputString -split "" #Reverse array [array]::Reverse($inputarray) } End { #Write out reverse string $inputarray -join "" } } }
PowerShellCorpus/PoshCode/Set-AppCompatFlag.ps1
Set-AppCompatFlag.ps1
<# .SYNOPSIS Sets the Compatibility flags for an application. .EXAMPLE Set-AppCompatFlag.ps1 -Path 'c:\\windows\\system32\\WindowsPowerShell\\v1.0\\PowerShell_ISE.exe' This sets the RUNASADMIN flag for the ISE .EXAMPLE Set-AppCompatFlag.ps1 -Path 'c:\\windows\\system32\\WindowsPowerShell\\v1.0\\PowerShell_ISE.exe' -ComputerName RemoteServer01 This sets the RUNASADMIN flag for the ISE on RemoteServer01. .PARAMETER Path The full path to the executable to flag for compatibility. .PARAMETER ComputerName Computer to run the command against. If this is a remote computer, the Remote Registry service needs to be running. This defaults to the local machine. .PARAMETER Scope The scope to set the compatibility flag at. This can be the CurrentUser or the LocalMachine level. The default is CurrentUser. .PARAMETER Flag The compatibility flag to set. Currently supports: "RUNASADMIN", "WINSRV03SP1", "WINSRV08SP1", "WINXPSP2", "WINXPSP3", "DISABLETHEMES", "640X480", "HIGHDPIAWARE", "256COLOR", "DISABLEDWM". The default is RUNASADMIN. .NOTES NAME: Set-AppCompatFlag AUTHOR: Steven Murawski LASTEDIT: February 07, 2011 5:27:44 PM KEYWORDS: #Requires -Version 2.0 #> param( [Parameter( Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [alias('FullName','FullPath')] [string] $Path, [Parameter( ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [string[]] $ComputerName, [Parameter(Position=2)] [string] [ValidateSet("CurrentUser", "LocalMachine")] $Scope = "CurrentUser", [Parameter(Position=3)] [string] [ValidateSet("RUNASADMIN", "WINSRV03SP1", "WINSRV08SP1", "WINXPSP2", "WINXPSP3", "DISABLETHEMES", "640X480", "HIGHDPIAWARE", "256COLOR", "DISABLEDWM")] $Flag = "RUNASADMIN" ) process { if (($ComputerName -eq $null) -or ($ComputerName.count -lt 1)) { $ComputerName = @($env:COMPUTERNAME) } foreach ($Computer in $ComputerName) { try { Write-Debug "Opening Remote Registry" $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Scope, $Computer) Write-Debug 'Reading SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AppCompatFlags\\\\Layers' $keys = $reg.OpenSubKey('SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AppCompatFlags\\\\Layers', $true) Write-Debug "Checking to see if $Path already has AppCompatFlags" $NotFlagged = $true $NotSet = $true if ($keys.GetValueNames() -contains $Path) { Write-Debug "Checking to see if $Path already has $Flag set" if ($keys.GetValue($Path) -like "*$Flag*") { $NotFlagged = $false Write-Debug "Found Application and it was already flagged - $Flag" } else { $CurrentValue = $keys.GetValue($Path) Write-Debug "Adding $Flag for $path to $Current on $Computer" $NewFlag = "$CurrentValue $Flag" Write-Debug "Setting $Flag for $path on $Computer" $Keys.SetValue($path, $NewFlag) Write-Verbose "Set $NewFlag for $path on $Computer" $NotSet = $false } } if ($NotFlagged -and $NotSet) { Write-Debug "Setting $Flag for $path on $Computer" $keys.SetValue("$path","$flag") Write-Verbose "Set $Flag for $path on $Computer" } else { Write-Debug "Did not set $Flag for $Path on $Computer. Flag already existed." Write-Verbose "Did not set $Flag for $Path on $Computer. Flag already existed." } } catch [Exception] { Write-Debug "Failed to connect to the remote registery or error reading the remote key." Write-Error $_.Exception } } }
PowerShellCorpus/PoshCode/Get-FactualData.ps1
Get-FactualData.ps1
# Get data from factual.com. Currently you need an API key to even query data so you'll # have to set one up before you can use this. Set your API key to the global variable # APIKEY. Hopefully one day factual will allow reads without requiring API keys, which # is why I chose not to make it an argument to the function. # # Note that table name must be the internal table name (e.g. Dbopve) and not any sort # of name meaningful to humans. Function Get-FactualData { param($tableName) $wc = New-Object Net.Webclient $url = "http://api.factual.com/v1/" + $APIKEY + "/tables/" + $tableName + "/read.xml" $xml = [xml]$wc.DownloadString($url) # Get the column titles. $nFields = $xml.result.response.fields.field.length - 1 $fields = $xml.result.response.fields.field[1 .. ($nFields + 1)] # Create objects for each entry. $xml.result.response.data.row | Foreach { $t = "" | Select $fields foreach ($i in 1 .. $nFields) { $t.($fields[$i-1]) = $_.cell[$i] } Write-Output $t } }
PowerShellCorpus/PoshCode/Compare-SQLResultSet.ps1
Compare-SQLResultSet.ps1
<# .SYNOPSIS Compares two result sets from SQL queries for differences. .DESCRIPTION Compares the result sets from two SQL queries and outputs the differences. Currently the function only handles similarly shaped result sets. That is, result sets with the same number and names of columns. Functionality will be added in the future to allow for comparison and differencing of disparate result sets. .PARAMETER ServerName1 The name of the server on which the first query should be executed. .PARAMETER DatabaseName1 The name of the database on which the first query should be executed. .PARAMETER Query1 The first SQL query to be executed. .PARAMETER ServerName2 The name of the server on which the second query should be executed. .PARAMETER DatabaseName2 The name of the database on which the second query should be executed. .PARAMETER Query2 The second SQL query to be executed. .EXAMPLE Compare-SQLResultSet -ServerName1 myServer1 -DatabaseName1 myDatabase -Query1 "exec dbo.myproc" -ServerName2 myServer2 -DatabaseName2 myDatabase -Query2 "exec dbo.myproc_changed" Could be used to compare two result sets from the same server and database, but two different procedures. Useful for comparing old and new code. .NOTES Author: Josh Feierman Version: 1 #> function Compare-SQLResultSet { [Cmdletbinding()] param ( [parameter(mandatory=$true)] [String]$ServerName1, [parameter(mandatory=$true)] [String]$DatabaseName1, [parameter(mandatory=$true)] [String]$Query1, [parameter(mandatory=$true)] [String]$ServerName2, [parameter(mandatory=$true)] [String]$DatabaseName2, [parameter(mandatory=$true)] [String]$Query2 ) try { if (-not (Get-Module -Name SQLPS -ListAvailable)) { Write-Warning "The SQLPS module is not installed, please obtain and install it." return } Import-Module SQLPS #Get the two result sets $resultSet1 = Invoke-Sqlcmd -ServerInstance $ServerName1 -Database $DatabaseName1 -Query $Query1 $resultSet2 = Invoke-Sqlcmd -ServerInstance $ServerName2 -Database $DatabaseName2 -Query $Query2 #Get a count of records in both sets, so we can iterate over the correct number $firstCount = $resultSet1.Count $secondCount = $resultSet2.Count if ($firstCount -gt $secondCount) {$totalCount = $firstCount} elseif ($secondCount -gt $firstCount) {$totalCount = $secondCount} else {$totalCount = $firstCount} #Begin iteration for ($counter = 0; $counter -lt $totalCount; $counter ++) { #Get the row from the first result set if ($counter -lt $firstCount) { $firstRow = $resultSet1[$counter] } else { $firstRow = $null } if ($counter -lt $secondCount) { $secondRow = $resultSet2[$counter] } else { $secondRow = $null } #Create custom output object for comparison $compareObject = New-Object PSObject -Property @{ RowNumber = $counter + 1 ColumnName = $null FirstValue = $null SecondValue = $null } #Get a list of columns $properties = Get-Member -inputObject $firstRow -MemberType Properties foreach ($property in $properties) { $firstValue = $firstRow.Item($property.Name) $secondValue = $secondRow.Item($property.Name) if ($firstValue -ne $secondValue) { $compareObject.ColumnName = $property.Name $compareObject.FirstValue = $firstValue $compareObject.SecondValue = $secondValue Write-Output $compareObject } } } } catch { Write-Warning $_.Exception.Message } }
PowerShellCorpus/PoshCode/Findup_2.ps1
Findup_2.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 void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { foreach (string d in pathRec) { Recursive(d, searchPattern, recursiveFlag, returnList); } return; } public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { 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))) { Recursive(d, searchPattern, recursiveFlag, returnList); } } catch (Exception e) { Console.WriteLine("Add Directory error: " + e.Message); } } } else { try { 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)) { Recursive(dirPart, filePart, recursiveFlag, returnList); } 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); } } catch (Exception e) { Console.WriteLine("Parse error on: " + pathRec); Console.WriteLine("Exception: " + e.Message); return; } } return; } } 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 bytesInDupes = 0; // bytes in all the duplicates long numOfDupes = 0; // number of duplicate files found. 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 ((System.String.Compare(args[i],"-help",true) == 0) || (System.String.Compare(args[i],"-h",true) == 0)) { 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(" "); return; } if (System.String.Compare(args[i],"-recurse",true) == 0) { recurse = true; continue; } if (System.String.Compare(args[i],"-delete",true) == 0) { delete = true; continue; } if (System.String.Compare(args[i],"-noprompt",true) == 0) { 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"); return; } Recurse recurseMe = new Recurse(); recurseMe.Recursive(paths, "*.*", recurse, fs); if (fs.Count < 2) { Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help"); return; } for (i = 0; i < fs.Count; i++) { if (fs[i].Checked == true) // If file was already matched, then skip to next. continue; for (c = i+1; c < fs.Count; c++) { if (fs[c].Checked == true) // skip already matched inner loop files. 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. bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates. if (delete != true) // if delete is specified, try to delete the duplicate file. 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("Files checked: " + fs.Count); Console.WriteLine("Duplicate files: " + numOfDupes); Console.WriteLine("Bytes in duplicate files: " + bytesInDupes); Console.WriteLine("Duplicates deleted: " + delFiles); Console.WriteLine("Bytes recovered: " + bytesRec); return; } private static readonly byte[] readBuf = new byte[1024]; private static string ComputeInitialHash(string path) { 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/Convert-BounceToX_7.ps1
Convert-BounceToX_7.ps1
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ # $Revision: 610 $ #.Synopsis # Convert Bounce to X500 #.Description # Convert URL Encoded address in a Bounce message to an X500 address # that can be added as an alias to the mail-enabled object #.Parameter bounceAddress # URL Encoded bounce message address# #.Example # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" #.Example # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 [CmdletBinding()] PARAM ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress ) BEGIN { Add-Type -AssemblyName System.Web|Out-Null } PROCESS { if($_) {$bounceAddress = $_} $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" $bounceAddress = $bounceAddress -Replace "%3D","=" $bounceAddress = $bounceAddress -Replace "\\+","%" $bounceAddress = $bounceAddress -Replace "_O=","/O=" $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} }
PowerShellCorpus/PoshCode/Invoke-Inline.ps1
Invoke-Inline.ps1
################################################################################ ## Invoke-Inline.ps1 (originally from Lee Holmes) ## Library support for inline C# ## ## Modified by Joel Bennett to accept include statements, and return collections ## ## Usage ## 1) Define just the body of a C# method, and store it in a string. "Here ## strings" work great for this. The code can be simple: ## ## $codeToRun = "Console.WriteLine(Math.Sqrt(337));" ## ## or more complex, using result.Add(): ## ## $codeToRun = @" ## string firstArg = (string) ((System.Collections.ArrayList) arg)[0]; ## int secondArg = (int) ((System.Collections.ArrayList) arg)[1]; ## ## Console.WriteLine("Hello {0} {1}", firstArg, secondArg ); ## ## result.Add(secondArg * 3); ## "@ ## ## 2) If you must pass arguments, you should make them strongly-typed, ## so that PowerShell doesn't wrap it as a PsObject. ## ## 3) Invoke the inline code, optionally retrieving the return value. You can ## set the return values in your inline code by assigning it to the ## "return" collection as shown above. ## ## $result = Invoke-Inline $usingStatements, $codeToRun $arguments ## $result = Invoke-Inline $codeToRun $arguments ## ## ## If your code is simple enough, you can even do this entirely inline: ## ## Invoke-Inline "Console.WriteLine(Math.Pow(337,2));" ## ################################################################################ param( [string[]] $code, [object[]] $arguments, [string[]] $reference = @() ) ## Stores a cache of generated inline objects. If this library is dot-sourced ## from a script, these objects go away when the script exits. if(-not (Test-Path Variable:\\inlineCode.Cache)) { ${GLOBAL:inlineCode.Cache} = @{} } $using = $null; $source = $null; if($code.length -eq 1) { $source = $code[0] } elseif($code.Length -eq 2){ $using = $code[0] $source = $code[1] } else { Write-Error "You have to pass some code, or this won't do anything ..." } ## un-nesting magic (why do I need this?) $params = @() foreach($arg in $arguments) { $params += $arg } $arguments = $params ## The main function to execute inline C#. ## Pass the argument to the function as a strongly-typed variable. They will ## be available from C# code as the Object variable, "arg". ## Any values assigned to the "returnValue" object by the C# code will be ## returned to MSH as a return value. function main { ## See if the code has already been compiled and cached $cachedObject = ${inlineCode.Cache}[$source] Write-Verbose "Type: $($arguments[0].GetType())" ## The code has not been compiled or cached if($cachedObject -eq $null) { $codeToCompile = @" using System; using System.Collections.Generic; $using public class InlineRunner { public List<object> Invoke(Object[] args) { List<object> result = new List<object>(); $source if( result.Count > 0 ) { return result; } else { return null; } } } "@ Write-Verbose $codeToCompile ## Obtains an ICodeCompiler from a CodeDomProvider class. $provider = New-Object Microsoft.CSharp.CSharpCodeProvider ## Get the location for System.Management.Automation DLL $dllName = [PsObject].Assembly.Location ## Configure the compiler parameters $compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters $assemblies = @("System.dll", $dllName) $compilerParameters.ReferencedAssemblies.AddRange($assemblies) $compilerParameters.ReferencedAssemblies.AddRange($reference) $compilerParameters.IncludeDebugInformation = $true $compilerParameters.GenerateInMemory = $true ## Invokes compilation. $compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $codeToCompile) ## Write any errors if generated. if($compilerResults.Errors.Count -gt 0) { $errorLines = "" foreach($error in $compilerResults.Errors) { $errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText } Write-Error $errorLines } ## There were no errors. Store the resulting object in the object ## cache. else { ${inlineCode.Cache}[$source] = $compilerResults.CompiledAssembly.CreateInstance("InlineRunner") } $cachedObject = ${inlineCode.Cache}[$source] } Write-Verbose "Argument $arguments`n`n$cachedObject" ## Finally invoke the C# code if($cachedObject -ne $null) { return $cachedObject.Invoke($arguments) } } . Main
PowerShellCorpus/PoshCode/Manage ASP_3.NET Providers.ps1
Manage ASP_3.NET Providers.ps1
# Manage_ASP_NET_Providers.ps1 # by Chistian Glessner # http://iLoveSharePoint.com # have to be initialized. If you want to change the app config you have to restart PowerShell param($appConfigPath=$(throw "-appConfigPath is mandatory")) # App config path have to be set before loading System.Web.dll [System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $path ) [void][System.Reflection.Assembly]::LoadWithPartialName("System.Web") # posh 2.0: Add-Type -Assembly "System.Web" function global:Get-MembershipProvider($providerName=$null) { if($providerName -eq $null) { return [System.Web.Security.Membership]::Provider } else { return [System.Web.Security.Membership]::Providers[$providerName] } } function global:Get-RoleProvider($providerName=$null) { if($providerName -eq $null) { return [System.Web.Security.Roles]::Provider } else { return [System.Web.Security.Roles]::Providers[$providerName] } } function global:Get-ProfileProvider($providerName=$null) { if($providerName -eq $null) { return [System.Web.Profile.ProfileManager]::Provider } else { return [System.Web.Profile.ProfileManager]::Providers[$providerName] } }
PowerShellCorpus/PoshCode/My Profile.ps1
My Profile.ps1
## If your PC doesn't have this set already, someone could tamper with this script... ## but at least now, they can't tamper with any of the scripts that I auto-load! Set-ExecutionPolicy AllSigned Process ## Set the profile directory first, so we can refer to it from now on. Set-Variable ProfileDir (Split-Path $MyInvocation.MyCommand.Path -Parent) -Option AllScope ## I determine which modules to pre-load here (in this SIGNED script) $AutoModules = 'Autoload', 'Strings', 'Authenticode', 'HttpRest', 'PoshCode', 'PowerTab', 'ResolveAliases', 'PSCX' ################################################################################################### ## Preload all the modules in AutoModules, printing out their names in color based on status ## No errors while loading modules (I will save them and print them out later) $ErrorActionPreference = "SilentlyContinue" Write-Host "Loading Modules: " -Fore Cyan -NoNewLine $AutoRunErrors = @() ForEach( $module in $AutoModules ) { Import-Module $module -EA SilentlyContinue -EV +script:AutoRunErrors if($?) { Write-Host "$module " -fore Cyan -NoNewLine } else { Write-Host "$module " -fore Red -NoNewLine } } ################################################################################################### Write-Host $ErrorActionPreference = "Continue" # Write out the error messages if we missed loading any modules if($AutoRunErrors) { $AutoRunErrors | Out-String | Write-Host -Fore Red } ################################################################################################### ## I have a few additional custom type and format data items which take prescedence over anyone else's Update-TypeData -PrependPath "$ProfileDir\\Formats\\Types.ps1xml" Update-FormatData -PrependPath "$ProfileDir\\Formats\\Formats.ps1xml" ################################################################################################### ## Developer tools stuff ... ## I need InstallUtil, MSBuild, and TF (TFS) and they're all in the.Net RuntimeDirectory OR Visual Studio*\\Common7\\IDE $Env:Path = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() + ";" + @(Get-Item C:\\Program*Files*\\*Visual?Studio*\\Common7\\IDE\\TF.exe -EA 0| Sort LastWriteTime -Desc)[0].Directory + ";$Env:Path" if(!(Get-Command TF.exe -ErrorAction SilentlyContinue)) { Write-Warning "Could not locate TF.exe in Visual Studio\\Common7. It may not be installed on this PC" } ################################################################################################### ## And a couple of functions that can't be saved as script files, and aren't worth modularizing ## Elipsis shortcut for Select -Expand name ${function:...} = { process { $_.$($args[0]) } } ## The Trinary shortcut function function ?: { param([ScriptBlock]$trueblock,[ScriptBlock]$falseblock) process { if($_){ &$trueblock $_ } else { &$falseblock $_ } } } ## Pre-load a few of my functions in case I need them. ## In particular, a couple that are better than PSCX's versions Autoload New-ShortCut Autoload Edit-File Autoload Get-PerformanceHistory ################################################################################################### ## Custom aliases I can't live without Set-Alias exec Invoke-Expression -Option AllScope -Description "Personal Function alias" Set-Alias edit Edit-File -Option AllScope -Description "Personal Function alias" Set-Alias rand Get-Random -Option AllScope -Description "Personal Cmdlet Alias" Set-Alias say Out-Speech -Option AllScope -Description "Personal Script Alias" Set-Alias gph Get-PerformanceHistory -Option AllScope -Description "Personal Script Alias" ################################################################################################### ## I love my random quotes ... Set-Variable QuoteDir (Resolve-Path (Join-Path (Split-Path $ProfileDir -parent) "@stuff\\Quotes")) -Scope Global -Option AllScope -Description "Personal PATH Variable" Set-Alias RandomLine Select-RandomLine -Option AllScope -Description "Personal Script Alias" Set-Alias Get-Quote Select-RandomLine -Option AllScope -Description "Personal Script Alias" Set-Alias gq Select-RandomLine -Option AllScope -Description "Personal Script Alias" ################################################################################################### ## I add my "Scripts" directory and all of its direct subfolders to my PATH $ENV:PATH = Get-ChildItem $ProfileDir\\Script[s],$ProfileDir\\Scripts\\* | Where-Object { $_.PsIsContainer } | ForEach-Object { $_.FullName } | Join ";" -append $ENV:PATH -unique ## I like all of my sessions to start in my profile directory Set-Location $ProfileDir ## My prompt function is in it's own script . Set-Prompt ## And finally, relax the code signing restriction so we can actually get work done Set-ExecutionPolicy RemoteSigned Process ## Get a random quote, and print it in yellow :D Write-Host $(Get-Quote) -Fore Yellow # SIG # Begin signature block # MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUTf/G2RuXibbNw/GxUxoBclEt # kOKgggUrMIIFJzCCBA+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 # BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQURIrjK39r # ycFCQgjjCok8yydU410wDQYJKoZIhvcNAQEBBQAEggEAaDce6yCDu4TU2JQzCji+ # JlREUjrc5achsjJXN3KqaElxEn4WDX2SZzSy+AfgthUkt0g+usfQhLDmqNBaXJnw # vlrvlq64ABY2z/fBUv5KurXOiSvDxWSGJTflN960TQsKdaO1dzisOSUxizUGAold # r4JvfnsRXGRTFSGnlOvi54VhOlypgsZuh0BXL2JF/6huGWNKXL1eXKz/gFArIeHB # +EcOenddxaUtlhmVV9s3As/MQS1/NRfFy5qa6gmG0nj9Vpn+2nzwMeMiXE4dAiJc # nQ09/WOFXrjhZZIEyNwwdl6lVoJTsL1XTIFOiU2UFK9V8xhNSjIqaGMj9uK1KP5u # zQ== # SIG # End signature block
PowerShellCorpus/PoshCode/Get-VMHostNetworks.ps1
Get-VMHostNetworks.ps1
Function Get-VMHostNetworks { <# .SYNOPSIS Return a list of networks from a given host .DESCRIPTION After connecting to your VI server, we get a list of virtual switches on the datacenter and from that we pull out the VHostID that matches the server we passed in at the command-line. Using the VHostID we return a list of networks objects on that server. .PARAMETER VMHost The name of the VMWare Host Server to pull networks from .PARAMETER VIServer The name of your VSPhere Server .EXAMPLE Get-VMHostNetworks -VMHost v1.copmany.com -VIServer vc.company.com Name Key VLanId PortBinding NumPorts ---- --- ------ ----------- -------- Management Network key-vim.host.PortGroup-Mana... 0 DMZ Network key-vim.host.PortGroup-DMZ ... 100 Admin Network key-vim.host.PortGroup-Admi... 101 Description ----------- This shows the output from the command using all parameters. .NOTES This script requires the VMware vSphere PowerCLI to be downloaded and installed, please see the second link for the download. .LINK http://scripts.patton-tech.com/wiki/PowerShell/VMWareManagement#Get-VMHostNetworks .LINK http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli .LINK http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Connect-VIServer.html .LINK http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-VirtualSwitch.html .LINK http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-VirtualPortGroup.html #> Param ( [string]$VMHost, [string]$VIServer ) Begin { Try { Connect-VIServer -Server $VIServer $VSwitches = Get-VirtualSwitch } Catch { Return $Error[0] } } Process { foreach ($Vswitch in $VSwitches) { If ($VSwitch.VMHost.Name -like "$($VMhost)*") { $VHostID = $VSwitch.VMHost.Id } } $VMNetworks = Get-VirtualPortGroup |Where-Object {$_.VMhostID -eq $VhostID} } End { Return $VMNetworks } }
PowerShellCorpus/PoshCode/Autoload (beta 4).ps1
Autoload (beta 4).ps1
#Requires -Version 2.0 ## Version History ## beta 4 - 2010.05.10 ## I made a few tweaks and bug fixes while testing it's use with PowerBoots. ## beta 3 - 2010.05.10 ## fix for signed scripts (strip signature) ## beta 2 - 2010.05.09 ## implement module support ## beta 1 - 2010.04.14 ## Initial Release ## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time. ## To use: ## 1) Create a function. To be 100% compatible, it should specify pipeline arguments ## For example: <# function Skip-Object { param( [int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $InputObject ) begin { if($Last) { $Queue = new-object System.Collections.Queue $Last } $e = $every; $UpTo++; $u = 0 } process { $InputObject | where { --$First -lt 0 } | foreach { if($Last) { $Queue.EnQueue($_) if($Queue.Count -gt $Last) { $Queue.DeQueue() } } else { $_ } } | foreach { if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo } } | foreach { if($every -and (--$e -le 0)) { $e = $every } else { $_ } } } } #> ## 2) Put the function into a script with the same name (in our case: Skip-Object.ps1) ## 3) Put the script in your PATH ($env:Path) somewhere (i have a "scripts" folder I add to my path as part of my profile) ## 4) Dot-source this file, or include it as part of your profile ## 5) Add one line to your profile (or on the commandline): <# autoload Skip-Object #> ## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it. ## Now, you can just use the function: ## 1..10 | Skip-Object -first 2 -upto 2 function Autoloaded { [CmdletBinding()]Param() DYNAMICPARAM { $CommandName = $MyInvocation.InvocationName if(!$Script:AutoloadHash[$CommandName]) { do { $Alias = $CommandName $CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition } while(!$Script:AutoloadHash[$Alias] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue)) $CommandName = $Alias } if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" } Write-Verbose "Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])" $ScriptName, $ModuleName = $Script:AutoloadHash[$CommandName] if(!$ScriptName){ $ScriptName = $CommandName } if($ModuleName) { $Module = Get-Module $ModuleName } else { $Module = $null } ## Determine the command name based on the alias used to invoke us ## Store the parameter set for use in the function later... $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary # $command = Get-Command $MyInvocation.InvocationName -Type ExternalScript #$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript ) $externalScript = Get-Command $ScriptName -Type ExternalScript Write-Verbose "Processing Script: $($externalScript |Out-String)" $parserrors = $null $prev = $null $script = $externalScript.ScriptContents [System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) [Array]::Reverse($tokens) ForEach($token in $tokens) { if($prev -and $token.Content -eq "# SIG # Begin signature block") { $script = $script.SubString(0, $token.Start ) } if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -eq $CommandName ) { $script = $script.Insert( $prev.Start, "global:" ) } $prev = $token } if($Module) { $script = Invoke-Expression "{ $Script }" Write-Verbose "What the $($Module)" &$Module $Script | Out-Null $command = Get-Command $CommandName -Type Function Write-Verbose "Loaded Module Function: $($command |Out-String)" } else { Invoke-Expression $script | out-null $command = Get-Command $CommandName -Type Function Write-Verbose "Loaded Local Function: $($command |Out-String)" } if(!$command) { throw "Something went wrong autoloading the $($CommandName) function. Function definition doesn't exist in script: $($externalScript.Path)" } Remove-Item Alias::$($CommandName) Write-Verbose "Defined the function and removed the alias... $($command | Out-string)" foreach( $pkv in $command.Parameters.GetEnumerator() ){ $parameter = $pkv.Value if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue } $param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes) $paramdictionary.Add($pkv.Key, $param) } return $paramdictionary }#DynamicParam begin { Write-Verbose "Autoloaded Begin: $CommandName" $command = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::Function ) $scriptCmd = {& $command @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($true) } process { Write-Verbose "Autoloaded Process: $CommandName ($_)" try { if($_) { $steppablePipeline.Process($_) } else { $steppablePipeline.Process() } } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } Write-Verbose "Autoloaded End: $CommandName" } }#AutoLoaded function autoload { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Name , [Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)] [Alias("BaseName")] $Alias = $Name , [Parameter(Position=2,Mandatory=$false)] [String]$Module , [Parameter(Mandatory=$false)] [String]$Scope = '2' ) begin { $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } } process { for($i=0;$i -lt $Name.Count;$i++){ if($Alias -is [Scriptblock]) { $a = $Name[$i] | &$Alias } elseif($Alias -is [Array]) { $a = $Alias[$i] } else { $a = $Alias } Write-Verbose "Set-Alias $Module\\$a Autoloaded -Scope $Scope" Set-Alias $a Autoloaded -Scope $Scope $Script:AutoloadHash[$a] = $Name[$i],$Module Write-Verbose "`$AutoloadHash[$a] = $($Script:AutoloadHash[$a])" } } } $Script:AutoloadHash = @{}
PowerShellCorpus/PoshCode/A Process Block.ps1
A Process Block.ps1
Process { #Get the type of object we have $InputTypeName = $_.GetType().Name #Do something with that object #is it VMware? if ( $InputTypeName -eq "VMHostImpl" ) { $output = $_ | Get-View | Select-Object $VMHost_UUID #is it Xen? } elseif ($InputTypeName -eq "Host"){ $output = $_ | get-view | Select-Object $XenHost_UUID #Otherwise throw an error } else { Write-Host "`nPlease pass this script either a VMHost or VM object on the pipeline.`n" } }
PowerShellCorpus/PoshCode/EchoTest.cmd.ps1
EchoTest.cmd.ps1
@Echo 00: %0 @Echo 01: %1 @Echo 02: %2 @Echo 03: %3 @Echo 04: %4 @Echo 05: %5 @Echo 06: %6 @Echo 07: %7 @Echo 08: %8 @Echo 09: %9 @Echo All together, it looked like this to DOS: @Echo %0 %*
PowerShellCorpus/PoshCode/Get-WebSite_3.ps1
Get-WebSite_3.ps1
function Get-WebPage { <# .SYNOPSIS Downloads web page from site. .DESCRIPTION Downloads web page from site and displays source code or displays total bytes of webpage downloaded .PARAMETER Url URL of the website to test access to. .PARAMETER UseDefaultCredentials Use the currently authenticated user's credentials .PARAMETER Proxy Used to connect via a proxy .PARAMETER Credential Provide alternate credentials .PARAMETER ShowSize Displays the size of the downloaded page in bytes .NOTES Name: Get-WebPage Author: Boe Prox DateCreated: 08Feb2011 .EXAMPLE Get-WebPage -url "http://www.bing.com" Description ------------ Returns the source code from bing.com -showsize .EXAMPLE Get-WebPage -url "http://www.bing.com" -ShowSize Description ------------ Returns the size of the webpage bing.com in bytes. #> [cmdletbinding( DefaultParameterSetName = 'url', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = '', ValueFromPipeline = $True)] [string][ValidatePattern("^(http|https)\\://*")]$Url, [Parameter( Position = 1, Mandatory = $False, ParameterSetName = 'defaultcred')] [switch]$UseDefaultCredentials, [Parameter( Mandatory = $False, ParameterSetName = '')] [string]$Proxy, [Parameter( Mandatory = $False, ParameterSetName = 'altcred')] [switch]$Credential, [Parameter( Mandatory = $False, ParameterSetName = '')] [switch]$ShowSize ) Begin { $psBoundParameters.GetEnumerator() | % { Write-Verbose "Parameter: $_" } #Create the initial WebClient object Write-Verbose "Creating web client object" $wc = New-Object Net.WebClient #Use Proxy address if specified If ($PSBoundParameters.ContainsKey('Proxy')) { #Create Proxy Address for Web Request Write-Verbose "Creating proxy address and adding into Web Request" $wc.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True) } #Determine if using Default Credentials If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) { #Set to True, otherwise remains False Write-Verbose "Using Default Credentials" $webrequest.UseDefaultCredentials = $True } #Determine if using Alternate Credentials If ($PSBoundParameters.ContainsKey('Credentials')) { #Prompt for alternate credentals Write-Verbose "Prompt for alternate credentials" $wc.Credential = (Get-Credential).GetNetworkCredential() } } Process { Try { If ($ShowSize) { #Get the size of the webpage Write-Verbose "Downloading web page and determining size" "{0:N0}" -f ($wr.DownloadString($url) | Out-String).length -as [INT] } Else { #Get the contents of the webpage Write-Verbose "Downloading web page and displaying source code" $wc.DownloadString($url) } } Catch { Write-Warning "$($Error[0])" } } }
PowerShellCorpus/PoshCode/Get-WMIVersions_3.ps1
Get-WMIVersions_3.ps1
#Requires -Version 2 param ( $Credential, $ComputerName ) # The official way to detect .NET versions is to look at their known location on the hard drive as per # this article: http://msdn.microsoft.com/en-us/kb/kb00318785.aspx # thanks to David M (http://twitter.com/makovec) for the WQL $query = "select name from win32_directory where name like 'c:\\\\windows\\\\microsoft.net\\\\framework\\\\v%'" $res = Get-WmiObject -query $query -Credential $Credential -ComputerName $ComputerName | ForEach-Object { Split-Path $_.name -Leaf } | # returns directories Where-Object { $_ -like 'v*' } | # only include those that start with v ForEach-Object { [system.version]( $_ -replace "^v" ) } # remove "v" from the string and convert to version object # Create hashtable with computername and version details $prop = @{ ComputerName = $ComputerName V1Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 0 } ) { $true } } V1_1Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 1 } ) { $true } } V2Present = &{ if ( $res | Where-Object { $_.Major -eq 2 -and $_.Minor -eq 0 } ) { $true } } V3_5Present = &{ if ( $res | Where-Object { $_.Major -eq 3 -and $_.Minor -eq 5 } ) { $true } } V4Present = &{ if ( $res | Where-Object { $_.Major -eq 4 -and $_.Minor -eq 0 } ) { $true } } VersionDetails = $res } # Create and output PSobject using hashtable New-Object PSObject -Property $prop
PowerShellCorpus/PoshCode/New-XVM_4.ps1
New-XVM_4.ps1
#Examples <# New-XVM -Name "WS2012-TestServer01" -SwitchName "Switch(192.168.2.0/24)" -VhdType NoVHD New-XVM -Name "WS2012-TestServer02" -SwitchName "Switch(192.168.2.0/24)" -VhdType ExistingVHD -VhdPath 'D:\\vhds\\WS2012-TestServer02.vhdx' New-XVM -Name "WS2012-TestServer03" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD New-XVM -Name "WS2012-TestServer04" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB New-XVM -Name "WS2012-TestServer05" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Dynamic New-XVM -Name "WS2012-TestServer06" -SwitchName "Switch(192.168.2.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx' New-XVM -Name "WS2012-TestServer07" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB;"BootDevice"="LegacyNetworkAdapter"} #> 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 = "_AllParameterSets" $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 break } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $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 = "_AllParameterSets" $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 break } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $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" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $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 -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { Try { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } 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" } Invoke-Expression -Command $command } End {} }
PowerShellCorpus/PoshCode/out-form with sort colum.ps1
out-form with sort colum.ps1
I think OUT-FORM is a very usefull function. I've added code to sort columns by clicking on headers. You nedd just add the columnTag parameters specifing if colunm value is text or numeric: out-form -data (get-process) -columnNames ("Name", "ID" ) -columnProperties ("Name", "ID") -columnTag ("Text", "Numeric") Hope can help function Out-Form { <# .Synopsis Output the results of a command in a Windows Form .Description Output the results of a command in a Windows Form with possibility to add buttons with actions .Example out-form -title "Services" -data (get-service) -columnNames ("Name", "Status") -columnProperties ("DisplayName", "Status") -actions @{"Start" = {$_.start()}; "Stop" = {$_.stop()};} #> param ($title = "", $data = $null, $columnNames = $null, $columnTag, $columnProperties = $null, $actions = $null) # a little data defaulting/validation if ($columnNames -eq $null) { $columnNames = $columnProperties } if ($columnProperties -eq $null -or $columnNames.Count -lt 1 -or $columnNames.Count -ne $columnNames.Count) { throw "Data validation failed" } $numCols = $columnNames.Count # figure out form width $width = $numCols * 200 $actionWidth = $actions.Count * 100 + 40 if ($actionWidth -gt $width) { $width = $actionWidth } # set up form $form = new-object System.Windows.Forms.Form $form.text = $title $form.size = new-object System.Drawing.Size($width, 400) $panel = new-object System.Windows.Forms.Panel $panel.Dock = "Fill" $form.Controls.Add($panel) $lv = new-object windows.forms.ListView $panel.Controls.Add($lv) # add the buttons $btnPanel = new-object System.Windows.Forms.Panel $btnPanel.Height = 40 $btnPanel.Dock = "Bottom" $panel.Controls.Add($btnPanel) $btns = new-object System.Collections.ArrayList if ($actions -ne $null) { $btnOffset = 20 foreach ($action in $actions.GetEnumerator()) { $btn = new-object windows.forms.Button $btn.DialogResult = [System.Windows.Forms.DialogResult]"OK" $btn.Text = $action.name $btn.Left = $btnOffset $btn.Width = 80 $btn.Top = 10 $exprString = '{$lv.SelectedItems | foreach-object { $_.Tag } | foreach-object {' + $action.value + '}}' $scriptBlock = invoke-expression $exprString $btn.add_Click($scriptBlock) $btnPanel.Controls.Add($btn) $btnOffset += 100 $btns += $btn } } # create the columns $lv.View = [System.Windows.Forms.View]"Details" $lv.Size = new-object System.Drawing.Size($width, 350) $lv.FullRowSelect = $true $lv.GridLines = $true $lv.Dock = "Fill" foreach ($col in $columnNames) { $lv.Columns.Add($col, 200) > $null } # populate the view foreach ($d in $data) { $item = new-object System.Windows.Forms.ListViewItem( (invoke-expression ('$d.' + $columnProperties[0])).tostring()) for ($i = 1; $i -lt $columnProperties.Count; $i++) { $item.SubItems.Add( (invoke-expression ('$d.' + $columnProperties[$i])).tostring()) > $null } $item.Tag = $d $lv.Items.Add($item) > $null } # Added by Bar971.it for ($i = 0; $i -lt $columnTag.Count; $i++) { $lv.Columns[$i].Tag = $columnTag[$i] } $comparerClassString = @" using System; using System.Windows.Forms; using System.Drawing; using System.Collections; public class ListViewItemComparer : System.Collections.IComparer { public int col = 0; public System.Windows.Forms.SortOrder Order; // = SortOrder.Ascending; public ListViewItemComparer() { col = 0; } public ListViewItemComparer(int column, bool asc) { col = column; if (asc) {Order = SortOrder.Ascending;} else {Order = SortOrder.Descending;} } public int Compare(object x, object y) // IComparer Member { if (!(x is ListViewItem)) return (0); if (!(y is ListViewItem)) return (0); ListViewItem l1 = (ListViewItem)x; ListViewItem l2 = (ListViewItem)y; if (l1.ListView.Columns[col].Tag == null) { l1.ListView.Columns[col].Tag = "Text"; } if (l1.ListView.Columns[col].Tag.ToString() == "Numeric") { float fl1 = float.Parse(l1.SubItems[col].Text); float fl2 = float.Parse(l2.SubItems[col].Text); if (Order == SortOrder.Ascending) { return fl1.CompareTo(fl2); } else { return fl2.CompareTo(fl1); } } else { string str1 = l1.SubItems[col].Text; string str2 = l2.SubItems[col].Text; if (Order == SortOrder.Ascending) { return str1.CompareTo(str2); } else { return str2.CompareTo(str1); } } } } "@ Add-Type -TypeDefinition $comparerClassString ` -ReferencedAssemblies (` 'System.Windows.Forms', 'System.Drawing') $bool = $true $columnClick = { $lv.ListViewItemSorter = New-Object ListViewItemComparer($_.Column, $bool) $bool = !$bool } $lv.Add_ColumnClick($columnClick) # End Add by Bar971.it # display it $form.Add_Shown( { $form.Activate() } ) if ($btns.Count -gt 0) { $form.AcceptButton = $btns[0] } $form.showdialog() }
PowerShellCorpus/PoshCode/Read-HostMasked_1.ps1
Read-HostMasked_1.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/The PowerShell Talk 2.ps1
The PowerShell Talk 2.ps1
#The PowerShell Talk #Demo 2 - VM Easy Bake Oven #VMware #Connect to vCenter Get-Credential | connect-viserver -Server "Your vCenter Here" #Create the new VM get-vmhost -Name "ESX Server" | New-VM -Name Dave -DiskMB "10240" -GuestId "otherGuest" -MemoryMB 512 -NumCpu 1 -resourcepool "Demo" #Get some info on said VM get-resourcepool "Demo" | Get-VM | fl * #Change the Memory Get-VM -Name "Dave" | Set-VM -MemoryMB 1024 -confirm:$false #And the Network Get-VM -Name "Dave" | New-NetworkAdapter -NetworkName "Demo" -StartConnected:$true -confirm:$false #Delete the VM Get-VM -Name "Dave" | Remove-Vm -Confirm:$false
PowerShellCorpus/PoshCode/ac3d3fd4-f5da-4eeb-8a26-50cf89f15d26.ps1
ac3d3fd4-f5da-4eeb-8a26-50cf89f15d26.ps1
<# .SYNOPSIS Pulls down the leaderboards for the 2011 Scripting Games .DESCRIPTION Quick and dirty script to pull down the leaderboards for the 2011 scripting games. Can choose either beginner or advanced via a command line switch. .PARAMETER Level The leaderboard to parse .EXAMPLE Get-LeaderBoard -Level Beginner Retrieves the beginner leaderboard. .EXAMPLE Get-LeaderBoard -Level Advanced Retrieves the advanced leaderboard #> function Get-LeaderBoard { param( [Parameter( Position = 0, Mandatory = $true, HelpMessage = "Leaderboard to parse. Advanced, or Beginner")] [ValidateSet("Advanced","Beginner")] [String]$Level="Advanced" ) # create a webclient $WebClient = New-Object System.Net.WebClient # download the page $LeaderPage = $WebClient.DownloadString("http://2011sg.poshcode.org/Reports/TopUsers?filter=$Level") # create a horrific looking regular expression $RegEx = '<a href="/Scripts/By/\\d{1,3}">(?<UserName>[\\w\\s]*)</a>\\s*</td>\\s*<td>\\s*(?<TotalPoints>\\d{1,2}\\.\\d{1,2})\\s*</td>\\s*<td>\\s*(?<ScriptsRated>\\d*)' # split the page into seperate objects so we can parse each invidual $LeaderPage -split "<tr>" | ForEach { # match the regex $_ -match $RegEx | Out-Null # create a new PSObject, supply a hashtable with the properties New-Object PSObject -Property @{ "UserName" = $Matches.UserName "ScriptsRated" = $Matches.ScriptsRated "TotalPoints" = $Matches.TotalPoints "AverageRating" = if ($Matches.ScriptsRated -gt 0) { # get average round to two decimal places "{0:N2}" -f ($Matches.TotalPoints / $Matches.ScriptsRated) } } # clear matches if ($Matches) { $Matches.Clear() } # get our objects in a specific order. } | select -Unique UserName,ScriptsRated,AverageRating,TotalPoints }
PowerShellCorpus/PoshCode/Find Local Group Members_1.ps1
Find Local Group Members_1.ps1
# Author: Hal Rottenberg # Purpose: Find matching members in a local group # Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx # Change these two to suit your needs $ChildGroups = "Domain Admins", "Group Two" $LocalGroup = "Administrators" $MemberNames = @() # uncomment this line to grab list of computers from a file # $Servers = Get-Content serverlist.txt $Servers = $env:computername # for testing on local computer foreach ( $Server in $Servers ) { @@# Put $MemberNames = @() here to clear out the MemberNames variable between servers, otherwise we start to get incorrect results @@ $MemberNames = @() $Group= [ADSI]"WinNT://$Server/$LocalGroup,group" $Members = @($Group.psbase.Invoke("Members")) $Members | ForEach-Object { $MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } $ChildGroups | ForEach-Object { $output = "" | Select-Object Server, Group, InLocalAdmin $output.Server = $Server $output.Group = $_ $output.InLocalAdmin = $MemberNames -contains $_ Write-Output $output } }
PowerShellCorpus/PoshCode/Findup_30.ps1
Findup_30.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}, {"/xj", 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 long errors = 0; 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 + [r]] <files/directories/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(" /xj - Exclude File and Directory Junctions."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances /recurse /noerr /delete"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); Console.WriteLine(" - deletes duplicates after consent is given."); 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 /xfr \\"(jim)\\""); 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)\\""); 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 path 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(args[i]); else { try { Regex rgx = new Regex(args[i], 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"], "*.*", files, optionsbools["/recurse"], optionsbools["/xj"]); 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.WriteLine("Building dictionary of file sizes, SHA512 hashes and full paths..."); var SizeHashFile = new Dictionary<long, Dictionary<string,List<FileInfo>>>(); long filesize = 0; for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) continue; var breakout = false; while (true) { filesize = (files[i].Length); try { var _SHA512 = SHA512.Create(); using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } string SHA512string = Hash2String(_SHA512.Hash); if (!SizeHashFile.ContainsKey(filesize)) SizeHashFile.Add(filesize, new Dictionary<string,List<FileInfo>>()); if (!SizeHashFile[filesize].ContainsKey(SHA512string)) SizeHashFile[filesize][SHA512string] = new List<FileInfo>() {}; SizeHashFile[filesize][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); } if (SizeHashFile.ContainsKey(filesize)) { foreach (var HG in SizeHashFile[filesize]) { if (HG.Value.Count > 1) { Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HG.Value.Count, filesize, filesize * HG.Value.Count); foreach (var finfo in HG.Value) { Console.WriteLine(finfo.FullName); numOfDupes++; dupeBytes += finfo.Length; if (optionsbools["/delete"]) if (DeleteDupe(finfo)) { bytesrecovered += finfo.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("Errors : {0:N0}", errors); Console.WriteLine("Execution time : " + (DateTime.Now - startTime)); } private static void WriteErr(string Str) { errors++; if (!optionsbools["/noerr"]) Console.WriteLine(Str); } private static string Hash2String(Byte[] hasharray) { string SHA512string = ""; foreach (var c in hasharray) { SHA512string += String.Format("{0:x2}", c); } return SHA512string; } 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.ToLower()) == 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, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true) { foreach (string d in pathRec) { getFiles(d, searchPattern, returnList, recursiveFlag, xj); } } private static void getFiles(string[] pathRec, string searchPattern, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true) { foreach (string d in pathRec) { getFiles(d, searchPattern, returnList, recursiveFlag, xj); } } private static void getFiles(string pathRec, string searchPattern, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !xj) if (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); if (((Dir.Attributes & FileAttributes.ReparsePoint) == 0) || !xj) foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !xj) if (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, returnList, recursiveFlag, xj); } 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, returnList, recursiveFlag, xj); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Format-Column.ps1
Format-Column.ps1
function global:Format-Column { ################################################################ #.Synopsis # Formats incoming data to columns. #.Description # It works similarly as Format-Wide but it works vertically. Format-Wide outputs # the data row by row, but Format-Columns outputs them column by column. #.Parameter Property # Name of property to get from the object. # It may be # -- string - name of property. # -- scriptblock # -- hashtable with keys 'Expression' (value is string=property name or scriptblock) # and 'FormatString' (used in -f operator) #.Parameter Column # Number of columns to display. #.Parameter Autosize # Automatically calculate the number of columns to display. #.Parameter MaxColumn # Maximum number of columns to display if using Autosize. #.Parameter Flow # The direction of flow to display items. #.Parameter InputObject # Data to display. #.Example # PS> 1..150 | Format-Column -Autosize #.Example # PS> Format-Column -Col 3 -Input 1..130 #.Example # PS> Get-Process | Format-Column -prop @{Expression='Handles'; FormatString='{0:00000}'} -auto #.Example # PS> Get-Process | Format-Column -prop {$_.Handles} -auto #.Notes # Name: Format-Column # Author: stej, http://twitter.com/stejcz # Version 0.1 - January 6, 2010 - stej # Version 0.2 - January 14, 2010 - stej # - ADDED parameter MaxColumn # - FIXED displaying collection of 1 item was incorrect # Version 0.3 - March 14, 2012 - By Jason Archer (This Version) # - ADDED parameter Flow ################################################################ param( [Parameter(Position=0)][Object]$Property, [Parameter()][switch]$Autosize, [Parameter()][int]$Column, [Parameter()][int]$MaxColumn, [Parameter()][ValidateSet("Horizontal","Vertical")][String]$Flow = "Horizontal", [Parameter(Mandatory=$true,ValueFromPipeline=$true)][Object[]]$InputObject ) begin { [Object[]]$Values = @() } process { $Values += $InputObject } end { function ProcessValues { if ($Property -is [Hashtable]) { $exp = $Property.Expression if ($exp) { if ($exp -is [string]) { $Values = $Values | % { $_.($exp) } } elseif ($exp -is [scriptblock]) { $Values = $Values | % { & $exp $_} } else { throw 'Invalid Expression value' } } if ($Property.FormatString) { if ($Property.FormatString -is [string]) { $Values = $Values | % { $Property.FormatString -f $_ } } else { throw 'Invalid format string' } } } elseif ($Property -is [scriptblock]) { $Values = $Values | % { & $Property $_} } elseif ($Property -is [string]) { $Values = $Values | % { $_.$Property } } elseif ($Property -ne $null) { throw 'Invalid -Property type' } # in case there were some numbers, objects, etc., convert them to string $Values | % { $_.ToString() } } function Base($i) { [Math]::Floor($i) } function Max($i1, $i2) { [Math]::Max($i1, $i2) } if (!$Column) { $Autosize = $true } $Values = ProcessValues $valuesCount = $values.Count if ($valuesCount -eq 1) { $Values | Out-Host return } # For some reason the console host doesn't use the last column and writes to new line $consoleWidth = $Host.UI.RawUI.MaxWindowSize.Width - 1 $spaceWidthBetweenCols = 2 # get length of the longest string $Values | ForEach-Object -Begin { [int]$maxLength = -1 } -Process { $maxLength = Max $maxLength $_.Length } # get count of columns if not provided if ($Autosize) { $Column = Max (Base ($consoleWidth/($maxLength+$spaceWidthBetweenCols))) 1 $remainingSpace = $consoleWidth - $Column*($maxLength+$spaceWidthBetweenCols); if ($remainingSpace -ge $maxLength) { $Column++ } if ($MaxColumn -and $MaxColumn -lt $Column) { Write-Debug "Columns corrected to $MaxColumn (original: $Column)" $Column = $MaxColumn } } $countOfRows = [Math]::Ceiling($valuesCount / $Column) $maxPossibleLength = Base ($consoleWidth / $Column) # cut too long values, considers count of columns and space between them $Values = $Values | ForEach-Object { if ($_.length -gt $maxPossibleLength) { $_.Remove($maxPossibleLength-2) + '..' } else { $_ } } #add empty values so that the values fill rectangle (2 dim array) without space if ($Column -gt 1) { $Values += (@('') * ($countOfRows * $Column - $valuesCount)) } <# now we have values like this: 1, 2, 3, 4, 5, 6, 7, '' #> $formatString = (1..$Column | %{"{$($_-1),-$maxPossibleLength}"}) -join '' 1..$countOfRows | ForEach-Object { $r = $_ - 1 if ($Flow -eq "Horizontal") { <# Display them like this: 1 2 3 4 5 6 7 '' #> $line = @(1..$Column | % { $Values[($r * $Column) + ($_ - 1)]}) } else { <# Display them like this: 1 3 5 7 2 4 6 '' #> $line = @(1..$Column | % { $Values[$r + ($_ - 1) * $countOfRows]}) } $formatString -f $line | Out-Host } } }
PowerShellCorpus/PoshCode/Get-HostsFile_2.ps1
Get-HostsFile_2.ps1
Function Get-HostsFile { <# .SYNOPSIS Retrieves the contents of a hosts file on a specified system. .DESCRIPTION Retrieves the contents of a hosts file on a specified system. .PARAMETER ComputerName The computers to access. .NOTES Name: Get-HostsFile Author: Boe Prox DateCreated: 15Mar2011 1.1 - 2011-03-17 - Jason Archer Improved pipeline support (and fixed positional usage). Added custom object creation and incremental output (better performance and cleaner code). For local host, use local path. Added error messages for error conditions. 1.0 - 2011-03-15 - Boe Prox Initial release. .LINK http://boeprox.wordpress.com .EXAMPLE Get-HostsFile "server1" Description ----------- Retrieves the contents of the hosts file on 'server1'. #> [CmdletBinding()] Param( [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] [ValidateNotNull()] [string[]]$ComputerName = "localhost" ) Begin { $PSBoundParameters.GetEnumerator() | Foreach-Object { Write-Verbose "Parameter: $_" } } Process { Write-Verbose "Starting process of computers" ForEach ($c in $ComputerName ) { Write-Verbose "Testing connection of $c" If (Test-Connection -ComputerName $c -Quiet -Count 1) { Write-Verbose "Validating path to hosts file" if ($c -eq "localhost") { $root = "C:" } else { $root = "\\\\$c\\C`$" } If (Test-Path "$root\\Windows\\system32\\drivers\\etc\\hosts") { Switch -regex -file ("$root\\Windows\\system32\\drivers\\etc\\hosts") { "^#\\w+" { } "^\\d\\w+" { Write-Verbose "Adding IPV4 information to collection" $new = $_.Split("") | Where-Object {$_ -ne ""} If ($new[2] -eq $null) { $notes = $null } Else { $notes = $new[2] } New-Object PSObject -Property @{ ComputerName = $c IPV4 = $new[0] IPV6 = $null Hostname = $new[1] Notes = $notes } } Default { If (!("\\s+" -match $_ -OR $_.StartsWith("#"))) { Write-Verbose "Adding IPV6 information to collection" $new = $_.Split("") | ? {$_ -ne ""} If ($new[2] -eq $null) { $notes = $null } Else { $notes = $new[2] } New-Object PSObject -Property @{ ComputerName = $c IPV4 = $null IPV6 = $new[0] Hostname = $new[1] Notes = $notes } } } } } ElseIf (Test-Path "$root\\WinNT\\system32\\drivers\\etc\\hosts") { Switch -regex -file ("$root\\WinNT\\system32\\drivers\\etc\\hosts") { "^#\\w+" { } "^\\d\\w+" { Write-Verbose "Adding IPV4 information to collection" $new = $_.Split("") | ? {$_ -ne ""} If ($new[2] -eq $null) { $notes = $null } Else { $notes = $new[2] } New-Object PSObject -Property @{ ComputerName = $c IPV4 = $new[0] IPV6 = $null Hostname = $new[1] Notes = $notes } } Default { If (!("\\s+" -match $_ -OR $_.StartsWith("#"))) { Write-Verbose "Adding IPV6 information to collection" $new = $_.Split("") | ? {$_ -ne ""} If ($new[2] -eq $null) { $notes = $null } Else { $notes = $new[2] } New-Object PSObject -Property @{ ComputerName = $c IPV4 = $null IPV6 = $new[0] Hostname = $new[1] Notes = $notes } } } } } Else { ## TODO: Could use the properly localized path not found error Write-Error "Unable to locate host file on computer: $c" } } Else { ## TODO: Could use the properly localized can not locate host error Write-Error "Unable to locate computer: $c" } } } }
PowerShellCorpus/PoshCode/Set-Opacity.ps1
Set-Opacity.ps1
#.Synopsis\n # Mess with the transparency and blur of the PowerShell window\n #.Parameter color\n # The color to treat as transparent (you can set this to your foreground or background for best effect, but you must pass an actual [Drawing.Color]\n #.Parameter opacity\n # On a scale of 0 to 255, how opaque to make the window (255 is no transparency, 0 is invisible)\n #.Parameter Off\n # If set, turns off the color and opacity settings\n #.Parameter Handle\n # The handle of the window to act on. Defaults to the current PowerShell window\n #.Example \n # Set-Opacity -Color ([System.Drawing.Color]::FromArgb( 0xff, 1, 36, 86 ))\n #\n # Makes the PowerShell Blue color completely transparent\n #.Example \n # Set-Opacity -Opacity 200\n #\n # Sets the window partly transparent\n param([byte]$opacity, [System.Drawing.Color]$color, [switch]$Off, [IntPtr]$handle = (ps -Id $pid).MainWindowHandle)\n \n\nAdd-Type -Type @"\nusing System;\nusing System.Runtime.InteropServices;\nnamespace Huddled {\n public class Opacity {\n \n [DllImport("user32.dll")]\n public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);\n \n [DllImport("user32.dll", SetLastError=true)]\n public static extern int GetWindowLong(IntPtr hWnd, int nIndex);\n\n [DllImport("user32.dll")]\n public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);\n }\n \n [StructLayout(LayoutKind.Sequential)]\n public struct ColorRef\n {\n public uint ColorDWORD;\n\n public static implicit operator uint(ColorRef cr) {\n return cr.ColorDWORD;\n }\n public static implicit operator ColorRef(uint crKey) {\n ColorRef cr = new ColorRef();\n cr.ColorDWORD = crKey;\n return cr;\n }\n \n public static implicit operator System.Drawing.Color(ColorRef cr){\n return System.Drawing.Color.FromArgb((int)(0x000000FFU & cr.ColorDWORD), (int)(0x0000FF00U & cr.ColorDWORD) >> 8, (int)(0x00FF0000U & cr.ColorDWORD) >> 16);\n }\n \n public static implicit operator ColorRef(System.Drawing.Color color){\n ColorRef cr = new ColorRef();\n cr.ColorDWORD = (uint)color.R + (((uint)color.G) << 8) + (((uint)color.B) << 16);\n return cr;\n }\n }\n}\n"@ -Ref System.Drawing\n\nfunction global:Set-Opacity {\n #.Synopsis\n # Mess with the transparency and blur of the PowerShell window\n #.Parameter color\n # The color to treat as transparent (you can set this to your foreground or background for best effect, but you must pass an actual [Drawing.Color]\n #.Parameter opacity\n # On a scale of 0 to 255, how opaque to make the window (255 is no transparency, 0 is invisible)\n #.Parameter Off\n # If set, turns off the color and opacity settings\n #.Parameter Handle\n # The handle of the window to act on. Defaults to the current PowerShell window\n #.Example \n # Set-Opacity -Color ([System.Drawing.Color]::FromArgb( 0xff, 1, 36, 86 ))\n #\n # Makes the PowerShell Blue color completely transparent\n #.Example \n # Set-Opacity -Opacity 200\n #\n # Sets the window partly transparent\n param([byte]$opacity, [System.Drawing.Color]$color, [switch]$Off, [IntPtr]$handle = (ps -Id $pid).MainWindowHandle)\n \n if($Off) { \n $style = [Huddled.Opacity]::GetWindowLong($handle, -20) -bor 0x80000 -bxor 0x80000\n } else {\n $style = [Huddled.Opacity]::GetWindowLong($handle, -20) -bor 0x80000 \n }\n $style = [Huddled.Opacity]::SetWindowLong($Handle, -20, $style);\n\n $flag = 0\n if($color) { $flag += 1 } else { $color = [System.Drawing.Color]::Black }\n if($opacity) { $flag += 2 } else { $opacity = 255 }\n \n $null = [Huddled.Opacity]::SetLayeredWindowAttributes($handle, ([uInt32][Huddled.ColorRef]$color), $opacity, $flag)\n}\n\nSet-Opacity @PSBoundParameters
PowerShellCorpus/PoshCode/Get-WebFile _2.7.3.ps1
Get-WebFile _2.7.3.ps1
function Get-WebFile { <# .SYNOPSIS Downloads a file or page from the web. .DESCRIPTION Downloads a file or page from the web (aka wget for PowerShell). .PARAMETER URL The URL to download. .PARAMETER FileName Download file path. If ommitted, the name is autmaitcally determined and downloaded to the current directory. .PARAMETER Passthru Output text files to the pipeline. NOTE: Content type must be text/html, text/xml, Content .PARAMETER Quiet Turn off the progress reports. .EXAMPLE Get-WebFile http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml Download service-names-port-numbers.xml to the current directory. .EXAMPLE Get-WebFile http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml C:\\Temp\\Ports.xml Download service-names-port-numbers.xml and save as C:\\Temp\\Ports.xml .NOTES Get-WebFile by Gwen Dallas (aka wget for PowerShell) History: v3.7.3 - Checks to see if URL is formatted properly (contains http or https) v3.7.2 - Puts a try-catch block around $writer = new-object System.IO.FileStream and returns/breaks to prevent further execution if fso creation fails (e.g. if path is invalid). Note: known issue -- Script hangs if you try to connect to a good FQDN (e.g. www.google.com) with a bad port (e.g. 81). It will work fine if you use "http://192.168.1.1:81" but hang/crash if you use "http://www.google.com:81". v3.7.1 - Puts a try-catch block around the $request.GetResponse() call to prevent further execution if the page does not exist, cannot connect to server, can't resolve host, etc. v3.7 - [int] to [long] to support files larger than 2.0 GB 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) .LINK http://poshcode.org/3219 #> [cmdletbinding()] param( [parameter(Position=0, Mandatory=$true, HelpMessage="URL to download.")] [string]$URL = (Read-Host "The URL to download"), [parameter(Position=1, Mandatory=$false, HelpMessage="Download file path.")] [Object]$FileName = $null, [parameter(HelpMessage="Output text files.")] [switch]$Passthru, [parameter(HelpMessage="Turn off the progress reports.")] [switch]$Quiet ) if ($url.Contains("http")) { $request = [System.Net.HttpWebRequest]::Create($url) } else { $URL_Format_Error = [string]"Connection protocol not specified. Recommended action: Try again using protocol (for example 'http://" + $url + "') instead. Function aborting..." Write-Error $URL_Format_Error return } #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw $request.CookieContainer = New-Object System.Net.CookieContainer try { $responce = $request.GetResponse() Write-Verbose "Responce Status: $($responce.StatusCode) ContentType: $($responce.ContentType) CharacterSet: $($responce.CharacterSet)" } catch { Write-Error $error[0].Exception.InnerException.Message return } if ( $FileName -and -not (Split-Path $FileName) ) { $FileName = Join-Path (Get-Location -PSProvider "FileSystem") $FileName } elseif ((-not $Passthru -and ($FileName -eq $null)) -or (($FileName -ne $null) -and (Test-Path -PathType "Container" $FileName))) { [string]$FileName = ([regex]'(?i)filename=(.*)$').Match( $responce.Headers["Content-Disposition"] ).Groups[1].Value $FileName = $FileName.Trim("\\/""'") if ( -not $FileName ) { $FileName = $responce.ResponseUri.Segments[-1] $FileName = $FileName.Trim("\\/") if(-not $FileName) { $FileName = Read-Host "Please provide a file name" } $FileName = $FileName.trim("\\/") if( -not ([IO.FileInfo]$FileName).Extension) { $FileName = $FileName + "." + $responce.ContentType.Split(";")[0].Split("/")[1] } } $FileName = Join-Path (Get-Location -PSProvider "FileSystem") $FileName } if ( $Passthru ) { try { #Can't encode if character set is $null (e.g. where ContentType is application/xml) if ( $responce.CharacterSet ) { $encoding = [System.Text.Encoding]::GetEncoding( $responce.CharacterSet ) [string]$output = "" } else { Write-Warning "Can't output ContentType: $($responce.ContentType) to the pipeline." $Passthru = $false } } catch { Write-Error $error[0].Exception.InnerException.Message return } } if ( $responce.StatusCode -eq 200 ) { [long]$goal = $responce.ContentLength $reader = $responce.GetResponseStream() if ($FileName) { try { $writer = New-Object System.IO.FileStream $FileName, "Create" } catch { Write-Error $error[0].Exception.InnerException.Message return } } [byte[]]$buffer = New-Object byte[] 4096 [long]$total = [long]$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 (-not $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 } } $responce.Close() if ( $FileName ) { Get-Item $FileName } }#end
PowerShellCorpus/PoshCode/Search-WmiNamespace.ps1
Search-WmiNamespace.ps1
##############################################################################\n##\n## Search-WmiNamespace\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\nSearch the WMI classes installed on the system for the provided match text.\n\n.EXAMPLE\n\nSearch-WmiNamespace Registry\nSearches WMI for any classes or descriptions that mention "Registry"\n\n.EXAMPLE\n\nSearch-WmiNamespace Process ClassName,PropertyName\nSearchs WMI for any classes or properties that mention "Process"\n\n.EXAMPLE\n\nSearch-WmiNamespace CPU -Detailed\nSearches WMI for any class names, descriptions, or properties that mention\n"CPU"\n\n#>\n\nparam(\n ## The pattern to search for\n [Parameter(Mandatory = $true)]\n [string] $Pattern,\n\n ## Switch parameter to look for class names, descriptions, or properties\n [switch] $Detailed,\n\n ## Switch parameter to look for class names, descriptions, properties, and\n ## property description.\n [switch] $Full,\n\n ## Custom match options.\n ## Supports any or all of the following match options:\n ## ClassName, ClassDescription, PropertyName, PropertyDescription\n [string[]] $MatchOptions = ("ClassName","ClassDescription")\n)\n\nSet-StrictMode -Off\n\n## Helper function to create a new object that represents\n## a Wmi match from this script\nfunction New-WmiMatch\n{\n param( $matchType, $className, $propertyName, $line )\n\n $wmiMatch = New-Object PsObject -Property @{\n MatchType = $matchType;\n ClassName = $className;\n PropertyName = $propertyName;\n Line = $line\n }\n\n $wmiMatch\n}\n\n## If they've specified the -detailed or -full options, update\n## the match options to provide them an appropriate amount of detail\nif($detailed)\n{\n $matchOptions = "ClassName","ClassDescription","PropertyName"\n}\n\nif($full)\n{\n $matchOptions =\n "ClassName","ClassDescription","PropertyName","PropertyDescription"\n}\n\n## Verify that they specified only valid match options\nforeach($matchOption in $matchOptions)\n{\n $fullMatchOptions =\n "ClassName","ClassDescription","PropertyName","PropertyDescription"\n\n if($fullMatchOptions -notcontains $matchOption)\n {\n $error = "Cannot convert value {0} to a match option. " +\n "Specify one of the following values and try again. " +\n "The possible values are ""{1}""."\n $ofs = ", "\n throw ($error -f $matchOption, ([string] $fullMatchOptions))\n }\n}\n\n## Go through all of the available classes on the computer\nforeach($class in Get-WmiObject -List -Rec)\n{\n ## Provide explicit get options, so that we get back descriptios\n ## as well\n $managementOptions = New-Object System.Management.ObjectGetOptions\n $managementOptions.UseAmendedQualifiers = $true\n $managementClass =\n New-Object Management.ManagementClass $class.Name,$managementOptions\n\n ## If they want us to match on class names, check if their text\n ## matches the class name\n if($matchOptions -contains "ClassName")\n {\n if($managementClass.Name -match $pattern)\n {\n New-WmiMatch "ClassName" `\n $managementClass.Name $null $managementClass.__PATH\n }\n }\n\n ## If they want us to match on class descriptions, check if their text\n ## matches the class description\n if($matchOptions -contains "ClassDescription")\n {\n $description =\n $managementClass.Qualifiers |\n foreach { if($_.Name -eq "Description") { $_.Value } }\n if($description -match $pattern)\n {\n New-WmiMatch "ClassDescription" `\n $managementClass.Name $null $description\n }\n }\n\n ## Go through the properties of the class\n foreach($property in $managementClass.Properties)\n {\n ## If they want us to match on property names, check if their text\n ## matches the property name\n if($matchOptions -contains "PropertyName")\n {\n if($property.Name -match $pattern)\n {\n New-WmiMatch "PropertyName" `\n $managementClass.Name $property.Name $property.Name\n }\n }\n\n ## If they want us to match on property descriptions, check if\n ## their text matches the property name\n if($matchOptions -contains "PropertyDescription")\n {\n $propertyDescription =\n $property.Qualifiers |\n foreach { if($_.Name -eq "Description") { $_.Value } }\n if($propertyDescription -match $pattern)\n {\n New-WmiMatch "PropertyDescription" `\n $managementClass.Name $property.Name $propertyDescription\n }\n }\n }\n}
PowerShellCorpus/PoshCode/Select-ViaGUI.ps1
Select-ViaGUI.ps1
## Select-ViaGui.ps1 ## Use a graphical interface to select (and pass-through) pipeline objects ## originally by Lee Holmes (http://www.leeholmes.com/blog), although he might not recognize it now ;-) Import-Module ShowUI ## Get the item as it would be displayed by Format-Table ## Generate the window Show-UI -Title "Object Filter" -MinWidth 400 -Height 600 { param($InputItems) Grid -Margin 5 -RowDefinitions Auto, *, Auto, Auto { # 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 $StringItems = New-Object System.Collections.ArrayList # So, use a hashtable, with the strings as the keys to the original values $originalItems = @{} ## Convert input to string representations and store ... foreach($item in $InputItems) { $stringRepresentation = (($item | ft -HideTableHeaders | Out-String )-Split"\\n")[-4].trimEnd() $originalItems[$stringRepresentation] = $item $null = $StringItems.Add($stringRepresentation) } ## This is just a label ... TextBlock -Margin 5 -Grid-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 -Grid-Row 1 { ListBox -SelectionMode Multiple -ItemsSource $StringItems -Name SelectedItems ` -FontFamily "Consolas, Courier New" -On_MouseDoubleClick { param($source,$e) $originalItems[$e.OriginalSource.DataContext] | Write-UIOutput $ShowUI.ActiveWindow.Close() } } ## This is the filter box: Notice we update the filter on_KeyUp TextBox -Margin 5 -Name SearchText -Grid-Row 2 -On_KeyUp { $filterText = $this.Text $SelectedItems = Select-UIElement "Object Filter" SelectedItems [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 } } ## An event handler for the OK button, to send the selected items down the pipeline function OK_Click { $selectedItems = Select-UIElement "Object Filter" SelectedItems $source = $selectedItems.Items if($selectedItems.SelectedItems.Count -gt 0) { $source = $selectedItems.SelectedItems } ## Use Write-UIOutput to send things out from the UI to the pipeline... $originalItems[$source] | Write-UIOutput $ShowUI.ActiveWindow.Close() } ## Use a GridPanel ... it's a simple, yet effective way to lay out a couple of buttons. GridPanel -Margin 5 -HorizontalAlignment Right -ColumnDefinitions 65, 10, 65 { Button "OK" -IsDefault -Width 65 -On_Click OK_Click -"Grid.Column" 0 Button "Cancel" -IsCancel -Width 65 -"Grid.Column" 2 } -"Grid.Row" 3 -Passthru ## Focus on the Search box by default } -On_Loaded { (Select-UIElement $this SearchText).Focus() } ## Don't forget to pass in the pipeline input } -Args $input -Export
PowerShellCorpus/PoshCode/New-StoredProcFunction_2.ps1
New-StoredProcFunction_2.ps1
# New-StoredProcFunction.ps1 # Steven Murawski # http://blog.usepowershell.com # 04/08/2009 # Example: ./New-StoredProcFunction.ps1 'Data Source=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123' sp_createnewcustomer # Example 'sp_createnewcustomer | ./New-StoredProcFunction.ps1 'Data Source=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123' param($ConnectionString, [String[]]$StoredProc= $null) BEGIN { if ($StoredProc.count -gt 0) { $StoredProc | ./New-StoredProcFunction.ps1 $ConnectionString } function Get-StoredProcText() { param ($ProcName, $ConnectionString) $query = @' SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_BODY = 'SQL' AND ROUTINE_NAME LIKE '$_' '@ $connection = New-Object System.Data.SqlClient.SqlConnection $connectionString $command = New-Object System.Data.SqlClient.SqlCommand $query,$connection $connection.Open() $adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command $dataset = New-Object System.Data.DataSet [void] $adapter.Fill($dataSet) $result = $dataSet.Tables | ForEach-Object {$_.Rows} $connection.Close() return $Result.ROUTINE_DEFINITION } function Get-FunctionParameter() { param ($Text) [regex]$EndRegex = '\\)\\s+AS' [regex]$ParamRegex = '@(?<Parameter>\\w+?)\\s+(?<DataType>\\w+(\\(\\d+\\))*)(,|\\s+)*(?<Output>out)*' $ParamStart = $Text.indexof('(') $ParamEnd = $EndRegex.Match($text).index $ParamText = $Text.Substring($ParamStart, ($ParamEnd-$ParamStart)) $RegMatches = $ParamRegex.matches($ParamText) foreach ($RegMatch in $RegMatches) { $Parameter = "" | Select-Object Name, DataType, IsOutput $Parameter.Name = $RegMatch.Groups[3].value $Parameter.DataType = $RegMatch.Groups[4].Value [bool]$Parameter.IsOutput = $RegMatch.Groups[5].Value $Parameter } } } PROCESS { if ($_ -ne $null) { $FunctionName = $_ $StoredProcText = Get-StoredProcText $FunctionName $ConnectionString $Parameters = Get-FunctionParameter $StoredProcText [String[]]$InputParamNames = $Parameters | where {-not $_.IsOutput} | ForEach-Object {$_.Name} [String[]]$OutputParameterNames = $Parameters | Where-Object {$_.IsOutput} | ForEach-Object {$_.Name} $ScriptText = ' ' if ($InputParamNames.count -gt 0) { $OFS = ', $' $ScriptText += 'param (${0})' -f $InputParamNames $ScriptText += "`n" $OFS = ', ' } $BodyTemplate = @' $connection = New-Object System.Data.SqlClient.SqlConnection('{0}') $command = New-Object System.Data.SqlClient.SqlCommand('{1}', $connection) $command.CommandType = [System.Data.CommandType]::StoredProcedure '@ $ScriptText += $BodyTemplate -f $ConnectionString, $FunctionName if ( ($Parameters -ne $null) -or ($Parameters.count -gt 1) ) { if ($OutputParameterNames.count -gt 0) { $ReturnText = "" $CommandOutput = "" | select $OutputParameterNames } #Add the parameters foreach ($param in $Parameters) { if ($param.datatype -match '(?<type>\\w+)\\((?<nbr>\\d+)\\)') { $ParamTemplate = '$command.Parameters.Add("@{0}", "{1}", {2}) | out-null ' $ScriptText += "`n" $ScriptText += $ParamTemplate -f $param.name, $matches.type, $matches.nbr } else { $ParamTemplate = '$command.Parameters.Add("@{0}", "{1}") | out-null ' $ScriptText += "`n" $ScriptText += $ParamTemplate -f $param.name, $param.datatype } if ($param.IsOutput) { $ScriptText += "`n" $ScriptText += '$command.Parameters["@{0}"].Direction = [System.Data.ParameterDirection]::Output ' -f $param.Name $ReturnText += "`n" $ReturnText += '$CommandOutput.{0} = $command.Parameters["@{0}"].Value' -f $param.name } else { $ScriptText += "`n" $ScriptText += '$command.Parameters["@{0}"].Value = ${0} ' -f $param.name } } } $ScriptText += "`n" $ScriptText += @' $connection.Open() | out-null $command.ExecuteNonQuery() | out-null '@ if ($OutputParameterNames.count -gt 0) { $ScriptText += $ReturnText } $ScriptText += @' $connection.Close() | out-null return $CommandOutput '@ #$ScriptText Set-Item -Path function:global:$FunctionName -Value $scripttext } }
PowerShellCorpus/PoshCode/Reflection Module_1.ps1
Reflection Module_1.ps1
#requires -version 2.0 # ALSO REQUIRES Autoload for some functionality # You should create a Reflection.psd1 with the contents: @{ RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="3.5.0.0" } #History: # 1.0 - First public release (March 19, 2010) # 2.0 - Private Build # - Included the Accelerator function inline # - Added a few default aliases # 3.0 - September 3, 2010 # - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!) # - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312 # 3.5 - January 28, 2011 # - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature # - Fixed alias exporting so aliases will show up now # - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies function Get-Type { <# .Synopsis Gets the types that are currenty loaded in .NET, or gets information about a specific type .Description Gets information about one or more loaded types, or gets the possible values for an enumerated type or value. .Parameter Assembly The Assemblies to search for types. Can be an actual Assembly object or a regex to pass to Get-Assembly. .Parameter TypeName The type name(s) to search for (wildcard patterns allowed). .Parameter BaseType A Base type they should derive from (wildcard patterns allowed). .Parameter Enum An enumeration to list all of enumeration values for .Parameter Namespace A namespace to restrict where we selsect types from (wildcard patterns allowed). .Parameter Force Causes Private types to be included .Example Get-Type Gets all loaded types (takes a VERY long time to print out) .Example Get-Type -Assembly ([PSObject].Assembly) Gets types from System.Management.Automation .Example [Threading.Thread]::CurrentThread.ApartmentState | Get-Type Gets all of the possible values for the ApartmentState property .Example [Threading.ApartmentState] | Get-Type Gets all of the possible values for an apartmentstate #> [CmdletBinding(DefaultParameterSetName="Assembly")] param( # The assembly to collect types from [Parameter(ValueFromPipeline=$true)] [PsObject[]]$Assembly , # The type names to return from [Parameter(Mandatory=$false)] [String[]]$TypeName , # The type names to return from [Parameter(Mandatory=$false)] [String[]]$Namespace , # A Base Type they should derive from [Parameter(Mandatory=$false)] [String[]]$BaseType , # The enumerated value to get all of the possibilties of [Parameter(ParameterSetName="Enum")] [PSObject]$Enum , [Parameter()][Alias("Private","ShowPrivate")] [Switch]$Force ) process { if($psCmdlet.ParameterSetName -eq 'Enum') { if($Enum -is [Enum]) { [Enum]::GetValues($enum.GetType()) } elseif($Enum -is [Type] -and $Enum.IsEnum) { [Enum]::GetValues($enum) } else { throw "Specified Enum is neither an enum value nor an enumerable type" } } else { if($Assembly -as [Reflection.Assembly[]]) { ## This is what we expected, move along } elseif($Assembly -as [String[]]) { $Assembly = Get-Assembly $Assembly } elseif(!$Assembly) { $Assembly = [AppDomain]::CurrentDomain.GetAssemblies() } :asm foreach ($asm in $assembly) { Write-Verbose "Testing Types from Assembly: $($asm.Location)" if ($asm) { trap { if( $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) { $PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail") continue asm } Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail" Write-Debug $( $_.Exception.LoaderExceptions | Out-String ) continue asm } $asm.GetTypes() | Where { ( $Force -or $_.IsPublic ) -AND ( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND ( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND ( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) } } } } } } function Add-Assembly { #.Synopsis # Load assemblies #.Description # Load assemblies from a folder #.Parameter Path # Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). #.Parameter Passthru # Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output. # Aliased to -Types #.Parameter Recurse # Gets the items in the specified locations and in all child items of the locations. # # Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("PSPath")] [string[]]$Path = "." , [Alias("Types")] [Switch]$Passthru , [Switch]$Recurse ) process { foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) { Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic } } } } function Get-Assembly { <# .Synopsis Get a list of assemblies available in the runspace .Description Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match .Parameter Name A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly. #> [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true, Position=0)] [string[]]$Name = '' ) process { [appdomain]::CurrentDomain.GetAssemblies() | Where { $Assembly = $_ if($Name){ $( foreach($n in $Name){ if(Resolve-Path $n -ErrorAction 0) { $n = [Regex]::Escape( (Resolve-Path $n).Path ) } $Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n) } ) -contains $True } else { $true } } } } function Get-Constructor { <# .Synopsis Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type. .Description Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor. .Parameter Type The type to get the constructor for .Parameter Force Force inclusion of Private and Static constructors which are hidden by default. .Parameter NoWarn Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors. .Example Get-Constructor System.IO.FileInfo Description ----------- Gets all the information about the single constructor for a FileInfo object. .Example Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax Description ----------- Displays the constructor syntax for all of the *Info objects in the System.IO namespace. Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors. .Example $path = $pwd $driveName = $pwd.Drive $fileName = "$Profile" Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax } Description ----------- Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo. Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical. #> [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("ParameterType")] [Type]$Type , [Switch]$Force , [Switch]$NoWarn ) process { $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor | Select *, @{ name = "TypeName"; expression = { $_.ReflectedType.FullName } }, @{ name = "Definition"; expression = {Get-MemberSignature $_ -Simple} }, @{ name = "Syntax"; expression = {Get-MemberSignature $_ -Simple} }, @{ name = "SafeSyntax"; expression = {Get-MemberSignature $_} } if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" } } } function Get-Method { <# .Synopsis Returns MethodInfo for the (public) methods of the specified Type. .Description Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method. .Parameter Type The type to get methods on .Parameter Name The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns) .Parameter Force Force inclusion of Private methods and property accessors which are hidden by default. #> [CmdletBinding(DefaultParameterSetName="Type")] param( [Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Type]$Type , [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=1)] [String[]]$Name ="*" , [Switch]$Definition , [Switch]$Force ) process { foreach($method in $type.GetMethods() + $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic } | # Hide the Property accessor methods Where-Object { $Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_" } | Where-Object { $( foreach($n in $Name) { $_.Name -like $n } ) -contains $True } ) { $method | Add-Member NoteProperty TypeName -Value $($method.ReflectedType.FullName ) -Passthru | Add-Member NoteProperty Definition -Value $(Get-MemberSignature $method -Simple) -Passthru | Add-Member AliasProperty Syntax Definition -Passthru | #Add-Member NoteProperty Syntax -Value $(Get-MemberSignature $method -Simple) -Passthru | Add-Member NoteProperty SafeSyntax -Value $(Get-MemberSignature $method ) -Passthru } } } function Get-MemberSignature { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [System.Reflection.MethodBase]$MethodBase, [Switch]$Simple ) process { $parameters = $( foreach($param in $MethodBase.GetParameters()) { # Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)" if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' } if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' } if($Simple) { '{0} {1}' -f $param.ParameterType.ToString(), $param.Name } else { '{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.ToString().TrimEnd('&'), $param.Name } } ) if($MethodBase.IsConstructor) { "New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')" } elseif($Simple) { "$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))" } elseif($MethodBase.IsStatic) { "[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))" } else { "[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))" } } } function Read-Choice { [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] [hashtable[]]$Choices , [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!" , [Parameter(Mandatory=$False)] [string]$Message = "Choose one of the following options:" , [Parameter(Mandatory=$False)] [int[]]$Default = 0 , [Switch]$MultipleChoice , [Switch]$Passthru ) begin { [System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value } ) ) if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } } function Get-Argument { param( [Type]$Target , [String]$Method , $Arguments ) end { trap { write-error $_ break } Write-Verbose "Get $Method Method on $($Target.FullName):" $MethodBase = Get-Method $target $Method Write-Verbose $($MethodBase | Out-String) if(@($MethodBase).Count -gt 1) { $i = 0 $i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:" [System.Reflection.MethodBase]$MethodBase = $MethodBase[$i] } ForEach($parameter in $MethodBase.GetParameters()) { $found = $false For($a =0;$a -lt $Arguments.Count;$a++) { if($argument[$a] -as $parameter.ParameterType) { Write-Output $argument[$a] if($a -gt 0 -and $a -lt $Arguments.Count) { $Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a) } elseif($a -eq 0) { $Arguments = $Arguments | Select -Last ($Arguments.Count - 1) } else { # a -eq count $Arguments = $Arguments | Select -First ($Arguments.Count - 1) } $found = $true break } } if(!$Found) { $userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)" if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) { Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType) } else { Write-Output ($userInput -as $parameter.ParameterType) } } } } } function Invoke-Member { [CmdletBinding()] param( [parameter(position=0, valuefrompipeline=$true, mandatory=$true)] [allownull()] [allowemptystring()] $InputObject , [parameter(position=1, mandatory=$true)] [validatenotnullorempty()] $Method , [parameter(valuefromremainingarguments=$true)] [allowemptycollection()] [object[]]$Arguments , [parameter()] [switch]$Static ) # begin { # if(!(get-member SafeSyntax -input $method -type Property)){ # if(get-member Name -inpup $Method -Type Property) { # $Method = Get-Method $InputObject $Method.Name # } else { # $Method = Get-Method $InputObject $Method # } # } # $SafeSyntax = [ScriptBlock]::Create( $Method.SafeSyntax ) # } process { # if ($InputObject) # { # if ($InputObject | Get-Member $Method -static:$static) # { if ($InputObject -is [type]) { $target = $InputObject } else { $target = $InputObject.GetType() } if($Method -match "ctor|constructor") { $Method = ".ctor" [System.Reflection.BindingFlags]$flags = "CreateInstance" $InputObject = $Null } else { [System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod" if($Static) { $flags += "Static" } else { $flags += "Instance" } } [Object[]]$Parameters = Get-Argument $target $Method $Arguments Write-Verbose "$($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ })" try { Write-Verbose "Invoking $Method on [$target]$InputObject with $flags and $Parameters" Write-Verbose "[$($target.FullName)].InvokeMember('$Method', '$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))" $target.InvokeMember($Method, $flags, $null, $InputObject, $Parameters) } catch { if ($_.Exception.Innerexception -is [MissingMethodException]) { write-warning "Method argument count (or type) mismatch." } } # } else { # write-warning "Method $Method not found." # } # } } } function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On','Type')] $InputObject , [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName , [Parameter(Position=2)] [Alias('Returns')] [Type[]]$Types , [Parameter(Position=3, ValueFromPipelineByPropertyName=$true)] [Type[]]$ArgumentTypes , [Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Object[]]$WithArgs ) process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } if($WithArgs) { if(!$ArgumentTypes) { [Type[]]$ArgumentTypes = $withArgs | % { $_.GetType() } } [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject } $Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($Types).Invoke( $on, $Arguments ) } else { [Type[]]$ArgumentTypes = New-Object Type[] 0 $Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($Types).Invoke( $on ) } } } # get a reference to the Type $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") function Import-Namespace { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [string]$Namespace , [Switch]$Force ) Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator } function Add-Accelerator { <# .Synopsis Add a type accelerator to the current session .Description The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]). .Example Add-Accelerator list System.Collections.Generic.List``1 $list = New-Object list[string] Creates an accelerator for the generic List[T] collection type, and then creates a list of strings. .Example Add-Accelerator "List T", "GList" System.Collections.Generic.List``1 $list = New-Object "list t[string]" Creates two accelerators for the Generic List[T] collection type. .Parameter Accelerator The short form accelerator should be just the name you want to use (without square brackets). .Parameter Type The type you want the accelerator to accelerate (without square brackets) .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64]) Also see the help for Get-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding()] param( [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator , [Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type]$Type ) process { # add a user-defined accelerator foreach($a in $Accelerator) { $xlr8r::Add( $a, $Type) trap [System.Management.Automation.MethodInvocationException] { if($xlr8r::get.keys -contains $a) { if($xlr8r::get[$a] -ne $Type) { Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]" } Continue; } throw } } } } function Get-Accelerator { <# .Synopsis Get one or more type accelerator definitions .Description The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type .Example Get-Accelerator System.String Returns the KeyValue pair for the [System.String] accelerator(s) .Example Get-Accelerator ps*,wmi* Returns the KeyValue pairs for the matching accelerator definition(s) .Parameter Accelerator One or more short form accelerators to search for (Accept wildcard characters). .Parameter Type One or more types to search for. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". Also see the help for Add-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(DefaultParameterSetName="ByType")] param( [Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator , [Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type[]]$Type ) process { # add a user-defined accelerator switch($PSCmdlet.ParameterSetName) { "ByAccelerator" { $xlr8r::get.GetEnumerator() | % { foreach($a in $Accelerator) { if($_.Key -like $a) { $_ } } } break } "ByType" { if($Type -and $Type.Count) { $xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value } } else { $xlr8r::get.GetEnumerator() | %{ $_ } } break } } } } function Remove-Accelerator { <# .Synopsis Remove a type accelerator from the current session .Description The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators. .Example Remove-Accelerator int Add-Accelerator int Int64 Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works: So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64" .Example Get-Accelerator System.Single | Remove-Accelerator Removes both of the default accelerators for System.Single: [float] and [single] .Example Get-Accelerator System.Single | Remove-Accelerator -WhatIf Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print: What if: Removes the alias [float] for type [System.Single] What if: Removes the alias [single] for type [System.Single] .Parameter Accelerator The short form accelerator that you want to remove (Accept wildcard characters). .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Add-Accelerator and Get-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","FullName")] [string[]]$Accelerator ) process { foreach($a in $Accelerator) { foreach($key in $xlr8r::Get.Keys -like $a) { if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]", "Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?", "Removing Type Accelerator" )) { # remove a user-defined accelerator $xlr8r::remove($key) } } } } } ############################################################################### ##### Imported from PowerBoots $Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree' $DependencyProperties = @{} if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) { #$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) ) $DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml } function Get-ReflectionModule { $executioncontext.sessionstate.module } function Set-ObjectProperties { [CmdletBinding()] param( $Parameters, [ref]$DObject ) if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() } if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White } foreach ($param in $Parameters) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" } ## INGORE DEPENDENCY PROPERTIES FOR NOW :) if($param.Key -eq "DependencyProps") { ## HANDLE EVENTS .... } elseif ($param.Key.StartsWith("On_")) { $EventName = $param.Key.SubString(3) if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" } $sb = $param.Value -as [ScriptBlock] if(!$sb) { $sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock } $Dobject.Value."Add_$EventName".Invoke( $sb ); # $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) ); # $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) ); } ## HANDLE PROPERTIES .... else { try { ## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here. if($DebugPreference -ne "SilentlyContinue") { Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray } if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) { $Values = @() foreach($sb in $param.Value) { $Values += & (Get-ReflectionModule) $sb } } else { $Values = $param.Value } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green } Set-Property $Dobject $Param.Key $Values if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta } if($DebugPreference -ne "SilentlyContinue") { if( $Dobject.Value.$($param.Key) -ne $null ) { Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green } } } catch [Exception] { Write-Host "COUGHT AN EXCEPTION" -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } while($DependencyProps) { $name, $value, $DependencyProps = $DependencyProps $name = ([string]@($name)[0]).Trim("-") if($name -and $value) { Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value } } } if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host } if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() } } function Set-Property { PARAM([ref]$TheObject, $Name, $Values) $DObject = $TheObject.Value if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta } $PropertyType = $DObject.GetType().GetProperty($Name).PropertyType if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green} # [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject ) # [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) ) # In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class. [Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject ) [Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) ) $Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null $TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() ) } elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) { $Binding = @($Values)[0]; if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan} if(!$Binding.Source -and !$Binding.ElementName) { $Binding.Source = $DObject.DataContext } if($DependencyProperties.ContainsKey($Name)) { $field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType) if($field) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue } if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue} $DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null } else { throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )" } } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan } try { $DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null # $DObject.Add_Loaded( { # $this.SetBinding( ($this.GetType())::ItemsSourceProperty, (Binding -Source $this.DataContext) ) # } ) if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow } } catch { Write-Host "Nope, was not able to set it." -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } } elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) { if($Values -is [System.Collections.IEnumerable]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan } $DObject.$($Name) = $Values } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan } $DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]" $DObject.$($Name).Add($Values) } } elseif($DObject.$($Name) -is [System.Collections.IList]) { foreach ($value in @($Values)) { try { $null = $DObject.$($Name).Add($value) } catch { # Write-Host "CAUGHT array problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) ) } else { Write-Error $_.Exception throw } } } } else { ## If they pass an array of 1 when we only want one, we just use the first value if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White} try { $DObject.$($Name) = $Values[0] } catch [Exception] { # Write-Host "CAUGHT collection value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $Values[0]) ) }else { throw } } } else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan} try { $DObject.$($Name) = $Values } catch [Exception] { # Write-Host "CAUGHT value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $values) ) }else { throw } } } } } function Set-DependencyProperty { [CmdletBinding()] PARAM( [Parameter(Position=0,Mandatory=$true)] $Property , [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Element , [Parameter()] [Switch]$Passthru ) DYNAMICPARAM { $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary $Param1 = new-object System.Management.Automation.RuntimeDefinedParameter $Param1.Name = "Value" # $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) ) $Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) ) if( $Property ) { if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))) { $Param1.ParameterType = $Property.PropertyType } elseif($Property -is [string] -and $Property.Contains(".")) { $Class,$Property = $Property.Split(".") if($DependencyProperties.ContainsKey($Property)){ $type = $DependencyProperties.$Property.Keys -like "*$Class" if($type) { $Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType } } } elseif($DependencyProperties.ContainsKey($Property)){ if($Element) { if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) { $Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType } } else { $Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType } } else { $Param1.ParameterType = [PSObject] } } else { $Param1.ParameterType = [PSObject] } $paramDictionary.Add("Value", $Param1) return $paramDictionary } PROCESS { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red continue } if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])) ){ trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red continue } $Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType)) } else { if("$Property".Contains(".")) { $Class,$Property = "$Property".Split(".") } if( $DependencyProperties.ContainsKey("$Property" ) ) { $fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } ) if($fields.Count -eq 0 ) { $fields = @($DependencyProperties.$Property.Keys -like "*$Class" ) } if($fields.Count) { $success = $false foreach($field in $fields) { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red continue } $Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType))) if($?) { $success = $true; break } } if(!$success) { throw "food" } } else { Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red } } else { Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red } } if( $Passthru ) { $Element } } } function Add-ConstructorFunction { <# .Synopsis Add support for a new class by creating the dynamic constructor function(s). .Description Creates a New-Namespace.Type function for each type passed in, as well as a short form "Type" alias. Exposes all of the properties and events of the type as perameters to the function. NOTE: The Type MUST have a default parameterless constructor. .Parameter Assembly The Assembly you want to generate constructors for. All public types within it will be generated if possible. .Parameter Type The type you want to create a constructor function for. It must have a default parameterless constructor. .Example Add-ConstructorFunction System.Windows.Controls.Button Creates a new function for the Button control. .Example [Reflection.Assembly]::LoadWithPartialName( "PresentationFramework" ).GetTypes() | Add-ConstructorFunction Will create constructor functions for all the WPF components in the PresentationFramework assembly. Note that you could also load that assembly using GetAssembly( "System.Windows.Controls.Button" ) or Load( "PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) .Example Add-ConstructorFunction -Assembly PresentationFramework Will create constructor functions for all the WPF components in the PresentationFramework assembly. .Links http://HuddledMasses.org/powerboots .ReturnValue The name(s) of the function(s) created -- so you can export them, if necessary. .Notes AUTHOR: Joel Bennett http://HuddledMasses.org LASTEDIT: 2009-01-13 16:35:23 #> [CmdletBinding(DefaultParameterSetName="FromType")] PARAM( [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName="FromType",Mandatory=$true)] [type[]]$type , [Alias("FullName")] [Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ParameterSetName="FromAssembly",Mandatory=$true)] [string[]]$Assembly , [Parameter()] [string]$Path = "$PSScriptRoot\\Types_Generated" , [switch]$Force , [switch]$ShortAliases , [Switch]$Quiet ) BEGIN { [Type[]]$Empty=@() if(!(Test-Path $Path)) { MkDir $Path } $ErrorList = @() } END { #Set-Content -Literal $PSScriptRoot\\DependencyPropertyCache.xml -Value ([System.Windows.Markup.XamlWriter]::Save( $DependencyProperties )) Export-CliXml -Path $PSScriptRoot\\DependencyPropertyCache.xml -InputObject $DependencyProperties if($ErrorList.Count) { Write-Warning "Some New-* functions not aliased." } $ErrorList | Write-Error } PROCESS { if($PSCmdlet.ParameterSetName -eq "FromAssembly") { [type[]]$type = @() foreach($lib in $Assembly) { $asm = $null trap { continue } if(Test-Path $lib) { $asm = [Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path $lib -EA "SilentlyContinue") -EA "SilentlyContinue") ) } if(!$asm) { ## BUGBUG: LoadWithPartialName is "Obsolete" -- but it still works in 2.0/3.5 $asm = [Reflection.Assembly]::LoadWithPartialName( $lib ) } if($asm) { $type += $asm.GetTypes() | ?{ $_.IsPublic -and !$_.IsEnum -and !$_.IsAbstract -and !$_.IsInterface -and $_.GetConstructor( "Instance,Public", $Null, $Empty, @() )} } else { Write-Error "Can't find the assembly $lib, please check your spelling and try again" } } } foreach($T in $type) { $TypeName = $T.FullName $ScriptPath = Join-Path $Path "New-$TypeName.ps1" Write-Verbose $TypeName ## Collect all dependency properties .... $T.GetFields() | Where-Object { $_.FieldType -eq [System.Windows.DependencyProperty] } | ForEach-Object { [string]$Field = $_.DeclaringType::"$($_.Name)".Name [string]$TypeName = $_.DeclaringType.FullName if(!$DependencyProperties.ContainsKey( $Field )) { $DependencyProperties.$Field = @{} } $DependencyProperties.$Field.$TypeName = @{ Name = [string]$_.Name PropertyType = [string]$_.DeclaringType::"$($_.Name)".PropertyType.FullName } } if(!( Test-Path $ScriptPath ) -OR $Force) { $Pipelineable = @(); ## Get (or generate) a set of parameters based on the the Type Name $PropertyNames = New-Object System.Text.StringBuilder "@(" $Parameters = New-Object System.Text.StringBuilder "[CmdletBinding(DefaultParameterSetName='Default')]`nPARAM(`n" ## Add all properties $Properties = $T.GetProperties("Public,Instance,FlattenHierarchy") | Where-Object { $_.CanWrite -Or $_.PropertyType.GetInterface([System.Collections.IList]) } $Properties = ($T.GetEvents("Public,Instance,FlattenHierarchy") + $Properties) | Sort-Object Name -Unique foreach ($p in $Properties) { $null = $PropertyNames.AppendFormat(",'{0}'",$p.Name) switch( $p.MemberType ) { Event { $null = $PropertyNames.AppendFormat(",'{0}__'",$p.Name) $null = $Parameters.AppendFormat(@' [Parameter()] [PSObject]${{On_{0}}} , '@, $p.Name) } Property { if($p.Name -match "^$($CodeGenContentProperties -Join '$|^')`$") { $null = $Parameters.AppendFormat(@' [Parameter(Position=1,ValueFromPipeline=$true)] [Object[]]${{{0}}} , '@, $p.Name) $Pipelineable += @(Add-Member -in $p.Name -Type NoteProperty -Name "IsCollection" -Value $($p.PropertyType.GetInterface([System.Collections.IList]) -ne $null) -Passthru) } elseif($p.PropertyType -eq [System.Boolean]) { $null = $Parameters.AppendFormat(@' [Parameter()] [Switch]${{{0}}} , '@, $p.Name) } else { $null = $Parameters.AppendFormat(@' [Parameter()] [Object[]]${{{0}}} , '@, $p.Name) } } } } $null = $Parameters.Append(' [Parameter(ValueFromRemainingArguments=$true)] [string[]]$DependencyProps )') $null = $PropertyNames.Remove(2,1).Append(')') $collectable = [bool]$(@(foreach($p in @($Pipelineable)){$p.IsCollection}) -contains $true) $ofs = "`n"; $function = $( " if(!( '$TypeName' -as [Type] )) { $( if( $T.Assembly.GlobalAssemblyCache ) { " `$null = [Reflection.Assembly]::Load( '$($T.Assembly.FullName)' ) " } else { " `$null = [Reflection.Assembly]::LoadFrom( '$($T.Assembly.Location)' ) " } ) } ## if(`$ExecutionContext.SessionState.Module.Guid -ne (Get-ReflectionModule).Guid) { ## Write-Warning `"$($T.Name) not invoked in ReflectionModule context. Attempting to reinvoke.`" ## # `$scriptParam = `$PSBoundParameters ## # return iex `"& (Get-ReflectionModule) '`$(`$MyInvocation.MyCommand.Path)' ```@PSBoundParameters`" ## } Write-Verbose ""$($T.Name) in module `$(`$executioncontext.sessionstate.module) context!"" function New-$TypeName { <# .Synopsis Create a new $($T.Name) object .Description Generates a new $TypeName object, and allows setting all of it's properties. (From the $($T.Assembly.GetName().Name) assembly v$($T.Assembly.GetName().Version)) .Notes GENERATOR : $((Get-ReflectionModule).Name) v$((Get-ReflectionModule).Version) by Joel Bennett http://HuddledMasses.org GENERATED : $(Get-Date) ASSEMBLY : $($T.Assembly.FullName) FULLPATH : $($T.Assembly.Location) #> $Parameters BEGIN { `$DObject = New-Object $TypeName `$All = $PropertyNames } PROCESS { " if(!$collectable) { " # The content of $TypeName is not a collection # So if we're in a pipeline, make a new $($T.Name) each time if(`$_) { `$DObject = New-Object $TypeName } " } @' foreach($key in @($PSBoundParameters.Keys) | where { $PSBoundParameters[$_] -is [ScriptBlock] }) { $PSBoundParameters[$key] = $PSBoundParameters[$key].GetNewClosure() } Set-ObjectProperties @($PSBoundParameters.GetEnumerator() | Where { [Array]::BinarySearch($All,($_.Key -replace "^On_(.*)",'$1__')) -ge 0 } ) ([ref]$DObject) '@ if(!$collectable) { @' Microsoft.PowerShell.Utility\\Write-Output $DObject } #Process '@ } else { @' } #Process END { Microsoft.PowerShell.Utility\\Write-Output $DObject } '@ } @" } ## New-$TypeName `@PSBoundParameters "@ ) Set-Content -Path $ScriptPath -Value $Function } # Note: set the aliases global for now, because it's too late to export them # E.g.: New-Button = New-System.Windows.Controls.Button Set-Alias -Name "New-$($T.Name)" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) if($ShortAliases) { # E.g.: Button = New-System.Windows.Controls.Button Set-Alias -Name $T.Name "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) } New-AutoLoad -Name $ScriptPath -Alias "New-$TypeName" } }#PROCESS } function Import-ConstructorFunctions { #.Synopsis # Autoload pre-generated constructor functions and generate aliases for them. #.Description # Parses the New-* scripts in the specified path, and uses the Autoload module to pre-load them as commands and set up aliases for them, without parsing them into memory. #.Parameter Path # The path to a folder with functions to preload param( [Parameter()] [Alias("PSPath")] [string[]]$Path = "$PSScriptRoot\\Types_Generated" ) end { $Paths = $(foreach($p in $Path) { Join-Path $p "New-*.ps1" }) Write-Verbose "Importing Constructors from: `n`t$($Paths -join "`n`t")" foreach($script in Get-ChildItem $Paths -ErrorAction 0) { $TypeName = $script.Name -replace 'New-(.*).ps1','$1' $ShortName = ($TypeName -split '\\.')[-1] Write-Verbose "Importing constructor for type: $TypeName ($ShortName)" # Note: set the aliases global for now, because it's too late to export them # E.g.: New-Button = New-System.Windows.Controls.Button Set-Alias -Name "New-$ShortName" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) if($ShortAliases) { # E.g.: Button = New-System.Windows.Controls.Button Set-Alias -Name $ShortName "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) } New-Autoload -Name $Script.FullName -Alias "New-$TypeName" # Write-Host -fore yellow $(Get-Command "New-$TypeName" | Out-String) Get-Command "New-$TypeName" } } } #.Parameter Snapin # The full path to where the snapin .dll is #.Parameter OutputPath # Force the module manifest(s) to output in a different location than where the snapin .dll is #.Parameter ModuleName # Override the snapin name(s) for the module manifest #.Parameter Author # Overrides the Company Name from the manifest when generating the module's "Author" comment #.Parameter Passthru # Returns the ModuleManifest (same as -Passthru on New-ModuleManifest) #.Example # New-ModuleManifestFromSnapin ".\\Quest Software\\Management Shell for AD" -ModuleName QAD # # Description # ----------- # Generates a new module manifest file: QAD.psd1 in the folder next to the Quest.ActiveRoles.ArsPowerShellSnapIn.dll #.Example # New-ModuleManifestFromSnapin "C:\\Program Files (x86)\\Microsoft SQL Server\\100\\Tools\\Binn\\" -Output $pwd # # Description # ----------- # Generates module manifest files for the SqlServer PSSnapins and stores them in the current folder function New-ModuleManifestFromSnapin { param( [Parameter(Mandatory=$true, Position="0", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [String[]]$Snapin , [Parameter()] $OutputPath , [Parameter()] $ModuleName , [Parameter()] [String]$Author , [Switch]$Passthru ) # $SnapinPath = $(Get-ChildItem $SnapinPath -Filter *.dll) $EAP = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" Add-Assembly $Snapin $ErrorActionPreference = $EAP $SnapinTypes = Get-Assembly $Snapin | Get-Type -BaseType System.Management.Automation.PSSnapIn -WarningAction SilentlyContinue foreach($SnapinType in $SnapinTypes) { $Installer = New-Object $SnapinType if(!$PSBoundParameters.ContainsKey("OutputPath")) { $OutputPath = (Split-Path $SnapinType.Assembly.Location) } if(!$PSBoundParameters.ContainsKey("ModuleName")) { $ModuleName = $Installer.Vendor } if(!$PSBoundParameters.ContainsKey("Author")) { $Author = $Installer.Name } $ManifestPath = (Join-Path $OutputPath "$ModuleName.psd1") Write-Verbose "Creating Module Manifest: $ManifestPath" $RequiredAssemblies = @( $SnapinType.Assembly.GetReferencedAssemblies() | Get-Assembly | Where-Object { (Split-Path $_.Location) -eq (Split-Path $SnapinType.Assembly.Location) } | Select-Object -Expand Location | Resolve-Path -ErrorAction Continue) $Types = $Installer.Types | Resolve-Path -ErrorAction Continue $Formats = $Installer.Formats | Resolve-Path -ErrorAction Continue if(!$Types) { $Types = @() } if(!$Formats) { $Formats = @() } # New-ModuleManifest has a bad bug -- it makes paths relative to the current location (and it does it wrong). Push-Location $OutputPath New-ModuleManifest -Path $ManifestPath -Author $Author -Company $Installer.Vendor -Description $Installer.Description ` -ModuleToProcess $SnapinType.Assembly.Location -Types $Types -Formats $Formats ` -RequiredAssemblies $RequiredAssemblies -Passthru:$Passthru ` -NestedModules @() -Copyright $Installer.Vendor -FileList @() Pop-Location } } ############################################################################### Add-Accelerator list System.Collections.Generic.List``1 Add-Accelerator dictionary System.Collections.Generic.Dictionary``2 Set-Alias aasm Add-Assembly Set-Alias gt Get-Type Set-Alias gasm Get-Assembly Set-Alias gctor Get-Constructor Set-Alias gax Get-Accelerator Set-Alias aax Add-Accelerator Set-Alias rax Remove-Accelerator Export-ModuleMember -Function * -Alias * # SIG # Begin signature block # MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUkJYW6JPKxz+4dOokg9yawy4i # J3ugggUrMIIFJzCCBA+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 # BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUT+azELP/ # woY6L3YYUM4jLhkFEw4wDQYJKoZIhvcNAQEBBQAEggEALhaeyR7d+6dPmocW6XV0 # Ik0c+u4rAS0aQyB9QWYcBwDSqCRRdQx6J4UVC13Lf3Dk2PEo3QzoiTYxvdlkZT4Q # q67JgT7OW5XKjiOKMQYh/zlydc7To2/vtCiu4/vZDEU2sMwlhu8E7LHuTRMODt9j # OnmQZus1asmkwt4cIvJK31FoZfdBHxUMgUwBsx3BBn8O4iGq4GfZHGrxsU7an/bf # +KANyJ3y4LnolTHx+74/9rAO83HJY/6Ps1/VwBEm/bXYmley806QyQwyK2kM7gya # QACvIz6ZOELUmZA52y0fnJ+5NRJovYhblSqoY1qm4jkU9nC3AImF3BunR74YZULZ # lQ== # SIG # End signature block
PowerShellCorpus/PoshCode/out-form with sort colum_1.ps1
out-form with sort colum_1.ps1
I think OUT-FORM is a very usefull function. I've added code to sort columns by clicking on headers. You nedd just add the columnTag parameters specifing if colunm value is text or numeric: out-form -data (get-process) -columnNames ("Name", "ID" ) -columnProperties ("Name", "ID") -columnTag ("Text", "Numeric") Hope can help function Out-Form { <# .Synopsis Output the results of a command in a Windows Form .Description Output the results of a command in a Windows Form with possibility to add buttons with actions .Example out-form -title "Services" -data (get-service) -columnNames ("Name", "Status") -columnProperties ("DisplayName", "Status") -actions @{"Start" = {$_.start()}; "Stop" = {$_.stop()};} #> param ($title = "", $data = $null, $columnNames = $null, $columnTag, $columnProperties = $null, $actions = $null) # a little data defaulting/validation if ($columnNames -eq $null) { $columnNames = $columnProperties } if ($columnProperties -eq $null -or $columnNames.Count -lt 1 -or $columnNames.Count -ne $columnNames.Count) { throw "Data validation failed" } $numCols = $columnNames.Count # figure out form width $width = $numCols * 200 $actionWidth = $actions.Count * 100 + 40 if ($actionWidth -gt $width) { $width = $actionWidth } # set up form $form = new-object System.Windows.Forms.Form $form.text = $title $form.size = new-object System.Drawing.Size($width, 400) $panel = new-object System.Windows.Forms.Panel $panel.Dock = "Fill" $form.Controls.Add($panel) $lv = new-object windows.forms.ListView $panel.Controls.Add($lv) # add the buttons $btnPanel = new-object System.Windows.Forms.Panel $btnPanel.Height = 40 $btnPanel.Dock = "Bottom" $panel.Controls.Add($btnPanel) $btns = new-object System.Collections.ArrayList if ($actions -ne $null) { $btnOffset = 20 foreach ($action in $actions.GetEnumerator()) { $btn = new-object windows.forms.Button $btn.DialogResult = [System.Windows.Forms.DialogResult]"OK" $btn.Text = $action.name $btn.Left = $btnOffset $btn.Width = 80 $btn.Top = 10 $exprString = '{$lv.SelectedItems | foreach-object { $_.Tag } | foreach-object {' + $action.value + '}}' $scriptBlock = invoke-expression $exprString $btn.add_Click($scriptBlock) $btnPanel.Controls.Add($btn) $btnOffset += 100 $btns += $btn } } # create the columns $lv.View = [System.Windows.Forms.View]"Details" $lv.Size = new-object System.Drawing.Size($width, 350) $lv.FullRowSelect = $true $lv.GridLines = $true $lv.Dock = "Fill" foreach ($col in $columnNames) { $lv.Columns.Add($col, 200) > $null } # populate the view foreach ($d in $data) { $item = new-object System.Windows.Forms.ListViewItem( (invoke-expression ('$d.' + $columnProperties[0])).tostring()) for ($i = 1; $i -lt $columnProperties.Count; $i++) { $item.SubItems.Add( (invoke-expression ('$d.' + $columnProperties[$i])).tostring()) > $null } $item.Tag = $d $lv.Items.Add($item) > $null } # Added by Bar971.it for ($i = 0; $i -lt $columnTag.Count; $i++) { $lv.Columns[$i].Tag = $columnTag[$i] } $comparerClassString = @" using System; using System.Windows.Forms; using System.Drawing; using System.Collections; public class ListViewItemComparer : System.Collections.IComparer { public int col = 0; public System.Windows.Forms.SortOrder Order; // = SortOrder.Ascending; public ListViewItemComparer() { col = 0; } public ListViewItemComparer(int column, bool asc) { col = column; if (asc) {Order = SortOrder.Ascending;} else {Order = SortOrder.Descending;} } public int Compare(object x, object y) // IComparer Member { if (!(x is ListViewItem)) return (0); if (!(y is ListViewItem)) return (0); ListViewItem l1 = (ListViewItem)x; ListViewItem l2 = (ListViewItem)y; if (l1.ListView.Columns[col].Tag == null) { l1.ListView.Columns[col].Tag = "Text"; } if (l1.ListView.Columns[col].Tag.ToString() == "Numeric") { float fl1 = float.Parse(l1.SubItems[col].Text); float fl2 = float.Parse(l2.SubItems[col].Text); if (Order == SortOrder.Ascending) { return fl1.CompareTo(fl2); } else { return fl2.CompareTo(fl1); } } else { string str1 = l1.SubItems[col].Text; string str2 = l2.SubItems[col].Text; if (Order == SortOrder.Ascending) { return str1.CompareTo(str2); } else { return str2.CompareTo(str1); } } } } "@ Add-Type -TypeDefinition $comparerClassString ` -ReferencedAssemblies (` 'System.Windows.Forms', 'System.Drawing') $bool = $true $columnClick = { $lv.ListViewItemSorter = New-Object ListViewItemComparer($_.Column, $bool) $bool = !$bool } $lv.Add_ColumnClick($columnClick) # End Add by Bar971.it # display it $form.Add_Shown( { $form.Activate() } ) if ($btns.Count -gt 0) { $form.AcceptButton = $btns[0] } $form.showdialog() }
PowerShellCorpus/PoshCode/Set-WLWAutoLink.ps1
Set-WLWAutoLink.ps1
#requires -version 2 function Set-WLWAutoLink{ param( [Parameter( Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true )] [String]$Name, [Parameter( Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true )] [String]$URL, [Parameter()][switch]$OpenInNewWindow ) begin { $Glossary = "$env:APPDATA\\Windows Live Writer\\LinkGlossary\\linkglossary.xml" if(!(test-path $Glossary)) { throw "linkglossary.xml cannot be found" } else { $xml = [xml](Get-Content $Glossary) $nodeNames = "text","url","title","rel","openInNewWindow" } } process { try{ $node = $xml.glossary.entry | where {$_.text -eq $name} if($node) { Write-Verbose "Updating '$name' node." $node.url = [string]$_.url } else { Write-Verbose "Creating '$name' node." $entry = $xml.CreateElement("entry") $nodeNames | foreach { $null = $entry.AppendChild($xml.CreateElement($_))} $el = $xml.documentElement.AppendChild($entry) $el.text=$Name $el.url=$URL $el.openInNewWindow = "$openInNewWindow" } } catch { Write-Error $_ Continue } } end { try { $xml.save($Glossary) } catch { throw } } }
PowerShellCorpus/PoshCode/Get-ActivesyncUsers.ps1
Get-ActivesyncUsers.ps1
#Get all mailboxes that have an active sync partnership: $Mailboxes = Get-CASMailbox -Filter{HasActiveSyncDevicePartnership -eq $true}| select name, servername, DistinguisheDName, ActiveSyncMailboxPolicy $NumberWiped = 0 $NumberSent =0 $TotalCount = 0 Foreach ($mailbox in $Mailboxes) { $Name = $mailbox.Name $DName= $mailbox.distinguisheDName $Stats = Get-ActiveSyncDeviceStatistics -mailbox $DName if ($Stats -ne $null) { $bodySummary = $bodySummary + "<br />User "+ $mailbox.Name +" is on " +$mailbox.ServerName + " using the " +$mailbox.ActiveSyncMailboxPolicy + " policy" $TotalCount ++ } } $body = "<font color=blue>Executive Summary:<br /><br />There are " + $TotalCount +" mailboxes that have a current Active Sync partnership:<br />" $body = $body + $bodySummary $bodydetail = $bodydetail + "<br /><br />Device Information:" Foreach ($mailbox in $Mailboxes) { $Name = $mailbox.Name $DName= $mailbox.distinguisheDName $Stats = Get-ActiveSyncDeviceStatistics -mailbox $DName if ($Stats.count -gt 1) { $bodydetail = $bodydetail +"<br /><br />User "+ $mailbox.Name + " has the following " + $Stats.Count + " devices:<br />" } elseif($Stats.count -lt 2 -and $Stats -ne $null) { $bodydetail = $bodydetail +"<br /><br />User "+ $mailbox.Name + " has the following device:<br />" $bodydetail = $bodydetail + $Stats.count } if ($Stats.count -lt 2 -and $Stats -ne $null) { if ($Stats.DeviceWipeRequestTime -ne $null) { if ($Stats.DeviceWipeAckTime -ne $null) { $NumberWiped ++ $bodydetail = $bodydetail +"<br /><br />This device was wiped on " + $Stats.DeviceWipeAckTime.ToString() $bodydetail = $bodydetail +"<br />Click here to remove this active sync partnership:<a href= https://webmail.mt.gov/ExchActiveSync/RemoveActiveSyncConfirm.aspx?strIdentity=" + $Stats.Identity +"Remove Partnership>" } else { $NumberSent ++ $bodydetail = $bodydetail +"><br /><font color=red><strong>This device was sent the wipe command on " + $Stats.DeviceWipeRequestTime.ToString() +"</strong></font color>" $bodydetail = $bodydetail +"<br />Click here to remove this active sync partnership:<a href= https://webmail.mt.gov/ExchActiveSync/RemoveActiveSyncConfirm.aspx?strIdentity=" + $Stats.Identity +">Remove Partnership" } } $bodydetail = $bodydetail + "<table><TR><TD>FirstSyncTime </TD><TD>: " + $Stats.FirstSyncTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>LastPolicyUpdateTime </TD><TD>: " + $Stats.LastPolicyUpdateTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>LastSyncAttemptTime </TD><TD>: " + $Stats.LastSyncAttemptTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>LastSuccessSync </TD><TD>: " + $Stats.LastSuccessSync +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceType </TD><TD>: " + $Stats.DeviceType +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceID </TD><TD>: " + $Stats.DeviceID +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceUserAgent </TD><TD>: " + $Stats.DeviceUserAgent +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceWipeSentTime </TD><TD>: " + $Stats.DeviceWipeSentTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceWipeRequestTime </TD><TD>: " + $Stats.DeviceWipeRequestTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceWipeAckTime </TD><TD>: " + $Stats.DeviceWipeAckTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceModel </TD><TD>: " + $Stats.DeviceModel +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceFriendlyName </TD><TD>: " + $Stats.DeviceFriendlyName +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceOS </TD><TD>: " + $Stats.DeviceOS +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceOSLanguage </TD><TD>: " + $Stats.DeviceOSLanguage +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DevicePhoneNumber </TD><TD>: " + $Stats.DevicePhoneNumber +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>Identity </TD><TD>: " + $Stats.Identity +"</TD></TR></table><BR />" } elseif ($Stats.Count -gt 1) { foreach ($Stat in $Stats) { if ($Stat.DeviceWipeRequestTime -ne $null) { if ($Stat.DeviceWipeAckTime -ne $null) { $Wiped= "" $NumberWiped ++ $bodydetail = $bodydetail +"<br /><br />This device was wiped on " + $Stat.DeviceWipeAckTime.ToString() } else { $NumberSent ++ $bodydetail = $bodydetail +"<br /><STRONG><font color=red>This device was sent the wipe command on " + $Stat.DeviceWipeRequestTime.ToString()+"</STRONG></font color>" $bodydetail = $bodydetail +"<br />Click here to remove this active sync partnership:<a href= https://webmail.mt.gov/ExchActiveSync/RemoveActiveSyncConfirm.aspx?strIdentity=" + $Stats.Identity +">Remove Partnership" } } $bodydetail = $bodydetail + "<table><TR><TD>FirstSyncTime </TD><TD>: " + $stat.FirstSyncTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>LastPolicyUpdateTime </TD><TD>: " + $stat.LastPolicyUpdateTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>LastSyncAttemptTime </TD><TD>: " + $stat.LastSyncAttemptTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>LastSuccessSync </TD><TD>: " + $stat.LastSuccessSync +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceType </TD><TD>: " + $stat.DeviceType +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceID </TD><TD>: " + $stat.DeviceID +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceUserAgent </TD><TD>: " + $stat.DeviceUserAgent +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceWipeSentTime </TD><TD>: " + $stat.DeviceWipeSentTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceWipeRequestTime </TD><TD>: " + $stat.DeviceWipeRequestTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceWipeAckTime </TD><TD>: " + $stat.DeviceWipeAckTime +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>LastPingHeartbeat </TD><TD>: " + $stat.LastPingHeartbeat +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceModel </TD><TD>: " + $stat.DeviceModel +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceIMEI </TD><TD>: " + $stat.DeviceIMEI +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceFriendlyName </TD><TD>: " + $stat.DeviceFriendlyName +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceOS </TD><TD>: " + $stat.DeviceOS +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DeviceOSLanguage </TD><TD>: " + $stat.DeviceOSLanguage +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>DevicePhoneNumber </TD><TD>: " + $stat.DevicePhoneNumber +"</TD></TR>" $bodydetail = $bodydetail + "<TR><TD>Identity </TD><TD>: " + $stat.Identity +"</TD></TR></table><BR />" } } } function sendmail([string] $body) { $SmtpClient = new-object system.net.mail.smtpClient $MailMessage = New-Object system.net.mail.mailmessage $SmtpClient.Host = "smtp.host" $mailmessage.from = "From.Address@from.com" $mailmessage.To.add("to.address@to.com") $mailmessage.Subject = "Mailboxes that have an Active Sync Device Partnership" $MailMessage.IsBodyHtml = $False $mailmessage.Body = $body $MailMessage.IsBodyHtml = $TRUE $smtpclient.Send($mailmessage) } $body = $body + "<br /><br />There are $NumberWiped devices that have been wiped." $body = $body + "<br />There are $NumberSent devices that have a pending wipe command.</font color>" $Body = $Body + $BodyDetail sendmail($Body) $bodydetail = "" $Name = "" $bodySummary = ""
PowerShellCorpus/PoshCode/Get-UnityLicense.ps1
Get-UnityLicense.ps1
# # get-unitylicense.ps1 # # Returns license information for a Cisco Unity environment # Usage: get-unitylicense <server> # # Author: Robbie Foust (rfoust@duke.edu) # function global:get-unitylicense ([string]$server = $(throw "Please provide a server name!")) { $webContent = new-object net.webclient $page = $webContent.DownloadString("http://$server/avxml/effectivelicense.asp") # remove leading whitespace $page = $page -replace "^.`n" $license = [xml]$page new-object psobject | add-member -memberType NoteProperty -name LicLanguagesMax -value $license.AvXmlLicData.Licenses.LicLanguagesMax -passthru | add-member -memberType NoteProperty -name LicMaxMsgRecLenIsLicensed -value $license.AvXmlLicData.Licenses.LicMaxMsgRecLenIsLicensed -passthru | add-member -memberType NoteProperty -name LicPoolingIsEnabled -value $license.AvXmlLicData.Licenses.LicPoolingIsEnabled -passthru | add-member -memberType NoteProperty -name LicSubscribersMax -value $license.AvXmlLicData.Licenses.LicSubscribersMax -passthru | add-member -memberType NoteProperty -name LicUMSubscribersMax -value $license.AvXmlLicData.Licenses.LicUMSubscribersMax -passthru | add-member -memberType NoteProperty -name LicVMISubscribersMax -value $license.AvXmlLicData.Licenses.LicVMISubscribersMax -passthru | add-member -memberType NoteProperty -name LicVoicePortsMax -value $license.AvXmlLicData.Licenses.LicVoicePortsMax -passthru | add-member -memberType NoteProperty -name AvLicUtilizationSecondaryServer -value $license.AvXmlLicData.Utilization.AvLicUtilizationSecondaryServer -passthru | add-member -memberType NoteProperty -name AvLicUtilizationSubscribers -value $license.AvXmlLicData.Utilization.AvLicUtilizationSubscribers -passthru | add-member -memberType NoteProperty -name AvLicUtilizationVMISubscribers -value $license.AvXmlLicData.Utilization.AvLicUtilizationVMISubscribers -passthru }
PowerShellCorpus/PoshCode/Backup-ModifiedGPOs.ps1
Backup-ModifiedGPOs.ps1
###########################################################################" # # NAME: Backup-ModifiedGPOs.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: All Group Policy Objects modified in the specified timespan are backup up to the specified backup path. # For more details, see the following blog-post: # http://blog.powershell.no/2010/06/15/backing-up-group-policy-objects-using-windows-powershell # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 15.06.2010 - Initial release # ###########################################################################" #Requires -Version 2.0 Import-Module grouppolicy $BackupPath = "C:\\GPO Backup" $ReportPath = "C:\\GPO Backup\\Reports\\" $Timespan = (Get-Date).AddDays(-1) $ModifiedGPOs = Get-GPO -all | Where-Object {$_.ModificationTime -gt $Timespan} Write-Host "The following "$ModifiedGPOs.count" GPOs were successfully backed up:" -ForegroundColor yellow Foreach ($GPO in $ModifiedGPOs) { $GPOBackup = Backup-GPO $GPO.DisplayName -Path $BackupPath $Path = $ReportPath + $GPO.ModificationTime.Month + "-"+ $GPO.ModificationTime.Day + "-" + $GPO.ModificationTime.Year + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html" Get-GPOReport -Name $GPO.DisplayName -path $Path -ReportType HTML Write-Host $GPO.DisplayName }
PowerShellCorpus/PoshCode/Get-Hostname_4.ps1
Get-Hostname_4.ps1
# .SYNOPSIS # Print the hostname of the system. # .DESCRIPTION # This function prints the hostname of the system. You can additionally output the DNS # domain or the FQDN by using the parameters as described below. # .PARAMETER Short # (Default) Print only the computername, i.e. the same value as returned by $env:computername # .PARAMETER Domain # If set, print only the DNS domain to which the system belongs. Overrides the Short parameter. # .PARAMETER FQDN # If set, print the fully-qualified domain name (FQDN) of the system. Overrides the Domain parameter. param ( [switch]$Short = $true, [switch]$Domain = $false, [switch]$FQDN = $false ) $ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() if ( $FQDN ) { return "{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName } if ( $Domain ) { return $ipProperties.DomainName } if ( $Short ) { return $ipProperties.HostName }
PowerShellCorpus/PoshCode/Invoke-Generic_3.ps1
Invoke-Generic_3.ps1
function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On')] $InputObject , [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName , [Parameter(Position=2)] [Alias("Types")] [Type[]]$ParameterType , [Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Args")] [Object[]]$ArgumentList , [Switch]$Static ) begin { if($Static) { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static" } else { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance" } } process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } if($ArgumentList -and -not $ParameterType) { $ParameterType = $ArgumentList | % { $_.GetType() } } elseif(!$ParameterType) { $ParameterType = [Type]::EmptyTypes } trap { continue } $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags) if(!$MemberInfo) { $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null) } if(!$MemberInfo) { $MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object { $MI = $_ [bool]$Accept = $MI.Name -eq $MethodName if($Accept){ Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)" [Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name) [Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value { $GenericTypes -Contains $this.ParameterType } -Passthru) $Accept = $ParameterType.Count -eq $Parameters.Count Write-Verbose " $Accept = $($Parameters.Count) Arguments" if($Accept) { for($i=0;$i -lt $Parameters.Count;$i++) { $Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterType[$i] -eq $Parameters[$i].ParameterType)) Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterType[$i]) -eq $($Parameters[$i].ParameterType)" } } } return $Accept } | Sort { @($_.GetGenericArguments()).Count } | Select -First 1 } Write-Verbose "Time to make generic methods." Write-Verbose $MemberInfo [Type[]]$GenericParameters = @() [Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType) for($i=0;$i -lt $ParameterType.Count;$i++){ Write-Verbose "$($ParameterType[$i]) ? $($ConcreteTypes[$i] -eq $ParameterType[$i])" if($ConcreteTypes[$i] -ne $ParameterType[$i]) { $GenericParameters += $ParameterType[$i] } $ParameterType[$i] = Add-Member -in $ParameterType[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterType[$i]) -Passthru } $ParameterType | Where-Object { $_.IsGeneric } Write-Verbose "$($GenericParameters -join ', ') generic parameters" $MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters ) Write-Verbose $MemberInfo if($ArgumentList) { [Object[]]$Arguments = $ArgumentList | %{ $_.PSObject.BaseObject } Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')" $MemberInfo.Invoke( $InputObject, $Arguments ) } else { $MemberInfo.Invoke( $InputObject ) } } }
PowerShellCorpus/PoshCode/Monitor-FileSize.ps1
Monitor-FileSize.ps1
function Monitor-FileSize { <# .Synopsis Checks the file size of a given file until it reaches the specified size .Description Checks the file size of a given file until it reaches the specified size. AT that point, it alerts the user as to what the original file-size-boundry was and what it currently is. The interval at which the script runs can be specified by the user. .Parameter FilePath Path of the file that will be monitored. If not pointed to a specific file, the script will montior all sub-directories as well. ie. if pointed to C:\\ drive, will monitor ALL files on C:\\ drive .Parameter Size File size is monitored against this value. When file size is equal or greater than this value, user alert is triggered. Enter size constraints as integer values (ex: -Size 100 NOT -Size 100kb) .Parameter Interval The wait interval between the executions of the function. The value of this parameter is in seconds and default value is 5 seconds .Example Monitor-FileSize -FilePath C:\\Test -Size 100 Returns a message to the user alerting them when at least 100kb worth of memory is stored in the selected location. .Example Monitor-FileSize -FilePath C:\\Test -Size 100 -Interval 20 Checking the size of the file and all sub-directories every 20 seconds .Notes This script cannot be run as a background job and so must have a separate PowerShell window on which it can be running. Author: Paul Kiri. #> param ( [Parameter(mandatory=$true,position=0)] [string[]]$FilePath , [Parameter(mandatory=$true,position=1)] [int]$Size , [Parameter(mandatory=$false)] [int]$Interval=5 ) if((Test-Path $FilePath)) { While($FS -le $Size) { Start-Sleep -Seconds $Interval $FileSize = get-childitem $FilePath -Recurse -Include *.* | foreach-object -Process { $_.length / 1024 } | Measure-Object -Sum | Select-Object -Property Sum $FS = $FileSize.Sum } } #end if Test-Path else{"File does not exist!"} Write-Output "The files at location, $FilePath , have exceeded $Size kb and are now $('{0:N4}' -f $FileSize.Sum) kb in size." }
PowerShellCorpus/PoshCode/Logger.psm1.ps1
Logger.psm1.ps1
<# Name : Universal Log4Net Logging Module (Logger.psm1) Version : 0.1 Author : Joel Bennett (MVP) Site : http://www.HuddledMasses.org/ See Also : http://poshcode.org/1743 You should download this config and put it in your Modules\\Logger folder with this Logger.psm1 Uses Log4Net : http://logging.apache.org/log4net/download.html Documentation: http://logging.apache.org/log4net/release/sdk/ NOTES: By default, this overwrites the Write-* cmdlets for Error, Warning, Debug, Verbose, and even Host. This means that you may end up logging a lot of stuff you didn't intend to log (ie: verbose output from other scripts) ***** BUT IT ONLY WORKS FOR SCRIPTS ***** It currently has no effect on error/verbose/warning that is logged from cmdlets. To avoid this behavior, Import it with a -Prefix, and call it's methods directly. I.E.: Import-Module Logger -Prefix Logged Write-LoggedWarning "This is your warning" Write-LoggedHost "You should know that..." Write-LoggedVerbose "Everything would be logged, otherwise" #> Add-Type -Path $PSScriptRoot\\log4net.dll [Log4Net.Config.BasicConfigurator]::Configure() function Get-Logger { param( [Parameter(Mandatory=$true)] [string]$Name , [Parameter(Mandatory=$false)] [string]$Configuration = "default.config" ) [log4net.LogManager]::GetLogger($Name) | Tee-Object -Variable script:logger if(Test-Path $Configuration) { [log4net.Config.XmlConfigurator]::Configure( ([IO.FileInfo]$Configuration) ) } else { $Configuration = Join-Path $PSScriptRoot $Configuration if(Test-Path $Configuration) { [log4net.Config.XmlConfigurator]::Configure( ([IO.FileInfo]$Configuration) ) } } } function Set-Logger { param( [Parameter(Mandatory=$true)] [log4net.Core.LogImpl]$Logger ) $script:Logger = $Logger } function Push-Context { param( [Parameter(Mandatory=$true)] [string]$Name ) [log4net.NDC]::Push($Name) } function Pop-Context { [log4net.NDC]::Pop() } function Write-Debug { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Alias('Msg')] [AllowEmptyString()] [System.String] ${Message}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Debug', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $logger.debug($Message) #Write-Debug $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Debug .ForwardHelpCategory Cmdlet #> } function Write-Error { [CmdletBinding(DefaultParameterSetName='NoException')] param( [Parameter(ParameterSetName='WithException', Mandatory=$true)] [System.Exception] ${Exception}, [Parameter(ParameterSetName='NoException', Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Parameter(ParameterSetName='WithException')] [Alias('Msg')] [AllowNull()] [AllowEmptyString()] [System.String] ${Message}, [Parameter(ParameterSetName='ErrorRecord', Mandatory=$true)] [System.Management.Automation.ErrorRecord] ${ErrorRecord}, [Parameter(ParameterSetName='NoException')] [Parameter(ParameterSetName='WithException')] [System.Management.Automation.ErrorCategory] ${Category}, [Parameter(ParameterSetName='WithException')] [Parameter(ParameterSetName='NoException')] [System.String] ${ErrorId}, [Parameter(ParameterSetName='NoException')] [Parameter(ParameterSetName='WithException')] [System.Object] ${TargetObject}, [System.String] ${RecommendedAction}, [Alias('Activity')] [System.String] ${CategoryActivity}, [Alias('Reason')] [System.String] ${CategoryReason}, [Alias('TargetName')] [System.String] ${CategoryTargetName}, [Alias('TargetType')] [System.String] ${CategoryTargetType}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Error', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $logger.error($Message,$Exception) #Write-Error $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Error .ForwardHelpCategory Cmdlet #> } function Write-Host { [CmdletBinding()] param( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromRemainingArguments=$true)] [System.Object] ${Object}, [Switch] ${NoNewline}, [System.Object] ${Separator} = $OFS, [System.ConsoleColor] ${ForegroundColor}, [System.ConsoleColor] ${BackgroundColor}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $logger.info(($Object -join $Separator)) #Write-Verbose $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Host .ForwardHelpCategory Cmdlet #> } function Write-Verbose { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Alias('Msg')] [AllowEmptyString()] [System.String] ${Message}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $logger.info($Message) $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Verbose .ForwardHelpCategory Cmdlet #> } function Write-Warning { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Alias('Msg')] [AllowEmptyString()] [System.String] ${Message}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Warning', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $logger.warn($Message) #Write-Warning $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Warning .ForwardHelpCategory Cmdlet #> } $script:defaultLogger = Get-Logger "Default"
PowerShellCorpus/PoshCode/Disconnect-VMHost_1.ps1
Disconnect-VMHost_1.ps1
#requires -version 2 #requires -pssnapin VMware.VimAutomation.Core Function Disconnect-VMHost { <# .Summary Used to Disconnect a Connected host from vCenter. .Parameter VMHost VMHost to Disconnect to virtual center .Example Get-VMHost | Where-Object {$_.state -eq "Connected"} | Disconnect-VMHost Will Attempt to Disconnect any host that are currently Connected. .Example Disconnect-VMHost -Name ESX1.get-admin.local Will Disconnect ESX1 From vCenter #> [CmdletBinding( SupportsShouldProcess=$True, SupportsTransactions=$False, ConfirmImpact="low", DefaultParameterSetName="ByString" )] Param( [Parameter( Mandatory=$True, Valuefrompipeline=$true, ParameterSetName="ByObj" )] [VMware.VimAutomation.Client20.VMHostImpl[]] $VMHost, [Parameter( Mandatory=$True, Position=0, ParameterSetName="ByString" )] [string[]] $Name ) Begin { IF ($Name) { $VMHost = $Name|%{ Get-VMHost -Name $_ } } } process { Foreach ($VMHostImpl in ($VMHost|Get-View)) { if ($pscmdlet.ShouldProcess($VMHostImpl.name)) { $VMHostImpl.DisconnectHost_Task() } } } }
PowerShellCorpus/PoshCode/Open-ISEFile Posh v3.ps1
Open-ISEFile Posh v3.ps1
#Requires -Version 3.0 function Open-ISEFile { <# .NOTES Name: Open-ISEFile Author: Tome Tanasovski Created: 6/20/2010 Version: 2.0a History: 1.0 6/20/2010 Initial Release 2.0 4/1/2012 Updated for v3 Added support to launch in ISE even if you are not in an ISE window via powershell_ise.exe -file .SYNOPSIS Open a new file in ISE .DESCRIPTION This cmdlet allows you to open a file in a new file tab within your current Powershell ISE tab. You can pass a collection of files to open more than one file. If ISE is not open, a new window will be opened. .PARAMETER Path Specifies a path to one or more files. Wildcards are permitted. The default location is the current directory (.). .EXAMPLE Open-ISEFile -Path $profile Opens your profile in ISE. .EXAMPLE dir *.ps1 |Open-ISEFile Opens up all ps1 files in the current directory as new file tabs in ISE. .EXAMPLE Open-ISEFile *.ps1 Opens up all ps1 files in the current directory as new file tabs in ISE. .EXAMPLE $file = Open-ISEFile "c:\\file1.ps1" -PassThru Opens up file1.ps1 in ISE. The command uses the passthru parameter to generate an object that represents a file in ISE. .INPUTS System.String .OUTPUTS None or Microsoft.PowerShell.Host.ISE.ISEFile When you use the PassThru parameter, Open-ISEFile returns a Microsoft.PowerShell.Host.ISE.ISEFile for each file opened. This is only supported when running Open-ISEFile in the PowerShell ISE host. If PassThru is not specified, this cmdlet does not generate any output. .LINK http://powertoe.wordpress.com #> param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline=$true)] [string[]] $Path, [Parameter(Mandatory = $false)] [switch] $PassThru ) BEGIN { $files = @() if (!$psise -and $PassThru) { Write-Warning "PassThru will not work when running Open-ISEFile when you are not in the PowerShell ISE host." } } PROCESS { foreach ($file in $Path) { if (Test-Path $file) { Get-ChildItem $file | foreach { if ($psise) { $file = $psise.CurrentPowerShellTab.Files.Add($_.fullname) if ($PassThru) { $file } } else { $files += $_.fullname } } } } } END { if ($files) { start powershell_ise.exe -ArgumentList ('-file',($files -join ',')) } } }
PowerShellCorpus/PoshCode/Test-Transcribing.ps1
Test-Transcribing.ps1
#requires -version 2.0 function Test-Transcribing { $externalHost = $host.gettype().getproperty("ExternalHost", [reflection.bindingflags]"NonPublic,Instance").getvalue($host, @()) try { $consoleHost.gettype().getproperty("IsTranscribing", [reflection.bindingflags]"NonPublic,Instance").getvalue($consolehost, @()) } catch { write-warning "This host does not support transcription." } }
PowerShellCorpus/PoshCode/Invoke-SqlCmd_7.ps1
Invoke-SqlCmd_7.ps1
####################### <# .SYNOPSIS Runs a T-SQL script. .DESCRIPTION Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified. Paramaterized queries are supported. .INPUTS None You cannot pipe objects to Invoke-Sqlcmd2 .OUTPUTS System.Data.DataTable .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. StartTime ----------- 2010-08-12 21:21:03.593 .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt" This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. VERBOSE: hello world .NOTES Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed Issue with connection closing v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type v1.4 - Justin Dearing <zippy1981 _at_ gmail.com> - Added the ability to pass parameters to the query. #> function Invoke-Sqlcmd2 { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$false)] [string]$Database, [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Username, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15, [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile, [Parameter(Position=8, Mandatory=$false)] [ValidateSet("DataSet", "DataTable", "DataRow")] [string]$As="DataRow" , [Parameter(Position=9, Mandatory=$false)] [System.Collections.IDictionary]$SqlParameters ) if ($InputFile) { $filePath = $(resolve-path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") } $conn=new-object System.Data.SqlClient.SQLConnection if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn.ConnectionString=$ConnectionString #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller if ($PSBoundParameters.Verbose) { $conn.FireInfoMessageEventOnUserErrors=$true $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"} $conn.add_InfoMessage($handler) } $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout if ($SqlParameters -ne $null) { $SqlParameters.GetEnumerator() | ForEach-Object { $cmd.Parameters.AddWithValue($_.Key, $_.Value) } > $null } $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() switch ($As) { 'DataSet' { Write-Output ($ds) } 'DataTable' { Write-Output ($ds.Tables) } 'DataRow' { Write-Output ($ds.Tables[0]) } } } #Invoke-Sqlcmd2
PowerShellCorpus/PoshCode/ASPX Mailbox (4 of 6).ps1
ASPX Mailbox (4 of 6).ps1
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Net.Mail; using System.Text.RegularExpressions; using System.Web.UI; using System.Web.UI.WebControls; public partial class MailboxConfirm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { if (Session["AdminUser"].ToString() == "") { Server.Transfer("MailboxTasks.aspx",false); } else { Session["blKeepAddress"] = chkKeepAddress.Checked; Session["NewAddress"] = newAddress.Text; Server.Transfer("MailboxTaskResults.aspx", true); } } //Variable Definition Collection<PSObject> Results; string strNTUser = Request.ServerVariables["LOGON_USER"]; string strUCNTUser = strNTUser.ToUpper(); string strUserToCheck = strUCNTUser; string strUserName = ""; string strTargName = ""; string strTargPath = ""; string strTask = ""; Session["AdminID"] = ""; Session["DirPath"] = ""; Session["OldAddress"] = ""; Session["NewAddress"] = ""; Session["AdminUser"] = ""; Session["LastName"] = ""; Session["Agency"] = ""; Session["DivisionOU"] = ""; Session["blKeepAddress"] = false; newAddress.Visible = false; chkKeepAddress.Visible = false; chkKeepAddress.Text = "Keep old email addresses"; strTargName = "'" + Request.Form[3] + "'"; strTask = Request.Form[4]; Session["Action"] = strTask; if (strUCNTUser.IndexOf("\\\\", 0) > 0) { strUserToCheck = strUCNTUser.Substring(strUCNTUser.IndexOf("\\\\",0)+1); } strNTUser = strUserToCheck.ToLower(); Results = runposh("dsquery user -samid " + strNTUser); if (Results != null) { strUserName = Results[0].ToString(); } Results = runposh("dsquery user -samid " + strTargName); if (Results != null) { if (Results.Count != 0) { Response.Write("Your logon ID and password are correct<br /><br />"); strTargPath = Results[0].ToString(); fnGetData(strTargPath, strUserName, strUserToCheck, strNTUser, strTask, strTargName); } else { Response.Write("We were unable to locate the object you specified (" + strTargName + "). Please check the name and try again<br /><br />"); fnAddBackButton(); } } } void fnGetData(string strTargPath, string strUserName, string strUserToCheck, string strNTUser, string strTask, string strTargName) { string strPoshCommand = ""; string strAgencyOU = ""; string strDivOU = ""; string strMBXGroup = ""; string strUPN = ""; int intAttaySize = 0; Boolean boolIsMemberOfAdminGroup = false; Boolean boolIsValidCompany = false; Collection<PSObject> Results; #region Find Admin Group strPoshCommand = strTargPath + ".split(',').length"; Results = runposh(strPoshCommand); intAttaySize = int.Parse(Results[0].ToString()); strPoshCommand = ""; for (int i = intAttaySize; i > 0; i--) { strPoshCommand = strPoshCommand + "$part" + i + ","; } strPoshCommand = strPoshCommand.Substring(0, strPoshCommand.Length - 1) + " = " + strTargPath + ".split(',')"; Results = runposh(strPoshCommand); strPoshCommand = "dsget user " + strTargPath + " -company"; //This is the agency Results = runposh(strPoshCommand); if (Results[1].ToString().Trim().Length >= 3) { boolIsValidCompany = true; strAgencyOU = Results[1].ToString().Trim().Substring(0, 3).ToUpper(); strMBXGroup = strAgencyOU + "MailboxAdmins"; } else { Response.Write("User " + strTargName + "'s Active Directory account does not seem to have an agency name in the Company field.<br>We will not be able to create a mailbox until this is corrected.<br>"); boolIsValidCompany = false; strAgencyOU = ""; } #endregion #region Validate Admin Group if (boolIsValidCompany == true) { //Check to see if user is in the admin group strPoshCommand = "dsget user " + strUserName + " -memberof -expand"; Results = runposh(strPoshCommand); for (int i = 0; i < Results.Count - 1; i++) { Array groupcheck = Results[i].ToString().Split(','); string strgroupstring = groupcheck.GetValue(0).ToString(); strgroupstring = strgroupstring.Substring(4); if (strgroupstring.ToUpper() == strMBXGroup.ToUpper()) { boolIsMemberOfAdminGroup = true; break; } if ((strgroupstring.ToLower() == "exchfulladmins") || (strgroupstring.ToLower() == "exch2k7servicedesk")) { boolIsMemberOfAdminGroup = true; break; } } } #endregion #region Results of Admin Group Checks if (boolIsValidCompany == true) { if (boolIsMemberOfAdminGroup == false) { Response.Write("User " + strUserToCheck.ToLower() + " is not a member of " + strMBXGroup + ". You will not be able to modify objects.<br><br>"); } else { if (strMBXGroup.Length > 0) { Response.Write("User " + strUserToCheck.ToLower() + " is a member of " + strMBXGroup + ".<br><br>"); } Results = runposh("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin"); Results = runposh("get-user " + strNTUser + " |fl -property userprincipalname |out-string"); strUPN = Results[0].ToString().Replace("UserPrincipalName :", "").Trim(); switch (strTask.ToLower()) { case "create mailbox": fnCreateMailboxChecks(strTargPath, strUserName, strUserToCheck.ToLower(), strTargName, strAgencyOU); break; case "delete mailbox": fnDeleteMailboxChecks(strTargPath, strUPN, strUserToCheck.ToLower()); break; case "change address": fnChangeAddressChecks(strTargPath, strUserToCheck.ToLower()); break; } } } #endregion } void fnCreateMailboxChecks(string strUserPath, string strAdminUser, string strAdminName, string strTargName, string strAgencyOU) { Collection<PSObject> Results; string strCompany = strAgencyOU; string strLastName = ""; string strExchangeServer = ""; Response.Write("Requested action is Create Mailbox"); Response.Write("<table border>"); Response.Write("<tr><th>Attribute</th><th>Value</th><th>Expected State</th></tr>"); Results = runposh("dsget user " + strUserPath + " -samid"); Response.Write("<tr><td>Logon ID</td><td><b>" + Results[1].ToString() + "</b></td><td>Populated</td></tr>"); Results = runposh("dsget user " + strUserPath + " -display"); Response.Write("<tr><td>Name</td><td><b>" + Results[1].ToString() + "</b></td><td>Populated</td></tr>"); Response.Write("<tr><td>Directory Path</td><td><b>" + strUserPath + "</b></td><td>Populated</td></tr>"); Results = runposh("dsget user " + strUserPath + " -ln"); strLastName = Results[1].ToString(); Response.Write("<tr><td>Last Name</td><td><b>" + strLastName + "</b></td><td>Populated</td></tr>"); Results = runposh("dsget user " + strUserPath + " -company"); strCompany = Results[1].ToString(); Results = runposh("dsget user " + strUserPath + " -upn"); Response.Write("<tr><td>Agency</td><td><b>" + strCompany + "</b></td><td>Populated</td></tr>"); Results = runposh("get-mailbox -identity " + strUserPath + " |fl servername |out-string"); if (Results[0].ToString() != "") { strExchangeServer = Results[0].ToString().TrimEnd(Convert.ToChar(32)).TrimStart(Convert.ToChar(32)); strExchangeServer = strExchangeServer.Substring(17); Response.Write("<tr><td>Exchange Server</td><td><b>" + strExchangeServer + "</b></td><td>Empty</td></tr></table>"); } else { Response.Write("<tr><td>Exchange Server</td><td><b></b></td><td>Empty</td></tr></table>"); } if ((strCompany.Replace(" ","") == "") || (strLastName.Replace(" ","") == "") || ((strExchangeServer.Replace(" ","") != ""))) { Response.Write("<span style='color:Red'>One or more required fields is in an incorrect state. Please check the values listed above and try again.</span>"); fnAddBackButton(); } else { Session["AdminID"] = strAdminUser; Session["AdminUser"] = strAdminName; Session["LastName"] = strLastName; Session["DirPath"] = strUserPath; Session["Agency"] = strCompany; Button btnCreate = new Button(); btnCreate.Attributes.Add("onclick", "this.value='Please wait...';this.disabled= true;" + ClientScript.GetPostBackEventReference(new PostBackOptions(this, "btnCreate"))); btnCreate.Text = "Create Mailbox"; frmMailboxConfirm.Controls.Add(btnCreate); } } void fnDeleteMailboxChecks(string strTargPath, string strAdminUser, string strAdminName) { Collection<PSObject> colDeleteResults; string strExchangeServer; Session["AdminID"] = strAdminUser; Session["AdminUser"] = strAdminName; Session["DirPath"] = strTargPath; Response.Write("Requested action is DELETE Mailbox<br>"); Response.Write("<table border>"); Response.Write("<tr><th>Attribute</th><th>Value</th><th>Expected State</th></tr>"); colDeleteResults = runposh("dsget user " + strTargPath + " -samid"); Response.Write("<tr><td>Logon ID</td><td><b>" + colDeleteResults[1].ToString() + "</b></td><td>Populated</td></tr>"); colDeleteResults = runposh("dsget user " + strTargPath + " -display"); Response.Write("<tr><td>Name</td><td><b>" + colDeleteResults[1].ToString() + "</b></td><td>Populated</td></tr>"); Response.Write("<tr><td>Directory Path</td><td><b>" + strTargPath + "</b></td><td>Populated</td></tr>"); colDeleteResults = runposh("get-mailbox -identity " + strTargPath + " |fl servername |out-string"); if (colDeleteResults[0].ToString() != "") { strExchangeServer = colDeleteResults[0].ToString().TrimEnd(Convert.ToChar(32)).TrimStart(Convert.ToChar(32)); strExchangeServer = strExchangeServer.Substring(17); Response.Write("<tr><td>Exchange Server</td><td><b>" + strExchangeServer + "</b></td><td>Populated</td></tr></table>"); Button btnDelete = new Button(); btnDelete.Attributes.Add("onclick", "this.value='Please wait...';this.disabled= true;" + ClientScript.GetPostBackEventReference(new PostBackOptions(this, "btnDelete"))); btnDelete.Text = "!DELETE Mailbox!"; frmMailboxConfirm.Controls.Add(btnDelete); } else { Response.Write("<tr><td>Exchange Server</td><td><b></b></td><td>Populated</td></tr></table>"); Response.Write("<br /><span style='color:Red'>One or more required fields is in an incorrect state. Please check the values listed above and try again.</span>"); fnAddBackButton(); } } void fnChangeAddressChecks(string strTargetPath, string strAdminName) { Collection<PSObject> colChangeResults; string strCompany = ""; string strLastName = ""; string strEmailAddress = ""; Session["DirPath"] = strTargetPath; Response.Write("Requested action is Change Address"); Response.Write("<table border>"); Response.Write("<tr><th>Attribute</th><th>Value</th><th>Expected State</th></tr>"); colChangeResults = runposh("dsget user " + strTargetPath + " -samid"); Response.Write("<tr><td>Logon ID</td><td><b>" + colChangeResults[1].ToString() + "</b></td><td>Populated</td></tr>"); colChangeResults = runposh("dsget user " + strTargetPath + " -display"); Response.Write("<tr><td>Name</td><td><b>" + colChangeResults[1].ToString() + "</b></td><td>Populated</td></tr>"); Response.Write("<tr><td>Directory Path</td><td><b>" + strTargetPath + "</b></td><td>Populated</td></tr>"); colChangeResults = runposh("get-mailbox -identity " + strTargetPath + " |select PrimarySmtpAddress"); if (colChangeResults.Count != 0) { strEmailAddress = colChangeResults[0].ToString(); strEmailAddress = strEmailAddress.Substring(20); strEmailAddress = strEmailAddress.Substring(1, strEmailAddress.Length - 2); Session["AdminUser"] = strAdminName; Response.Write("<tr><td>Current Adress</td><td><b>" + strEmailAddress + "</b></td><td>Populated</td></tr></table>"); } else { Response.Write("<tr><td>Current Adress</td><td><b></b></td><td>Populated</td></tr></table>"); } Label lblNewAddress = new Label(); lblNewAddress.Text = "New Address: "; lblNewAddress.Style["Position"] = "Absolute"; lblNewAddress.Style["Top"] = "290px"; lblNewAddress.Style["Left"]= "10px"; frmMailboxConfirm.Controls.Add(lblNewAddress); newAddress.Style["Position"] = "Absolute"; newAddress.Style["Top"] = "290px"; newAddress.Style["Left"] = "100px"; newAddress.Visible = true; Label lblDomain = new Label(); lblDomain.Text = "@domain.com"; lblDomain.Style["Position"] = "Absolute"; lblDomain.Style["Top"] = "290px"; lblDomain.Style["Left"] = "270px"; frmMailboxConfirm.Controls.Add(lblDomain); chkKeepAddress.Style["Position"] = "Absolute"; chkKeepAddress.Style["Top"] = "290px"; chkKeepAddress.Style["Left"] = "385px"; chkKeepAddress.Visible = true; colChangeResults = runposh("dsget user " + strTargetPath + " -company"); strCompany = colChangeResults[1].ToString(); colChangeResults = runposh("dsget user " + strTargetPath + " -ln"); strLastName = colChangeResults[1].ToString(); if ((strCompany.Replace(" ", "") == "") || (strLastName.Replace(" ", "") == "") || ((strEmailAddress == ""))) { Response.Write("<span style='color:Red'>One or more required fields is in an incorrect state. Please check the values listed above and try again.</span>"); newAddress.Visible = false; lblNewAddress.Visible = false; lblDomain.Visible = false; fnAddBackButton(); } else { Session["AdminUser"] = strAdminName; Session["LastName"] = strLastName; Session["Agency"] = strCompany; Session["OldAddress"] = strEmailAddress; Session["Action"] = "Change Address"; Session["AdminID"] = strAdminName; Button btnChange = new Button(); btnChange.Attributes.Add("onclick", "this.value='Please wait...';this.disabled= true;" + ClientScript.GetPostBackEventReference(new PostBackOptions(this, "btnChange"))); btnChange.Text = "Change Address"; btnChange.Style["Position"] = "Absolute"; btnChange.Style["Top"] = "325px"; btnChange.Style["Left"] = "10px"; frmMailboxConfirm.Controls.Add(btnChange); } } void fnAddBackButton() { Session["AdminUser"] = ""; Button btnBack = new Button(); btnBack.Attributes.Add("onclick", "this.value='Please wait...';this.disabled= true;" + ClientScript.GetPostBackEventReference(new PostBackOptions(this, "btnBack"))); btnBack.Text = "Return"; frmMailboxConfirm.Controls.Add(btnBack); } protected Collection<PSObject> runposh(string strCommand) { Runspace rs = GetRunspace(); Pipeline currentPipeline = GetPipeline(rs, strCommand); if (currentPipeline.PipelineStateInfo.State == PipelineState.NotStarted) { Collection<PSObject> results = currentPipeline.Invoke(); currentPipeline.Dispose(); Cache.Remove("currentPipe"); return (results); } else { return null; } } protected Runspace GetRunspace() { if (Cache["rs"] == null) { Runspace rs = RunspaceFactory.CreateRunspace(); rs.Open(); Cache["rs"] = rs; } return (Runspace)Cache["rs"]; } protected Pipeline GetPipeline(Runspace rs, string strCommand) { if (Cache["currentPipe"] == null) { Pipeline currentPipeline = rs.CreatePipeline(strCommand); Cache["currentPipe"] = currentPipeline; } return (Pipeline)Cache["currentPipe"]; } }
PowerShellCorpus/PoshCode/433da2cf-0b3d-481c-827e-375cf9760770.ps1
433da2cf-0b3d-481c-827e-375cf9760770.ps1
function Get-ParameterEnum { <# .Synopsis Displays enumeration values for specific parameter. .Description For provided combination of cmdlet/parameter displays all possible values. Parameter has to be enumeration type. Displays also numeric value and enumeration name. .Parameter Cmdlet Name of the cmdlet. .Parameter Parameter Name of the parameter you need to check. .Example Get-ParameterEnum -Cmdlet dir -Parameter ErrorAction 0: SilentlyContinue 1: Stop 2: Continue 3: Inquire .Example Get-ParameterEnum write-host ForegroundColor System.ConsoleColor 0: Black 1: DarkBlue 2: DarkGreen 3: DarkCyan 4: DarkRed 5: DarkMagenta 6: DarkYellow 7: Gray 8: DarkGray 9: Blue 10: Green 11: Cyan 12: Red 13: Magenta 14: Yellow 15: White .Link http://msdn.microsoft.com/en-us/library/system.enum.aspx #> param ( [Parameter(Mandatory=$true,Position=0)] [string]$Cmdlet, [Parameter(Mandatory=$true,Position=1)] [string]$Parameter ) $parameterClass = "((Get-Command $cmdlet).Parameters.$parameter.ParameterType).ToString()" Invoke-Expression $parameterClass Invoke-Expression "[Enum]::GetValues($parameterClass)" | % {"$($_.value__): $_"} }
PowerShellCorpus/PoshCode/4ddb6e30-dac0-481f-b6b5-547139c8a98a.ps1
4ddb6e30-dac0-481f-b6b5-547139c8a98a.ps1
Coresponding to the Scripting Guy blog "How Can I Both Save Information in a File and Display It on the Screen?" (http://blogs.technet.com/heyscriptingguy/archive/2009/07/07/hey-scripting-guy-how-can-i-both-save-information-in-a-file-and-display-it-on-the-screen.aspx): My comment is: All of the above is cool but can't work if you want your Write-Host or Write-Debug to be redirected to file as well as printing to console. Maybe the Scripting Guy can explain why (AFAIK these cmdlets are already redirecting their output). so these examples don't work!: Write-Debug "blablabla" > File.txt Write-Debug "blablabla" | Out-File -filepath C:\\File.txt Write-Debug "blablabla" | Tee -filepath C:\\File.txt so here's the function I finally use: Function WriteToDebug ([string]$DebugMessage) { $ScriptOut = ((Get-Date -format G ) + "`t$DebugMessage" ) Out-File -FilePath $LogFileDebug -Append -InputObject $ScriptOut Write-Debug "$ScriptOut" } Where i replaced every Write-Debug in the script to WriteToDebug.
PowerShellCorpus/PoshCode/SSL Oblivious Web Client_1.ps1
SSL Oblivious Web Client_1.ps1
function New-TrustAllWebClient { # Create a compilation environment $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider $Compiler=$Provider.CreateCompiler() $Params=New-Object System.CodeDom.Compiler.CompilerParameters $Params.GenerateExecutable=$False $Params.GenerateInMemory=$True $Params.IncludeDebugInformation=$False $Params.ReferencedAssemblies.Add("System.DLL") > $null $TASource=@' namespace Local.ToolkitExtensions.Net.CertificatePolicy { public class TrustAll : System.Net.ICertificatePolicy { public TrustAll() { } public bool CheckValidationResult(System.Net.ServicePoint sp, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem) { return true; } } } '@ $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource) $TAAssembly=$TAResults.CompiledAssembly ## We now create an instance of the TrustAll and attach it to the ServicePointManager $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll") [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll ## The ESX Upload requires the Preauthenticate value to be true which is not the default ## for the System.Net.WebClient class which has very simple-to-use downloadFile and uploadfile ## methods. We create an override class which simply sets that Preauthenticate value. ## After creating an instance of the Local.ToolkitExtensions.Net.WebClient class, we use it just ## like the standard WebClient class. $WCSource=@' namespace Local.ToolkitExtensions.Net { class WebClient : System.Net.WebClient { protected override System.Net.WebRequest GetWebRequest(System.Uri uri) { System.Net.WebRequest webRequest = base.GetWebRequest(uri); webRequest.PreAuthenticate = true; webRequest.Timeout = System.Threading.Timeout.Infinite; return webRequest; } } } '@ $WCResults=$Provider.CompileAssemblyFromSource($Params,$WCSource) $WCAssembly=$WCResults.CompiledAssembly ## Now return the custom WebClient. It behaves almost like a normal WebClient. $WebClient=$WCAssembly.CreateInstance("Local.ToolkitExtensions.Net.WebClient") return $WebClient } # Example of using this function to upload a file over SSL. # Notice that the object you get back from New-TrustAllWebClient is almost identical # to what you would get from new-object system.net.webclient. # $wc = New-TrustAllWebClient # $credential = get-credential # $wc.set_Credentials($credential.GetNetworkCredential()) # $URL = "https://192.168.25.129/folder/VM%201/VM%201.vmx?dcPath=ha-datacenter&dsName=datastore1" # $wc.UploadString($URL, "PUT", "Testing")
PowerShellCorpus/PoshCode/8eb8f683-4672-43f6-ae5a-77f76eb77c88.ps1
8eb8f683-4672-43f6-ae5a-77f76eb77c88.ps1
#You Need Quest AD Powershell Plugin #You Need VMWare VI Toolkit $Null = Connect-VIServer Your-VM-Server-Here; $Servers = New-Object System.Collections.ArrayList $Null = Get-QADComputer -SearchRoot 'your.domain.com/Path/To/Server/OU' | Select-Object -property Name | Format-Table -HideTableHeaders| Out-String -Stream | ForEach-Object{$Servers.Add($_.ToString().ToUpper())} $Null = Get-VM | Select-Object -property Name | Format-Table -HideTableHeaders | Out-String -Stream | ForEach-Object{$Servers.Remove($_.ToString().ToUpper())} foreach ($Server in $Servers | Sort-Object ) { ServiceTag = (Get-WmiObject Win32_BIOS -comp ($Server.ToString().Split(' '))[0]).SerialNumber; $Result = New-Object -TypeName psobject; $Result | Add-Member -MemberType NoteProperty -Name "Server Name" ($Server.ToString().Split(' '))[0]; $Result | Add-Member -MemberType NoteProperty -Name "Service Tag" $ServiceTag; Write-Output $Result; }
PowerShellCorpus/PoshCode/LNK file testing.ps1
LNK file testing.ps1
param( $Path = (Split-Path $PSHOME -Qualifier) ) if($lnks -eq $null) { $lnks = ls -Recurse $Path | ?{$_.extension.tolower() -eq ".lnk"} } $wsh = New-Object -ComObject WScript.Shell; foreach($lnk in $lnks) { $lnko = $wsh.CreateShortcut($lnk.fullname); $rtn = New-Object psobject -Property @{ "FilePath" = $lnk.FullName; "TargetPath" = $lnko.TargetPath; }; Add-Member -InputObject $rtn -MemberType NoteProperty -Name TargetExists -Value ($lnko.TargetPath -ne "" -and (Test-Path $lnko.TargetPath)) Add-Member -InputObject $rtn -MemberType ScriptProperty -Name IsUNC -Value {return $this.TargetPath.StartsWith("\\\\"); } $rtn; }
PowerShellCorpus/PoshCode/Add-SharePointLibraryFil.ps1
Add-SharePointLibraryFil.ps1
Add-SharePointLibraryFile { param ( [System.IO.FileInfo] $File, [System.Uri] $DocumentLibraryUrl = $(throw "Parameter -DocumentLibraryUrl [System.Uri] is required.") ) Begin { } Process { if($_) { $File = [System.IO.FileInfo] $_ } if (!$File.Exists) { Write-Error ($File.ToString() + " does not exist.") return $null } trap { Write-Error $_.Exception.Message break } [string]$webPath = $DocumentLibraryUrl if (-not $webPath.EndsWith("/")) { $webPath += "/"; } $webPath += $File.Name #Create a PUT Web request to upload the file. $request = [System.Net.WebRequest]::Create($webPath) #Set credentials of the current security context $request.Credentials = [System.Net.CredentialCache]::DefaultCredentials $request.Method = "PUT"; # Create buffer to transfer file $fileBuffer = New-Object byte[] 1024 # Write the contents of the local file to the request stream. $stream = $request.GetRequestStream() $fsWorkbook = $file.OpenRead() #Get the start point $startBuffer = $fsWorkbook.Read($fileBuffer, 0, $fileBuffer.Length); for ($i = $startBuffer; $i -gt 0; $i = $fsWorkbook.Read($fileBuffer, 0, $fileBuffer.Length)) { $stream.Write($fileBuffer, 0, $i); } $stream.Close() # Perform the PUT request $response = $request.GetResponse(); #Close response $response.Close(); } End { } } $url = "http://sharepoint/sites/andy/files" Get-Item 'C:\\Documents and Settings\\andy\\Desktop\\doc.pdf' | Add-SharePointLibraryFile -DocumentLibraryUrl $url
PowerShellCorpus/PoshCode/Get-ServiceAccounts.ps1
Get-ServiceAccounts.ps1
#requires -pssnapin PSCX #Author: Glenn Sizemore gesize@get-admin.com #Purpose: Scan a remote system for any services running under a non standard account. # Standard accounts would be considered, NT AUTHORITY\\NetworkService, # NT AUTHORITY\\LocalService, LocalSystem, or .\\ASPNET # #Usage: PS > Get-ServiceAccounts [-Target <string>] [-Path <string>] [-verbose] [-Credential <PSCredential Object> ] # # -Target(optional) # can be either a string or an array of strings. # -Path(optional) # Path to an item containing a list of Targets # -Verbose(optional) # turns on verbose logging to the console # -Credential(optional) # should only be used with V2, uses alternate credentials when # querying target for services. # #Returns: PSCustom Object # #Example: Get-ServiceAccounts -Target "host1","host2","host3" -Path "C:\\temp\\otherhosts.txt" -verbose # # this command will combined the targets: host1, host2, and host3 with all targets located in # the file otherhost.txt, and scan all of them for unique service accounts. # param($target, [string]$Path, [switch]$verbose, [System.Management.Automation.PSCredential]$credential = ($null) ) begin { # Create an empty object to hold all service accounts found. $SvcAccounts = @() #Save the current $ErrorActionPreference so we can restore it. $ErrActionSave = $ErrorActionPreference $Verbosesave = $VerbosePreference $warningSave = $WarningPreference #If a PSCredential is supplied then wmi query will be ran under that account. if ($credential) { Write-Host "there is a known bug using -credential in V1..." $gwmiquery = {Get-WmiObject -Class Win32_Service -ComputerName $computer -Credential $credential ` -property name, startname, caption, StartMode ` -filter 'NOT Startname LIKE "%NT AUTHORITY%" AND NOT Startname LIKE "LocalSystem" AND NOT Startname LIKE "ASPNET"'} } else { $gwmiquery = {Get-WmiObject -Class Win32_Service -ComputerName $computer -property name, startname, caption, StartMode ` -filter 'NOT Startname LIKE "%NT AUTHORITY%" AND NOT Startname LIKE "LocalSystem" AND NOT Startname LIKE "ASPNET"'} } if ($Verbose) {$VerbosePreference = "Continue"; $WarningPreference = "Continue"} #Workhorse... function ProcessTarget ($computer) { $obj = @() #Set ErrorAction to silent... we'll handle the error's ourselves. $ErrorActionPreference = "SilentlyContinue" Write-Verbose "querying $computer ..." #call the Query from above. $services = &$gwmiquery #set erroraction back there sould be no error's from here on out. $ErrorActionPreference = $ErrActionSave Write-Verbose " $($services.count) services located on $computer using " foreach ($service in $Services) { # If there was an error while attempting the gwmi call, there will be only one error. # We check that error to help annotate why we were unsuccessful. switch -regex ($Error[0].Exception) { "The RPC server is unavailable" { Write-warning "RPC Unavailable on $computer" $obj += "" | Select @{e={$computer};n='Target'},@{e={"RPC_Unavalable"};n='SvcName'} continue } #vista "Access denied" { Write-warning "Access Denied on $computer" $obj += "" | Select @{e={$computer};n='Target'},@{e={"Access_Denied"};n='SvcName'} continue } #XP/Server 2k3 "Access is denied" { Write-warning "Access Denied on $computer" $obj += "" | Select @{e={$computer};n='Target'},@{e={"Access_Denied"};n='SvcName'} continue } $null { $obj += "" | Select @{e={$computer};n='Target'}, @{e={$service.name };n='SvcName'}, @{e={$service.startname };n='SvcAcccount'}, @{e={$service.caption };n='SvcDes'}, @{e={$service.StartMode };n='StartMode'} } } $Error.clear() } return $obj } } process { $Targets = @() if ($Path){$Targets = Get-Content $Path} if ($Target){$Targets += $target} foreach ($computer in $Targets) { ping-host -HostName $computer -Count 1 -Quiet -Timeout 1| Where-Object { $_.loss -ne 100} | ` ForEach-Object {$SvcAccounts += ProcessTarget $_.host} } } End { $ErrorActionPreference = $ErrActionSave $VerbosePreference = $Verbosesave $WarningPreference = $warningSave Write-Output $SvcAccounts }
PowerShellCorpus/PoshCode/PowerCLI error report_1.ps1
PowerCLI error report_1.ps1
$getVmScript = { Connect-VIServer yourVCenterServer Get-VM } $ getVmScript | Get-ErrorReport -ProblemScriptTimeoutSeconds 60 -ProblemDescription "Get-VM hangs when trying to retrieve all the VMs form the server. The server’s inventory can be successfully browsed via the vClient." -Destination 'D:\\bug report'
PowerShellCorpus/PoshCode/CreateVDS.ps1
CreateVDS.ps1
function CreateVDS( $dvsName, $datacenter, $vmHost, $physicalNic, $portGroupType = "earlyBinding", ` [array]$portGroupNameList = @(),[array]$uplinkList = @() ) { # ------- Create vDS ------- # $dvsCreateSpec = New-Object VMware.Vim.DVSCreateSpec $dvsCreateSpec.configSpec = New-Object VMware.Vim.DVSConfigSpec $dvsCreateSpec.configSpec.name = $dvsName $dvsCreateSpec.configSpec.uplinkPortPolicy = New-Object VMware.Vim.DVSNameArrayUplinkPortPolicy if ($uplinkList.Count -eq 0) { $dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName = New-Object System.String[] (2) $dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[0] = "dvUplink1" $dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[1] = "dvUplink2" } else { $dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName = New-Object System.String[] ($uplinkList.Count) for ($i = 0; $i -lt $uplinkList.Count; $i++){ $dvsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[$i] = $uplinkList[$i] } } $hostIdValue = ($vmHost.Id.Split('-', 2))[1] $dvsCreateSpec.configSpec.host = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec[] (1) $dvsCreateSpec.configSpec.host[0] = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec $dvsCreateSpec.configSpec.host[0].operation = "add" $dvsCreateSpec.configSpec.host[0].host = New-Object VMware.Vim.ManagedObjectReference $dvsCreateSpec.configSpec.host[0].host.type = "HostSystem" $dvsCreateSpec.configSpec.host[0].host.value = $hostIdValue $dvsCreateSpec.configSpec.host[0].backing = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking $dvsCreateSpec.configSpec.host[0].backing = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking $dvsCreateSpec.configSpec.host[0].backing.pnicSpec = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec[] (1) $dvsCreateSpec.configSpec.host[0].backing.pnicSpec[0] = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec $dvsCreateSpec.configSpec.host[0].backing.pnicSpec[0].pnicDevice = $physicalNic.DeviceName $networkFolderView = Get-View -Id (($datacenter | Get-View).NetworkFolder) $dvsMoRef = $networkFolderView.CreateDVS($dvsCreateSpec) # ------- Add vDPortGroup ------- # if ($portGroupNameList.Count -eq 0){ $portGroupNameList += "dvPortGroup" } $dvProtGroupSpec = New-Object VMware.Vim.DVPortgroupConfigSpec[] ($portGroupNameList.Length) for ($i = 0; $i -lt $portGroupNameList.Length; $i++){ $dvProtGroupSpec[$i] = New-Object VMware.Vim.DVPortgroupConfigSpec $dvProtGroupSpec[$i].name = $portGroupNameList[$i] $dvProtGroupSpec[$i].numPorts = 128 $dvProtGroupSpec[$i].defaultPortConfig = New-Object VMware.Vim.VMwareDVSPortSetting $dvProtGroupSpec[$i].defaultPortConfig.vlan = New-Object VMware.Vim.VmwareDistributedVirtualSwitchVlanIdSpec $dvProtGroupSpec[$i].defaultPortConfig.vlan.inherited = $false $dvProtGroupSpec[$i].defaultPortConfig.vlan.vlanId = 0 $dvProtGroupSpec[$i].type = $portGroupType } $dvsView = Get-View -Id $dvsMoRef.ToString() $dvsView.AddDVPortgroup($dvProtGroupSpec) return $dvsMoRef }
PowerShellCorpus/PoshCode/ConvertTo-Module.ps1
ConvertTo-Module.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.Name -as [type])::$func.invoke($args) }.GetNewClosure() # capture the value of $func } export-modulemember -function $exports } -name $type.Name -ArgumentList $type }
PowerShellCorpus/PoshCode/UIAutomation 1.3.ps1
UIAutomation 1.3.ps1
# # # Select-Window Notepad | Remove-Window -passthru # # ## And later ... # # Select-Window Notepad | Select-ChildWindow | Send-Keys "%N" # # ## OR ## # # Select-Window Notepad | Select-ChildWindow | # # Select-Control -title "Do&n't Save" -recurse | Send-Click # # # # # # PS notepad | Select-Window | Select-ChildWindow | %{ New-Object Huddled.Wasp.Window $_ } # # # # cp C:\\Users\\Joel\\Projects\\PowerShell\\Wasp\\trunk\\WASP\\bin\\Debug\\Wasp.dll .\\Modules\\WASP\\ # # Import-Module WASP # function formatter { END { # $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto # }} # Add-Type -AssemblyName UIAutomationClient # Add-Type -AssemblyName UIAutomationTypes [Reflection.Assembly]::Load("UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") [Reflection.Assembly]::Load("UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") $SWA = "System.Windows.Automation" Import-Module Accelerators Add-Accelerator AutoElement "$SWA.AutomationElement" -EA SilentlyContinue $UIAFunctions = @{} # 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 $Patterns = [Reflection.Assembly]::GetAssembly([System.Windows.Automation.BasePattern]).GetTypes() | Where {$_.BaseType -like "System.Windows.Automation.BasePattern"} ## 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){ $FullName = $pattern.FullName $pattern.GetMethods() | Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } | ForEach { $Name = $($_.Name -replace 'Pattern`$') $Func1 = "Function:Invoke-$($Name)" $Func = "Function:Global:Invoke-$($Name)" if (test-path $Func1) { remove-item $Func1 } New-Item $Func -value " Param( $( [string]::Join( ", ", @($_.GetParameters() | % { "[$($_.ParameterType.FullName)]`$$($_.Name)" })) ) ) Process { trap { Write-Warning `"`$(`$_)`"; continue } `$pattern = `$_.GetCurrentPattern([$FullName]::Pattern) if(`$pattern) { `$Pattern.GetType().InvokeMember('$($_.name)','Public,Instance,InvokeMethod', `$null, `$pattern, `$PSBoundParameters.Values) } }" } $pattern.GetProperties() | Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} | ForEach { $Name = $($_.Name -replace 'Pattern`$') $Func1 = "Function:Get-$($Name)" $Func = "Function:Global:Get-$($Name)" if (test-path $Func1) { remove-item $Func1 } New-Item $Func -value "Process { trap { Write-Warning `"$FullName `$_`"; continue } `$pattern = `$_.GetCurrentPattern([$FullName]::Pattern) if(`$pattern) { `$pattern.'$($_.name)' } }" } } 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 Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue $FalseCondition = [Condition]::FalseCondition $TrueCondition = [Condition]::TrueCondition Add-Type -AssemblyName System.Windows.Forms Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue function New-UIAElement { [CmdletBinding()] PARAM( [Parameter(ValueFromPipeline=$true)] [AutoElement]$Element ) PROCESS { $Element | Add-Member -Name Text -Type ScriptProperty -PassThru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::NameProperty) } | Add-Member -Name ClassName -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::ClassNameProperty) } | Add-Member -Name FrameworkId -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::FrameworkIdProperty) } | Add-Member -Name ProcessId -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::ProcessIdProperty) } | Add-Member -Name ControlType -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::LocalizedControlTypeProperty) } # $e = # ForEach($method in $UIAFunctions.GetEnumerator()) { # $e = & $method.Value $e # } # $e } } function Select-Window { [CmdletBinding()] PARAM( [Parameter()] [Alias("Name")] [string]$Text="*" , [Parameter()] [string]$ClassName="*" , [Parameter()] [string]$ControlType="*" , [Parameter()] [switch]$Recurse , [Parameter(ValueFromPipeline=$true)] [AutoElement]$Parent = [AutoElement]::RootElement ) PROCESS { if($Recurse) { $Parent.FindAll( "Descendants", $TrueCondition ) | New-UIAElement | Where-Object { ($_.ClassName -like $ClassName) -AND ($_.Text -like $Text) -AND ($_.ControlType -like $ControlType) } } else { $Parent.FindAll( "Children", $TrueCondition ) | New-UIAElement | Where-Object { ($_.ClassName -like $ClassName) -AND ($_.Text -like $Text) -AND ($_.ControlType -like $ControlType) } } } } function formatter { END { $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto }} function Invoke-Element { [CmdletBinding()] PARAM( [Parameter(ValueFromPipeline=$true)] [AutoElement]$Target ) PROCESS { $Target.GetCurrentPattern([InvokePattern]::Pattern).Invoke() } } function Set-ElementText { [CmdletBinding()] PARAM( [Parameter()] [string]$Text , [Parameter(ValueFromPipeline=$true)] [AutoElement]$Target ) PROCESS { $Target.SetFocus(); $textPattern = $valuePattern = $null try { $textPattern = $Target.GetCurrentPattern([TextPattern]::Pattern) Write-Host "textPattern:`n$($textPattern | gm)" } catch { } try { $valuePattern = $Target.GetCurrentPattern([ValuePattern]::Pattern) Write-Host "valuePattern:`n$($valuePattern | gm)" } catch { } $Target.SetFocus(); if($valuePattern) { $valuePattern.SetValue( $Text ) } if($textPattern) { [SendKeys]::SendWait("^{HOME}"); [SendKeys]::SendWait("^+{END}"); [SendKeys]::SendWait("{DEL}"); [SendKeys]::SendWait( $Text ) } } }
PowerShellCorpus/PoshCode/PS file locking.ps1
PS file locking.ps1
################################################# #Scriptname: checklock.ps1 #Author: Michael Rüefli (www.miru.ch) #Date: 21.11.2009 #Description: The code uses a file locking mechanism to ensure that the # script beeing started is running exclusively. Mostly used where # a powershell script is started parallel within a few seconds # #Usage: Paste your code in the MAIN section and set the $lockfile paramater to match your needs ############################################ $lockfile = “d:\\lock.lck” $lockstatus = 0 While ($lockstatus -ne 1) { If (Test-Path $lockfile) { echo “Lock file found!” $pidlist = Get-content $lockfile If (!$pidlist) { $PID | Out-File $lockfile $lockstatus = 1 } $currentproclist = Get-Process | ? { $_.id -match $pidlist } If ($currentproclist) { echo “lockfile in use by other process!” $rndwait = New-Object system.Random $rndwait= $rndwait.next(500,1000) echo “Sleeping for $rndwait Milliseconds” Start-Sleep -Milliseconds $rndwait } Else { Remove-Item $lockfile -Force $PID | Out-File $lockfile $lockstatus = 1 } } Else { $PID | Out-File $lockfile $lockstatus = 1 } } #———————————————————————————————– ## Main Script Part ## Here you can paste your code, in fact what the script has to do echo “Hi, it seems that no other script is doing the same as me now.. so I can do my job exclusively” ## End of Main Part #———————————————————————————————– #remove the lockfile Remove-Item $lockfile -Force
PowerShellCorpus/PoshCode/New-RDCManFile.ps1
New-RDCManFile.ps1
########################################################################### # # NAME: New-RDCManFile.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jer@powershell.no # # COMMENT: Script to create a XML-file for use with Microsoft Remote Desktop Connection Manager # For more details, see the following blog-post: http://blog.powershell.no/2010/06/02/dynamic-remote-desktop-connection-manager-connection-list # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 02.06.2010 - Initial release # ########################################################################### #Importing Microsoft`s PowerShell-module for administering ActiveDirectory Import-Module ActiveDirectory #Initial variables $domain = $env:userdomain $OutputFile = "$home\\$domain.rdg" #Create a template XML $template = @' <?xml version="1.0" encoding="utf-8"?> <RDCMan schemaVersion="1"> <version>2.2</version> <file> <properties> <name></name> <expanded>True</expanded> <comment /> <logonCredentials inherit="FromParent" /> <connectionSettings inherit="FromParent" /> <gatewaySettings inherit="FromParent" /> <remoteDesktop inherit="FromParent" /> <localResources inherit="FromParent" /> <securitySettings inherit="FromParent" /> <displaySettings inherit="FromParent" /> </properties> <group> <properties> <name></name> <expanded>True</expanded> <comment /> <logonCredentials inherit="None"> <userName></userName> <domain></domain> <password storeAsClearText="False"></password> </logonCredentials> <connectionSettings inherit="FromParent" /> <gatewaySettings inherit="None"> <userName></userName> <domain></domain> <password storeAsClearText="False" /> <enabled>False</enabled> <hostName /> <logonMethod>4</logonMethod> <localBypass>False</localBypass> <credSharing>False</credSharing> </gatewaySettings> <remoteDesktop inherit="FromParent" /> <localResources inherit="FromParent" /> <securitySettings inherit="FromParent" /> <displaySettings inherit="FromParent" /> </properties> <server> <name></name> <displayName></displayName> <comment /> <logonCredentials inherit="FromParent" /> <connectionSettings inherit="FromParent" /> <gatewaySettings inherit="FromParent" /> <remoteDesktop inherit="FromParent" /> <localResources inherit="FromParent" /> <securitySettings inherit="FromParent" /> <displaySettings inherit="FromParent" /> </server> </group> </file> </RDCMan> '@ #Output template to xml-file $template | Out-File $home\\RDCMan-template.xml -encoding UTF8 #Load template into XML object $xml = New-Object xml $xml.Load("$home\\RDCMan-template.xml") #Set file properties $file = (@($xml.RDCMan.file.properties)[0]).Clone() $file.name = $domain $xml.RDCMan.file.properties | Where-Object { $_.Name -eq "" } | ForEach-Object { [void]$xml.RDCMan.file.ReplaceChild($file,$_) } #Set group properties $group = (@($xml.RDCMan.file.group.properties)[0]).Clone() $group.name = $env:userdomain $group.logonCredentials.Username = $env:username $group.logonCredentials.Domain = $domain $xml.RDCMan.file.group.properties | Where-Object { $_.Name -eq "" } | ForEach-Object { [void]$xml.RDCMan.file.group.ReplaceChild($group,$_) } #Use template to add servers from Active Directory to xml $server = (@($xml.RDCMan.file.group.server)[0]).Clone() Get-ADComputer -LDAPFilter "(operatingsystem=*server*)" | select name,dnshostname | ForEach-Object { $server = $server.clone() $server.DisplayName = $_.Name $server.Name = $_.DNSHostName $xml.RDCMan.file.group.AppendChild($server) > $null} #Remove template server $xml.RDCMan.file.group.server | Where-Object { $_.Name -eq "" } | ForEach-Object { [void]$xml.RDCMan.file.group.RemoveChild($_) } #Save xml to file $xml.Save($OutputFile) #Remove template xml-file Remove-Item $home\\RDCMan-template.xml -Force
PowerShellCorpus/PoshCode/Deploy VM with Static IP_2.ps1
Deploy VM with Static IP_2.ps1
# 1. Create a simple customizations spec: $custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows ` -OrgName “My Organization” -FullName “MyVM” -Domain “MyDomain” ` –DomainAdminUsername “user” –DomainAdminPassword “password” # 2. Modify the default network customization settings: $custSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping ` -IpMode UseStaticIP -IpAddress 192.168.121.228 -SubnetMask 255.255.248.0 ` -Dns 192.168.108.1 -DefaultGateway 192.168.108.1 # 3. Deploy a VM from a template using the newly created customization: New-VM -Name “MyNewVM” -Template $template -VMHost $vmHost ` -OSCustomizationSpec $custSpec
PowerShellCorpus/PoshCode/Get-PasswordExpiredUser.ps1
Get-PasswordExpiredUser.ps1
$filter = "(&(objectCategory=user)(userAccountControl:1.2.840.113556.1.4.803:=65536))" $ds = new-object directoryservices.directorysearcher([adsi]"",$filter) $users = $ds.findall() $users | format-table @{l="User";e={$_.properties.item('cn')}}, @{l="sAMAccountName";e={$_.properties.item('sAMAccountName')}}, @{l="Path";e={$_.path}}
PowerShellCorpus/PoshCode/Test-BufferBox 2.0.ps1
Test-BufferBox 2.0.ps1
## Test-BufferBox 2.0 #################################################################################################### ## This script is just a demonstration of some of the things you can do with the buffer ## in the default PowerShell host... it serves as a reminder of how much work remains on ## PoshConsole, and as an inspirations to anyone who is thinking about trying to create ## "interactive" PowerShell applications. ## ## Imagine it's a chat window: you can type, but the whole time, the ongoing conversation in the ## chat room you have joined is going on in the background. ## ## NOTE: because this is a "chat" demo, we treat your input as text, and to execute script in-line ## you have to enclose it inside $() braces. ## #################################################################################################### PARAM( $title = "PowerShell Interactive Buffer Demo" ) $global:fore = $Host.UI.RawUI.ForegroundColor $global:back = $Host.UI.RawUI.BackgroundColor Function New-Box ($Height, $Width, $Title="") { $box = &{ "ŻŻ$Title$('Ż'*($Width-($Title.Length+2)))"; 1..($Height - 2) | % {(' ' * $Width)}; ('_' * $Width); 1..2 | % {(' ' * $Width)}; } $boxBuffer = $Host.UI.RawUI.NewBufferCellArray($box,'Green','Black') ,$boxBuffer } Function Scroll-Buffer ($origin,$Width,$Height,$Scroll=-1){ $re = new-object $RECT $origin.x, $origin.y, ($origin.x + $width-2), ($origin.y + $height) $origin.Y += $Scroll $Host.UI.RawUI.ScrollBufferContents($re, $origin, $re, $blank) } Function Out-Buffer { PARAM ($Message, $Foreground = 'White',$Background = 'Black',[switch]$noscroll) BEGIN { if($Message) { $Message | Out-Buffer -Fore $Foreground -Back $Background -NoScript:$NoScroll } } PROCESS { if($_){$Message = $_ if ( -not $NoScroll) { Scroll-Buffer $ContentPos ($WindowSize.Width -2) ($WindowSize.Height - 4) } # "{0},{1} {2},{3} -{4}" -f $script:pos.X, $script:pos.Y, $MessagePos.X, $MessagePos.Y, $message $host.ui.rawui.SetBufferContents( $MessagePos, $Host.UI.RawUI.NewBufferCellArray( @($message.PadRight($WindowSize.Width)), $Foreground, $Background) ) }}} Function Clear-Prompt () { $Host.UI.RawUI.SetBufferContents( $PromptPos, $prompt ) $Host.UI.RawUI.CursorPosition = $CursorPos } ################################################################################################### ##### Initialize a lot of settings ################################################################################################### $RECT = "system.management.automation.host.rectangle" $blank = new-object System.Management.Automation.Host.BufferCell(' ','Gray','Black','complete') $WindowSize = $Host.UI.RawUI.WindowSize; "`n" * $WindowSize.Height $ContentPos = $Host.UI.RawUI.WindowPosition; $Host.UI.RawUI.ForegroundColor = "Yellow" $Host.UI.RawUI.BackgroundColor = "Black" $ContentPos.Y += 1 # Keep the title in the top row $ContentPos.X += 2 # 2 cell left padding on output # The Message is written into the very last line of the ContentBox $MessagePos = $ContentPos $MessagePos.Y += ($WindowSize.Height - 4) $PromptPos = $ContentPos $PromptPos.X = 0 $PromptPos.Y += $WindowSize.Height - 2 $prompt = $Host.UI.RawUI.NewBufferCellArray( @(&{"> "+(" " * ($WindowSize.Width-3))}), "Yellow", "Black") $CursorPos = $PromptPos $CursorPos.X += 2 ################################################################################################### ##### We only need this for the purposes of the demo... ##### In a real script you would, presumably, be getting stuff from somewhere else to display $noise = Get-Content ($MyInvocation.MyCommand.Path) $index = 0; $random = New-Object "Random" ################################################################################################### ##### The loop starts by clearing the screen ... $Host.UI.RawUI.SetBufferContents($Host.UI.RawUI.WindowPosition, (New-Box ($WindowSize.Height - 1) $WindowSize.Width $title)) ##### Printing a "How to Exit" message Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " This is just a demo. " -Fore Black -Back Cyan Out-Buffer " We will stream in the source code of this script ... " -Fore Black -Back Cyan Out-Buffer " And you can type at the bottom while it's running. " -Fore Black -Back Cyan Out-Buffer " Imagine this as an n-way chat application like IRC, except that " -Fore Black -Back Cyan Out-Buffer " FOR THIS PERFORMANCE ONLY: " -Fore Black -Back Cyan Out-Buffer " The part of your chatting friends is played by my source code. " -Fore DarkGray -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " Press ESC to exit, or enter 'exit' and hit Enter" -Fore Black -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan ##### Setting the prompt Clear-Prompt ##### And initializing our two variables ... $line="" $exit = $false while(!$exit){ while(!$exit -and $Host.UI.RawUI.KeyAvailable) { $char = $Host.UI.RawUI.ReadKey("IncludeKeyUp,IncludeKeyDown,NoEcho"); # we don't want the key up events, but we do want to get rid of them if($char.KeyDown) { switch([int]$char.Character) { 13 { # Enter if($line.Trim() -eq "exit") { $exit = $true; break; } ################################################################################################### ################################################################################################### ############# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ############# ############# This executes the user input! ############# ############# Don't use this on, say, content you got from a web page or chat room ############# iex "Out-Buffer `"$line`" -Fore Red"; ############# ################################################################################################### ################################################################################################### $line = ""; Clear-Prompt } 27 { # Esc $exit = $true; break; } 8 { # Backspace if($line.Length -gt 0) { $line = $line.SubString(0,$($line.Length-1)) } # $pos = $Host.UI.RawUI.CursorPosition $Host.UI.RawUI.SetBufferContents( $PromptPos, $Host.UI.RawUI.NewBufferCellArray( @(&{ "> $($line)$(' ' * ($WindowSize.Width-3-$line.Length))"}), "Yellow", "Black") ) } 0 { # Not actually a key # Out-Buffer $($Char | Out-String) } default { $line += $char.Character $Host.UI.RawUI.SetBufferContents( $PromptPos, $Host.UI.RawUI.NewBufferCellArray( @(&{ "> $($line)$(' ' * ($WindowSize.Width-3-$line.Length))"}), "Yellow", "Black") ) } } } } # Simulate doing useful things 25% of the time if($random.NextDouble() -gt 0.75) { $noise[($index)..($index++)] | Out-Buffer if($index -ge $noise.Length){$index = 0} } sleep -milli 100 } # set the colors back ... $Host.UI.RawUI.ForegroundColor = $fore $Host.UI.RawUI.BackgroundColor = $back
PowerShellCorpus/PoshCode/Multiple strings params.ps1
Multiple strings params.ps1
# For example I have this function function copySourceDestination { Param ( [string]$sourceFile, [string]$destinationPath ) # Strangely enough $sourceFile will contain both the values of $sourceFile and $destinationPath # in this case $destinationPath will be empty and $sourceFile will show up as: "C:\\bla.txt \\\\server\\share\\path" Copy-Item -Path:$sourceFile -Destination:$destinationPath -Force } # Calling the function copySourceDestination "C:\\bla.txt" "\\\\server\\share\\path"
PowerShellCorpus/PoshCode/Script-Proc.sql.ps1
Script-Proc.sql.ps1
param( [string] $ProcedureName, [string] $Path = "$($ProcedureName).sql", [string] $ConnectionString = 'Data Source=.\\sqlexpress;Initial Catalog=master;Integrated Security=SSPI;' ); try { [System.Data.SqlClient.SqlConnection] $cn = New-Object System.Data.SqlClient.SqlConnection (,$ConnectionString); $cn.Open() > $null; $cmd = $cn.CreateCommand(); $cmd.CommandType = [System.Data.CommandType]::StoredProcedure; $cmd.CommandText = 'sp_helptext'; $cmd.Parameters.AddWithValue('@objname', $ProcedureName) > $null; [System.Data.IDataReader] $rdr = $cmd.ExecuteReader(); [string] $sproc_text = ''; while ($rdr.Read()) { $sproc_text += $rdr[0]; } $sproc_text | Out-File -FilePath $Path; } finally { if ($cmd -ne $null) { $cmd.Dispose(); } if ($cn -ne $null) { $cn.Dispose(); } }
PowerShellCorpus/PoshCode/ImaginaryFriendFeed.ps1
ImaginaryFriendFeed.ps1
function New-ImaginaryFriend { ##.Note ## DEPENDS on the WatiN module in http`://poshcode.org/1108 ##.Synopsis ## Creates a new "Imaginary Friend" on friendfeed by automating your browser ##.Example ## New-ImaginaryFriend PoshCode @{Twitter="PoshCode"} http`://poshcode.org/PoshCode.png ## [CmdletBinding()] PARAM($name,[hashtable]$services,$avatar) Set-WatinUrl http`://friendfeed.com/settings/imaginary if($ie.Url -ne "http`://friendfeed.com/settings/imaginary" ) { throw "You are not authenticated to FriendFeed. Please log in and try again" } Find-Button value "Create imaginary friend" | % { $_.Click() } Find-TextField name name | % { $_.TypeText( $name ) } (Find-Form action "/a/createimaginary").Buttons | % { $_.click() } $null = $ie.url -match "http`://friendfeed.com/([^/]*)/services"; $ffid = $matches[1] # Write-Output $ffid foreach($service in $services.GetEnumerator()) { Write-Verbose "$($service.Key): $($service.Value)" Find-Link service $service.Key | % { $_.Click() } $form = Find-Form action "/a/configureservice" @($form.TextFields)[0].TypeText( $service.Value ) @($form.Buttons)[0].click(); } if($avatar) { Set-WatinUrl "http`://friendfeed.com/$ffid" $avatarFile = Get-WebFile $avatar ([uri]$avatar).segments[-1] Write-Verbose "Downloaded? $($avatarFile.FullName)" Start-Sleep -milli 500 Find-Link innertext "Change picture" | %{ $_.Click() } Find-FileUpload id pictureupload | % { $_.Set( $avatarFile.FullName ) } (Find-Form action "/a/changepicture").Buttons | % { $_.click() } Start-Sleep -milli 500 Remove-Item $avatarFile } } ## DEPENDS on the HttpRest module in http://poshcode.org/1107 Function Get-FriendFeedFriends { Param($username) $friendNames = Get-WebPageText "http`://friendfeed.com/api/user/$username/profile" //user/subscription/nickname @{format="xml";include="subscriptions"} ForEach($incoming in (Get-WebPageContent "http`://friendfeed.com/api/profiles" //profiles/profile @{ format="xml"; nickname=$($friendNames -join ",") })) { $output = Select -Input $incoming Name, NickName | Add-Member noteproperty Lists @($incoming.SelectNodes("//list/nickname").InnerText) -Passthru | Add-Member noteproperty Rooms @($incoming.SelectNodes("//room/nickname").InnerText) -Passthru ForEach($service in $incoming.service) { if(!$output."$($service.id)") { if($service.username) { Add-Member -input $output noteproperty $service.id $service.username } else { Add-Member -input $output noteproperty $service.id $service.profileUrl } } else { if($service.username) { $output."$($service.id)" = @($output."$($service.id)") + $service.username } else { $output."$($service.id)" = @($output."$($service.id)") + $service.profileUrl } } } $output } } ## This might work to copy over all your twitter friends to friend feed ... ## You'll need the modules: 1107 and 1108 ## And the dll's those depend on (WatiN and MindTouch Dream) ## And IE, logged into friendfeed ## And a little luck $ffNick = Read-Host "Your FriendFeed nick" $TwitterId = Read-Host "Your Twitter ID" $threshold = -14 ## Get all your FriendFeed friends... $friends = Get-FFFriends $ffNick ## Get any twitter friends who aren't on friendfeed ## Make sure you use FriendFeed's built in "add all your twitter friends" first $knownTweeters = $friends | select -expand twitter $page = 0 $twits = $tweeters = @() do { $twits += $tweeters $tweeters = Get-WebPageContent "http`://twitter.com/statuses/friends.xml" //users/user @{page=(++$page); screen_name=$TwitterId} | Where { $knownTweeters -notcontains $_.screen_name } } while($tweeters) ### Remove people who aren't updating $threshold = (Get-Date).AddDays($threshold) $twits = $twits | Where { $_.protected -or ([DateTime]::ParseExact($_.status.created_at, "ddd MMM dd HH:mm:ss +0000 yyyy", $Null) -gt $threshold) } ## Start adding them to friend feed New-Watin "http`://friendfeed.com/settings/imaginary" while( $ie.Url -ne "http`://friendfeed.com/settings/imaginary" ) { Set-WatinUrl "http`://friendfeed.com/settings/imaginary" Read-Host "Press Enter after you have logged into FriendFeed" } foreach($twit in $twits) { New-ImaginaryFriend $twit.name @{twitter=$twit.screen_name} $twit.profile_image_url }
PowerShellCorpus/PoshCode/Get-WebFile _2.6.ps1
Get-WebFile _2.6.ps1
## Get-WebFile (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.7 - Added Credentials parameter for passing credentials via System.Net.NetworkCredential ## 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, @@ [System.Net.NetworkCredential]$Credentials = $null ) $req = [System.Net.HttpWebRequest]::Create($url); $req.Credentials = $Credentials $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/Logging AD logins.ps1
Logging AD logins.ps1
#* FileName: loginTime.ps1 #*============================================================================= #* Created: [09/25/2009] #* Author: Alan Oakland #*============================================================================= #* Purpose: Create a log of login times. #*============================================================================= #*============================================================================= #* REVISION HISTORY #*============================================================================= #*============================================================================= #*============================================================================= #* Variable Configuration #*============================================================================= $adsobj = [ADSI]"WinNT://$domain/$env:username" $logpath = "\\\\server\\share\\path" #*============================================================================= #* FUNCTION LISTINGS #*============================================================================= #*============================================================================= #* SCRIPT BODY #*============================================================================= #Retrieve IP information $global:ipinfo = get-wmiobject -class "Win32_NetworkAdapterConfiguration" ` | Where{($_.IpEnabled -Match "True") -And ($_.DNSDomain -Match $curDomain)} if ($ipinfo) { $global:ip=$ipinfo.ipaddress[0] } else { $global:ip=[system.net.dns]::gethostAddresses($null)[0].ipaddresstostring if (!($ip)) { $global:ip="IP could not be resolved" } } $fullName = $adsobj.FullName.value.toString() $logfile = "$($logpath)\\USER-$fullname.ini" # this is the log file $recordstokeep = 200 # set this to the number of user records to keep #Create the logfile if it doesn't exist if (!(test-path -path "$logfile")) { $null = new-item $logfile -Type file } # write the log entry $logData = "$(get-date -Format M/dd/yyyy) - $(get-date -Format H:mm:ss) - Login - $ip - $env:username - $env:clientname=$env:computername" # read all the log entries into an array [Array]$entries = Get-Content $logfile #Add the data to the array $entries += $logData if (($entries.length-1) -gt $recordstokeep) { #delete anything less than required number of days $entries = $entries[0],$entries[($entries.length-$recordstokeep)..($entries.length-1)] } #Write Output $entries | Out-File $logfile #Computer Log $logfile = "$($logpath)\\COMP-$env:computername.ini" #this is the log file $recordstokeep = 200 # set this to the number of computer records to keep #Create the logfile if it doesn't exist if (!(test-path -path "$logfile")) { $null = new-item $logfile -Type file } # write the log entry $logData = "$(get-date -Format yyyy/M/dd) - $(get-date -Format H:mm:ss) - Login - $ip - $env:username =$fullName" # read all the log entries into an array [Array]$entries = Get-Content $logfile #Add the data to the array $entries += $logData if (($entries.length-1) -gt $recordstokeep) { #delete anything less than required number of days $entries = $entries[0],$entries[($entries.length-$recordstokeep)..($entries.length-1)] } #Write Output $entries | Out-File $logfile #*============================================================================= #* END OF SCRIPT #*=============================================================================
PowerShellCorpus/PoshCode/finddupe_4.ps1
finddupe_4.ps1
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } write-host "Usage: finddupe.ps1 <directory1> <directory2> ... <directoryN>" $matches = 0 # initialize number of matches for summary. if ($args.count -eq 0) { $files = (dir -recurse | ? {$_.psiscontainer -ne $true})} else {$files = (dir $args -recurse | ? {$_.psiscontainer -ne $true})} if ($files -eq $null) {write-host "No files found." -f red; exit} for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files { if ($files[$i] -eq $null) {continue} $md5 = $null $filecheck = $files[$i] $files[$i] = $null for ($c=0;$c -ne $files.count; $c++) { if ($files[$c] -eq $null) {continue} # write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline if ($filecheck.length -eq $files[$c].length) { #write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)} if ($md5 -eq (get-md5 $files[$c])) { write-host "Size and MD5 match: " -fore red -nonewline "{0} and {1}" -f $filecheck.fullname, $files[$c].fullname $matches++ $files[$c] = $null } } } } write-host "" write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found. write-host "Number of matches found: $($matches)." write-host ""
PowerShellCorpus/PoshCode/remove-ADobject.ps1
remove-ADobject.ps1
###################################################### # Script to remove unauthorized objects from AD group # (c) Josh Coen # Requires AD cmdlets ###################################################### # set path and file name in $strFile # file should contain authorized usernames or groups one on each line # set group you want to check in $strGroup $ErrorActionPreference = "SilentlyContinue" $strFile = "c:\\admins.txt" $testFile = Test-Path $strFile $aryAuth = Get-Content $strFile $strGroup = "Domain Admins" $colItems = Get-QADGroupMember $strGroup $intItem = 0 $intFile = 0 $match = 0 if ($testFile -eq $false) { "`n `n File Not Found: $strFile -- exiting script `n`n" break } while ($intItem -lt $colItems.Length) { while ($intFile -lt $aryAuth.Length) { $strType = $colItems[$intItem].type switch ($strType) { user {$exists = $colItems[$intItem].logonname -match $aryAuth[$intFile]} group {$exists = $colItems[$intItem].name -match $aryAuth[$intFile]} } if ($exists -eq $false) { $match ++ } $intFile ++ } if ($match -eq $aryAuth.length) { Remove-QADGroupMember -Identity $strGroup -Member $colItems[$intItem] } $match = 0 $intFile = 0 $intItem ++ }
PowerShellCorpus/PoshCode/Start-Presentation_2.ps1
Start-Presentation_2.ps1
if(-not(get-command New-System.Windows.Window -EA 0)){ Import-Module PowerBoots } Add-BootsTemplate $PSScriptRoot\\PresentationFrame.xaml $name = [System.Windows.Navigation.JournalEntry]::NameProperty [double]$global:zoomLevel = 1 $SlideCount = 0 function Start-Zoom { PARAM( [Parameter(Position=0)] $Zoom = 0 , [Parameter(ValueFromPipeline=$true)] $Root = $($global:Frame) , [Parameter()] $Window = $presentationTitle ) $null = Invoke-BootsWindow $Window { Param($Window,$Root) if(!$Root.RenderTransform.Children) { $Root.RenderTransform = TransformGroup { ScaleTransform -ScaleX $zoomLevel -ScaleY $zoomLevel TranslateTransform } $BootsWindow.Add_MouseDown( { if($zoomLevel -ne 1) { trap { Write-Host $( $_ | fl * | out-string ) } $global:MouseDownPoint = [System.Windows.Input.Mouse]::GetPosition($BootsWindow) $this.CaptureMouse() } } ) $BootsWindow.Add_MouseUp( { if($zoomLevel -ne 1) { trap { Write-Host $( $_ | fl * | out-string ) } $this.ReleaseMouseCapture() } } ) $BootsWindow.Add_MouseMove( { if($zoomLevel -ne 1) { trap { Write-Host $( $_ | fl * | out-string ) } if($_.LeftButton -eq "Pressed") { $newPos = [System.Windows.Input.Mouse]::GetPosition($BootsWindow) $this.Content.RenderTransform.Children[1].SetValue( [System.Windows.Media.TranslateTransform]::XProperty, $this.Content.RenderTransform.Children[1].Value.OffsetX + ($newPos.X - $MouseDownPoint.X) ) $this.Content.RenderTransform.Children[1].SetValue( [System.Windows.Media.TranslateTransform]::YProperty, $this.Content.RenderTransform.Children[1].Value.OffsetY + ($newPos.Y - $MouseDownPoint.Y) ) $global:MouseDownPoint = $newPos; } } } ) } } $Root } function Set-Zoom { PARAM( [Parameter(Position=0)] $Zoom = 0 , [Parameter()] $Root = $global:Frame , [Parameter()] $Window = $presentationTitle ) if($Zoom -gt 0) { $global:zoomLevel *= (1+($Zoom/10)) } elseif($Zoom -lt 0) { $global:zoomLevel /= (1+($Zoom/-10)) } else { $global:zoomLevel = 1.0 } $null = Invoke-BootsWindow $Window { Param($Window,$Root) $Root.RenderTransform.Children[0].SetValue( [System.Windows.Media.ScaleTransform]::ScaleXProperty, $zoomLevel ) $Root.RenderTransform.Children[0].SetValue( [System.Windows.Media.ScaleTransform]::ScaleYProperty, $zoomLevel ) ## Note that we have to account for rounding errors ;) if([Math]::Round($zoomLevel, 10) -eq 1.0 ) { $Root.NavigationUIVisibility = "Visible" $Root.RenderTransform.Children[1].SetValue( [System.Windows.Media.TranslateTransform]::XProperty, 0.0 ) $Root.RenderTransform.Children[1].SetValue( [System.Windows.Media.TranslateTransform]::YProperty, 0.0 ) } else { $Root.NavigationUIVisibility = "Hidden" } } $Root } function Show-Url { [CmdletBinding()] PARAM( [Parameter(Position=0, ValueFromPipeline=$true)] [Uri]$Content , [Parameter()] $Window = $presentationTitle ) Invoke-BootsWindow $Window { $global:Frame.Navigate( $Content ) } } New-Alias Navigate Show-Url # backwards compat function Add-Slide { #.Synopsis # Add a slide to the presentation #.Description # Add any .net object as a slide to a presentation, wrapping it in a Page to set the title. [CmdletBinding(DefaultParameterSetName="Script")] PARAM( [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)] [Alias("Name")] [String]$Title = "Slide $SlideCount" , [Parameter(Position=1, ValueFromPipeline=$true, Mandatory=$true)] $Content , [Parameter()] $Window = $presentationTitle ) PROCESS { $SlideCount++ Invoke-BootsWindow $Window { Param($Frame, $Content, $Title) $Frame.Content = Page -Content $Content -Title $Title } $global:Frame $Content $Title } } function Add-TextSlide { #.Synopsis # Add a text slide to the presentation #.Description # Add a textual slide to the presentation with a header and several points [CmdletBinding()] PARAM( [Parameter(Position=0)] $Title = "Slide $SlideCount" , [Parameter(Position=1, ValueFromPipeline=$true)] [string[]]$Content = @("Several bullet points", "Which are equally important") , [Parameter()] $Window = $presentationTitle ) BEGIN { [string[]]$global:Points = @() } PROCESS { [string[]]$global:Points += $Content } END { Add-Slide -Title $Title -Window $Window -Content { StackPanel -Margin 10 { grid { TextBlock $Title -FontSize 85 -FontFamily Impact -Foreground White -Effect { BlurEffect -Radius 15 } -TextAlign Center TextBlock $Title -FontSize 85 -FontFamily Impact -Foreground $global:TitleBrush -TextAlign Center } write-host "Points: $Points" $Points | % { TextBlock $_ -FontSize 64 -FontWeight Bold -Foreground "White" -TextWrapping Wrap -Effect { DropShadowEffect -BlurRadius 15 } } } }.GetNewClosure() } } function Add-TitleSlide { #.Synopsis # Add a text slide to the presentation #.Description # Add a textual slide to the presentation with a header and several points [CmdletBinding()] PARAM( [Parameter(Position=0)] $Title , [Parameter()] $Window = $presentationTitle ) BEGIN { [string[]]$Points = @() } PROCESS { [string[]]$Points += $Content } END { Add-Slide -Title $Title -Window $Window -Content { Grid { TextBlock $Title ` -FontSize 125 -FontFamily Impact -Foreground White ` -VerticalAlignment Center -TextAlignment Center ` -HorizontalAlignment Stretch -TextWrapping Wrap ` -Effect { BlurEffect -Radius 20 } TextBlock $Title ` -FontSize 125 -FontFamily Impact -Foreground White ` -VerticalAlignment Center -TextAlignment Center ` -HorizontalAlignment Stretch -TextWrapping Wrap ` -Effect { BlurEffect -Radius 20 } TextBlock $Title ` -FontSize 125 -FontFamily Impact -Foreground $global:TitleBrush ` -VerticalAlignment Center -TextAlignment Center ` -HorizontalAlignment Stretch -TextWrapping Wrap ` -Effect {DropShadowEffect -Color White -Radius 15} } } } } function Remove-Slide { #.Synopsis # Removes the specified slide from the deck (history) #.Description # Takes an index or name, and removes that slide, except that you CANNOT remove the last slide. PARAM( [Parameter(ParameterSetName="ByIndex", Mandatory=$true, Position=0)] [int]$index , [Parameter(ParameterSetName="ByTitle", Mandatory=$true, Position=0)] [Alias("Name")] [string]$Title , [Parameter()] $Window = $presentationTitle ) $null = Invoke-BootsWindow $Window { # Figure out where we are now, because we'll need to come back $global:currentSlide = @($global:Frame.BackStack.GetEnumerator()).Count # Activate the slide they want to delete ... [int]$removable = Set-Slide @PsBoundParameters -passthru } # Separate Invoke's are required for the window to register what's going on? $global:removable = $true $null = Invoke-BootsWindow $Window { if($global:Frame.CanGoForward) { $global:Frame.GoForward() } else { $global:removable = $false Write-Host "Sorry, you can't remove the last slide in the deck." -Fore Red } } if($global:removable) { # Separate Invoke's are required for the window to register what's going on? Invoke-BootsWindow $Window { $null = $global:Frame.RemoveBackEntry() Set-Slide $currentSlide } } } function Show-Slide { #.Synopsis # Set the active slide in a deck #.Description # Sets the active slide by index or name (title) [CmdletBinding(DefaultParameterSetName="ByIndex")] PARAM( [Parameter(ParameterSetName="ByIndex", Mandatory=$true, Position=0)] [int]$index , [Parameter(ParameterSetName="ByTitle", Mandatory=$true, Position=0)] [Alias("Name")] [string]$Title , [Parameter()] $Window = $presentationTitle , [Parameter()] [Switch]$Passthru ) switch($PSCmdlet.ParameterSetName) { "ByIndex" { $null = Invoke-BootsWindow $Window { # Figure out where we are now... [int]$global:current = @($global:Frame.BackStack.GetEnumerator()).Count # Then go where we need to for(;$current -lt $index -and $global:Frame.CanGoForward ;$global:current++) { $global:Frame.GoForward() } for(;$current -gt $index -and $global:Frame.CanGoBack ;$global:current--) { $global:Frame.GoBack() } } if($Passthru) { return $global:current } } "ByTitle" { [int]$global:result = -1 [int]$global:current = -1 $null = Invoke-BootsWindow $Window { # Figure out where we are now... $global:current = @($global:Frame.BackStack.GetEnumerator()).Count # Start with backward history ('cause it's more likely) [int]$i = 0; foreach($page in $global:Frame.BackStack) { if($page.Name -eq $Title) { $global:result = $current - $i - 1 for(;$i -gt $0 -and $global:Frame.CanGoBack;$i--) { $global:Frame.GoBack() } break; } $i++ } # Failing that, try forward history [int]$i = 0; foreach($page in $global:Frame.ForwardStack) { if($page.Name -eq $Title) { $global:result = $current + $i + 1 for(;$i -gt $0 -and $global:Frame.CanGoForward ;$i--) { $global:Frame.GoForward() } break; } $i++ } } if($Passthru) { if($global:result -ge 0) { return $global:result } else { return $global:current } } } } } New-Alias Set-Slide Show-Slide # backwards compat function Move-NextSlide { #.Synopsis # Navigates to the next slide (if there is another) PARAM( [Parameter()] $Window = $presentationTitle , [Parameter()] [Switch]$Passthru ) $DidGo = Invoke-BootsWindow $Window { Write-Output $global:Frame.CanGoForward if($global:Frame.CanGoForward) { $global:Frame.GoForward() } } if($Passthru){ $DidGo } } New-Alias Next-Slide Move-NextSlide # backwards compat function Move-PreviousSlide { #.Synopsis # Navigates to the previous slide (if there is another) PARAM( [Parameter()] $Window = $presentationTitle , [Parameter()] [Switch]$Passthru ) $DidGo = Invoke-BootsWindow $Window { Write-Output $global:Frame.CanGoForward if($global:Frame.CanGoBack) { $global:Frame.GoBack() } } if($Passthru){ $DidGo } } New-Alias Prev-Slide Move-PreviousSlide New-Alias Previous-Slide Move-PreviousSlide # backwards compat function Start-Presentation { #.Synopsis # Start a presentation window #.Description # This is the kick-off function you have to call to create the presentation window PARAM( $PresentationTitle = "PowerShell Presentation" , $BackgroundImagePath = $(Get-ItemProperty "HKCU:\\Control Panel\\Desktop" | Select -Expand Wallpaper | Get-ChildItem) ) $BackgroundImagePath = Convert-Path (Resolve-Path $BackgroundImagePath) $global:PresentationTitle = $PresentationTitle ## Finally, make the slide window Boots -Title $PresentationTitle ` -Height $([System.Windows.SystemParameters]::PrimaryScreenHeight) ` -Width $([System.Windows.SystemParameters]::PrimaryScreenWidth) ` { $global:TitleBrush = LinearGradientBrush -Start "0.5,0" -End "0.5,1" { GradientStop -Color "#FF084670" -Offset 0 GradientStop -Color "#FF084670" -Offset 0.6 GradientStop -Color "#FF000000" -Offset 0.6 } $global:Frame = Frame -Content { Page -Title "Welcome" { Grid { TextBlock $PresentationTitle ` -FontSize 125 -FontFamily Impact -Foreground White ` -VerticalAlignment Center -TextAlignment Center ` -HorizontalAlignment Stretch -TextWrapping Wrap ` -Effect { BlurEffect -Radius 30 } TextBlock $PresentationTitle ` -FontSize 125 -FontFamily Impact -Foreground White ` -VerticalAlignment Center -TextAlignment Center ` -HorizontalAlignment Stretch -TextWrapping Wrap ` -Effect { BlurEffect -Radius 30 } TextBlock $PresentationTitle ` -FontSize 125 -FontFamily Impact -Foreground $global:TitleBrush ` -VerticalAlignment Center -TextAlignment Center ` -HorizontalAlignment Stretch -TextWrapping Wrap ` } } } #Start-Zoom -Root $global:Frame $global:Frame } -Async -On_SourceInitialized { if(Test-Path $BackgroundImagePath) { $this.Background = ImageBrush -ImageSource $BackgroundImagePath } $this.WindowState = "Maximized" } -On_KeyDown { trap { Write-Host $( $_ | fl * | Out-String ) } switch -regex ($_.Key) { "Escape" { Set-Zoom 0; break; } "OemPlus|Add" { Set-Zoom +1; break; } "OemMinus|Subtract" { Set-Zoom -1; break; } "MediaNextTrack|BrowserForward|Right" { Next-Slide; break; } "MediaPreviousTrack|BrowserBack|Left" { Previous-Slide; break; } } } -On_MouseWheel { if($_.Delta -gt 0 ) { Set-Zoom +1 } else { Set-Zoom -1 } } # -WindowStyle None -AllowsTransparency $true } function Test-Presentation { Start-Presentation "PowerShell for Developers" Add-TextSlide "Overview" "What is PowerShell?", "How can it help me?", "Should I code for it?", "How do I ..." Add-TextSlide "What is PowerShell?" "A .Net Console","A new .Net Language","An admin scripting tool","An app automation engine", "All of the above" ls ~\\Pictures\\Comix | Add-Slide Set-Slide 0 ## The simple, automatic, force-my-hand slide timer. ## One slide, every 20 seconds: ## go forward and check if we can go forward again while( Move-NextSlide -Passthru ) { # note that we have to sleep outside the invoke... # otherwise the window can't update sleep 20 } } Export-ModuleMember -Function * -Alias *
PowerShellCorpus/PoshCode/Newer-LinkedClone.ps1
Newer-LinkedClone.ps1
#Requires -version 2 # TITLE: Newer-LinkedClone.ps1 # AUTHOR: Cameron Smith (original by Hal Rottenberg) # Adapted from a technique published originally by Keshav Attrey http://www.vmdev.info/?p=40 # Also see William Lam's Perl script: http://engineering.ucsb.edu/~duonglt/vmware/vGhettoLinkedClone.html # And Leo's manual version for ESX 3.5: http://blog.core-it.com.au/?p=333 param ( [parameter(Mandatory=$true)][string]$SourceName, [parameter(Mandatory=$true)][string]$CloneName, [parameter(Mandatory=$true)][string]$SnapName ) $vm = Get-VM $SourceName # Create new snapshot for clone #$cloneSnap = $vm | New-Snapshot -Name "Clone Snapshot" # Get managed object view $vmView = $vm | Get-View # Get folder managed object reference $cloneFolder = $vmView.parent # Build clone specification $cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec #$cloneSpec.Snapshot = $vmView.Snapshot.CurrentSnapshot $SnapRef = (Get-Snapshot -VM $SourceName -name "$SnapName") | Get-View $cloneSpec.Snapshot = $SnapRef.moref # Make linked disk specification $cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec $cloneSpec.Location.DiskMoveType = [Vmware.Vim.VirtualMachineRelocateDiskMoveOptions]::createNewChildDiskBacking # Create clone $vmView.CloneVM( $cloneFolder, $cloneName, $cloneSpec ) # Write newly created VM to stdout as confirmation Get-VM $cloneName
PowerShellCorpus/PoshCode/The PowerShell Talk Demo.ps1
The PowerShell Talk Demo.ps1
#The PowerShell Takl #Demo 1 - Hypervisors #ESX #Connect to vCenter Get-Credential | connect-viserver -Server "Your vCenter Address" #Create Our Network Get-VMHost "ESXServerName" | New-VirtualSwitch -Name "Test" -NumPorts 64 #And a Port Group on that network Get-VMHost "ESXServerName" | get-virtualswitch -Name "Test" | New-VirtualPortGroup -Name "TestPG" -VLanId 10 #Change the available ports Get-VMHost "ESXServerName" | Get-VirtualSwitch -Name "Test" | Set-VirtualSwitch -NumPorts 32 #Change our VLAN ID Get-VMHost "ESXServerName" | Get-VirtualSwitch -Name "Test" | Get-VirtualPortGroup -Name "TestPG" | Set-VirtualPortGroup -VLanId 12 #Destroy it Get-VMHost "ESXServerName" | Get-VirtualSwitch -Name "Test" | Get-VirtualPortGroup -Name "TestPG" | Remove-VirtualPortGroup -Confirm:$false Get-VMHost "ESXServerName" | Get-VirtualSwitch -Name "Test" | Remove-VirtualSwitch -Confirm:$false
PowerShellCorpus/PoshCode/IADsDNWithBinary Cmdlet.ps1
IADsDNWithBinary Cmdlet.ps1
@@//Adapted from code @ http://mow001.blogspot.com/2006/01/msh-snap-in-to-translate.html Thanks! using System; using System.ComponentModel; using System.Management.Automation; using System.Reflection; using System.Diagnostics; namespace space { // This class defines the properties of a snap-in [RunInstaller(true)] public class readIADsDNWithBinary : PSSnapIn { /// Creates instance of Snapin class. public readIADsDNWithBinary() : base() { } ///Snapin name is used for registration public override string Name { get { return "readIADsDNWithBinary"; } } /// Gets description of the snap-in. public override string Description { get { return "Reads a IADsDNWithBinary"; } } public override string Vendor { get { return "Andrew"; } } } /// Gets a IADsDNWithBinary [Cmdlet("Read", "IADsDNWithBinary")] public class readIADsDNWithBinaryCommand : Cmdlet { [Parameter(Position = 0, Mandatory = true)] public object DNWithBinary { get { return DNWithBin; } set { DNWithBin = value; } } private object DNWithBin; protected override void EndProcessing() { ActiveDs.IADsDNWithBinary DNB = (ActiveDs.IADsDNWithBinary)DNWithBin; ActiveDs.DNWithBinary boink = new ActiveDs.DNWithBinaryClass(); boink.BinaryValue = (byte[])DNB.BinaryValue; boink.DNString = DNB.DNString; WriteObject(boink); } } /// Sets a IADsDNWithBinary [Cmdlet("Write", "IADsDNWithBinary")] public class writeIADsDNWithBinaryCommand : Cmdlet { [Parameter(Mandatory = true)] public byte[] Bin { get { return bin; } set { bin = value; } } private byte[] bin; [Parameter(Mandatory = true)] public string DN { get { return dn; } set { dn = value; } } private string dn; protected override void EndProcessing() { ActiveDs.DNWithBinary boink2 = new ActiveDs.DNWithBinaryClass(); boink2.BinaryValue = bin; boink2.DNString = dn; WriteObject(boink2); } } }
PowerShellCorpus/PoshCode/Create-Mdb.ps1
Create-Mdb.ps1
# Copyright (c) 2011 Justin Dearing <zippy1981@gmail.com> # # 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 authoritative version of this script lives at: https://gist.github.com/1166670 #TODO: Get The PInvoke calls to actually use these ENUMS. Add-Type -TypeDefinition @" namespace PInvoke { public enum ODBC_Constants { ODBC_ADD_DSN = 1, ODBC_CONFIG_DSN, ODBC_REMOVE_DSN, ODBC_ADD_SYS_DSN, ODBC_CONFIG_SYS_DSN, ODBC_REMOVE_SYS_DSN, ODBC_REMOVE_DEFAULT_DSN, }; public enum SQL_RETURN_CODE { SQL_ERROR = -1, SQL_INVALID_HANDLE = -2, SQL_SUCCESS = 0, SQL_SUCCESS_WITH_INFO = 1, SQL_STILL_EXECUTING = 2, SQL_NEED_DATA = 99, SQL_NO_DATA = 100 } } "@; $signature = @' [DllImport("ODBCCP32.DLL",CharSet=CharSet.Unicode, SetLastError=true)] public static extern int SQLConfigDataSource (int hwndParent, int fRequest, string lpszDriver, string lpszAttributes); [DllImport("odbccp32", CharSet=CharSet.Auto)] public static extern int SQLInstallerError(int iError, ref int pfErrorCode, StringBuilder lpszErrorMsg, int cbErrorMsgMax, ref int pcbErrorMsg); '@; Add-Type -MemberDefinition $signature -Name Win32Utils -Namespace PInvoke -Using PInvoke,System.Text; Function Create-MDB ([string] $fileName, [switch] $DeleteIfExists = $false) { # We need to pass the full path of the file to SQLConfigDataSource(). Relative paths will fail. $fileName = [System.IO.Path]::GetFullPath($fileName); if ($DeleteIfExists -and (Test-Path $fileName)) { Remove-Item $fileName; } [string] $attrs = [string]::Format("CREATE_DB=`"{0}`" General`0", $fileName); # For 32 bit processes we use the older ODBCJT32.dll driver [string] $driver = 'Microsoft Access Driver (*.mdb)'; # There is no 64 bit version of this driver so we use ACEODBC.dll # This requires the Microsoft Access Database Engine 2010 Redistributable # http://www.microsoft.com/download/en/details.aspx?id=13255 if ([IntPtr]::Size -eq 8) { $driver = 'Microsoft Access Driver (*.mdb, *.accdb)'; } # TODO: Interogate the registry (HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBCINST.INI) to search for which driver to use. # TODO: If no driver found use the 64 bit ones [int] $retCode = [PInvoke.Win32Utils]::SQLConfigDataSource( 0, [PInvoke.ODBC_Constants]::ODBC_ADD_DSN, $driver, $attrs); if ($retCode -eq 0) { [int] $errorCode = 0 ; [int] $resizeErrorMesg = 0 ; $sbError = New-Object System.Text.StringBuilder(512); [PInvoke.Win32Utils]::SQLInstallerError(1, [ref] $errorCode, $sbError, $sbError.MaxCapacity, [ref] $resizeErrorMesg); if ($sbError.ToString() -eq 'Component not found in the registry') { $sbError = New-Object System.Text.StringBuilder(512); if ([intptr]::Size -eq 8) { $sbError.Append("Their appears to be no 64 bit MS Access Driver installed. Please install a 64 bit access driver or run this script from a 32 bit powershell instance"); } if ([intptr]::Size -eq 4) { $sbError.Append("Their appears to be no 32 bit MS Access Driver installed. Please install a 32 bit access driver or run this script from a 64 bit powershell instance"); } } throw New-Object ApplicationException([string]::Format("Cannot create file: {0}. Error: {1}", $fileName, $sbError)); } } Create-Mdb ".\\foo.mdb" -DeleteIfExists
PowerShellCorpus/PoshCode/get attach. from Lotus.ps1
get attach. from Lotus.ps1
Param ( [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='Lotus Domino Server')] $ServerName, [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='Lotus Mail Database')] $Database, [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='View to Select')] $View, [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='Folder to save Attachments to.')] $Folder ) Function Get-Attachments{ [CmdletBinding()] Param ( [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='Lotus Domino Server')] $ServerName, [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='Lotus Mail Database')] $Database, [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='View to Select')] $View, [Parameter(ValueFromPipelineByPropertyName=$True, HelpMessage='Folder to save Attachments to.')] $Folder ) Begin { $NotesSession = New-Object -ComObject Lotus.NotesSession $NotesSession.Initialize() } Process { $NotesDatabase = $NotesSession.GetDatabase( $ServerName, $Database, 1 ) $AllViews = $NotesDatabase.Views | Select-Object -ExpandProperty Name $dbview = $AllViews | Select-String -Pattern $View Foreach ($nview in $dbview) { $view = $NotesDatabase.GetView($nview) $viewnav = $view.CreateViewNav() $docs = $viewnav.GetFirstDocument() while ($docs -ne $null){ $document = $docs.Document $docdate = ($document.Created).ToShortDateString() $date = (Get-Date).ToShortDateString() if ($docdate -eq $date){ if ($document.HasEmbedded){ foreach ($itm in $document.Items){ if ($itm.type -eq 1084){ $attach = $document.GetItemValue($itm.Name) #$attach = $document.GetItemValue('$File') $attachment = $document.GetAttachment($attach) $atname = $attachment.Source if (Get-Item $Folder\\$atname){ $extra = (Get-Date -UFormat "%H.%M.%S").toString() $attachment.ExtractFile("$Folder\\$extra_$atname") } $attachment.ExtractFile("$Folder\\$atname") } } } } $docs = $viewnav.GetNextDocument($docs) } } } End {} } Get-Attachments -ServerName $ServerName -Database $Database -View $View -Folder $Folder
PowerShellCorpus/PoshCode/New-XVM.ps1
New-XVM.ps1
#Examples <# New-XVM -Name "WS2012-TestServer01" -SwitchName "Switch(192.168.2.0/24)" -VhdType NoVHD New-XVM -Name "WS2012-TestServer02" -SwitchName "Switch(192.168.2.0/24)" -VhdType ExistingVHD -VhdPath 'D:\\vhds\\WS2012-TestServer02.vhdx' New-XVM -Name "WS2012-TestServer03" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD New-XVM -Name "WS2012-TestServer04" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB New-XVM -Name "WS2012-TestServer05" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Dynamic New-XVM -Name "WS2012-TestServer06" -SwitchName "Switch(192.168.2.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx' New-XVM -Name "WS2012-TestServer07" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB;"BootDevice"="LegacyNetworkAdapter"} #> 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 = "_AllParameterSets" $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 break } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $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 = "_AllParameterSets" $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 break } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $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" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $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 -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { Try { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } 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" } Invoke-Expression -Command $command } End {} }
PowerShellCorpus/PoshCode/Get-FreeDiskSpace.ps1
Get-FreeDiskSpace.ps1
<# .SYNOPSIS Return free space on disk .DESCRIPTION This script works in conjunction with an Event Trigger on the System event on our file servers. This script queries the System log for EventID 2013, and returns the drive letter from the most recent event. This should be the same event that triggered this script to run in the first place. It outputs an XML file to the StorageReports directory which exists on both nodes of the file server cluster. .PARAMETER FileName The fully qualified path and filename for the report. .EXAMPLE Get-FreeDiskSpace.ps1 Description ----------- This is the only syntax for this script. .NOTES ScriptName: Get-FreeDiskSpace.ps1 Created By: Jeff Patton Date Coded: July 12, 2011 ScriptName is used to register events for this script LogName is used to determine which classic log to write to .LINK http://scripts.patton-tech.com/wiki/PowerShell/Production/Get-FreeDiskSpace #> Param ( $FileName = "DiskSpace-$((get-date -format "yyyMMdd-hhmmss")).xml" ) Begin { $ScriptName = $MyInvocation.MyCommand.ToString() $LogName = "Application" $ScriptPath = $MyInvocation.MyCommand.Path $Username = $env:USERDOMAIN + "\\" + $env:USERNAME New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message # Dotsource in the functions you need. } Process { $LowDisk = (((Get-WinEvent -LogName System |Where-Object {$_.id -eq 2013})[0].Message).TrimStart("The ")).TrimEnd(" disk is at or near capacity. You may need to delete some files.") $DiskSpace = [math]::round(((Get-WmiObject -Class win32_LogicalDisk |Where-Object{$_.DeviceId -eq $LowDisk}).FreeSpace /1024 /1024 /1024),3) $Report = New-Object -TypeName PSObject -Property @{ Drive = $LowDisk FreeSpace = $DiskSpace } } End { $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message Export-Clixml -Path "C:\\StorageReports\\$($FileName)" -InputObject $Report }
PowerShellCorpus/PoshCode/POC csharp expressions.ps1
POC csharp expressions.ps1
function run-csharpexpression([string] $expression ) { $local:name = [system.guid]::NewGuid().tostring().replace('-','_').insert(0,"csharpexpr") $local:template = @" using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace ShellTools.DynamicCsharpExpression { public class [[CLASSNAME]] { public static object RunExpression() { return [[EXPRESSION]]; } } } "@ $local:source = $local:template.replace("[[CLASSNAME]]",$local:name).replace("[[EXPRESSION]]",$expression) add-Type $local:source -Language CsharpVersion3 | out-Null invoke-Expression $('[ShellTools.DynamicCsharpExpression.' + $local:name + ']::RunExpression()' ) } set-alias c run-csharpexpression c DateTime.Now c "new{a=1,b=2,c=3}" c 'from x in Directory.GetFiles(@"c:\\downloads") where x.Contains("win") select x'
PowerShellCorpus/PoshCode/powertab patch_1.ps1
powertab patch_1.ps1
# Stick this anywhere filter convertTypeToTabCompletionName() { $typeToTabCompletion=@{ [Microsoft.Powershell.Commands.X509StoreLocation]={$_.Location}; [System.Security.Cryptography.X509Certificates.X509Store]={$_.Name}; [Microsoft.Win32.RegistryKey]={ $_.Name.Split("\\")[-1] }; } $convertToTabCompletionFunction =$typeToTabCompletion[$_.GetType()] if (-not $convertToTabCompletionFunction ) { $convertToTabCompletionFunction = {$_.Name} } $_ | % $convertToTabCompletionFunction } #Replace the final Invoke-TabItemSelector with: @@ $ChildItems | convertTypeToTabCompletionName |% {$container + "\\" + $_}| Invoke-TabItemSelector $lastPath -SelectionHandler $SelectionHandler -return $lastword -ForceList |% {
PowerShellCorpus/PoshCode/h20 -Hashtables 2 object.ps1
h20 -Hashtables 2 object.ps1
#hashtable to object function. #used to be able to make custom objects with math inside the pipeline #e.g. 1..10 | h20 { @{karl = $_;dude = $_+1} } # gps | h20 { @{name = $_.processname; mem = $_.workingset / 1MB} } function h20([scriptblock]$sb ) { begin {} process{ if ($sb -ne $null) { $ht = &$sb; if ($ht -is [hashtable]) { New-Object PSObject -Property $ht} } } end{} }
PowerShellCorpus/PoshCode/PresentationFrame.xaml.ps1
PresentationFrame.xaml.ps1
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"> <!-- Resource dictionary entries should be defined here. --> <LinearGradientBrush x:Key="NavigationWindowNavigationChromeBackground" EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#FFFFFF" Offset="0"/> <GradientStop Color="#E3E8F4" Offset="0.5"/> <GradientStop Color="#E3E8F4" Offset="0.5"/> <GradientStop Color="#FFFFFF" Offset="1.0"/> </LinearGradientBrush> <Style x:Key="NavigationWindowMenu" TargetType="{x:Type Menu}"> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <DockPanel/> </ItemsPanelTemplate> </Setter.Value> </Setter> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/> <Setter Property="IsMainMenu" Value="false"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Menu}"> <ItemsPresenter/> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="MenuScrollButton" BasedOn="{x:Null}" TargetType="{x:Type RepeatButton}"> <Setter Property="ClickMode" Value="Hover"/> <Setter Property="MinWidth" Value="0"/> <Setter Property="MinHeight" Value="0"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type RepeatButton}"> <DockPanel SnapsToDevicePixels="true" Background="Transparent"> <Rectangle x:Name="R1" Fill="Transparent" Width="1" DockPanel.Dock="Right"/> <Rectangle x:Name="B1" Fill="Transparent" Height="1" DockPanel.Dock="Bottom"/> <Rectangle x:Name="L1" Fill="Transparent" Width="1" DockPanel.Dock="Left"/> <Rectangle x:Name="T1" Fill="Transparent" Height="1" DockPanel.Dock="Top"/> <ContentPresenter x:Name="ContentContainer" HorizontalAlignment="Center" Margin="2,2,2,2" VerticalAlignment="Center"/> </DockPanel> <ControlTemplate.Triggers> <Trigger Property="IsPressed" Value="true"> <Setter Property="Fill" TargetName="R1" Value="{DynamicResource {x:Static SystemColors.ControlLightLightBrushKey}}"/> <Setter Property="Fill" TargetName="B1" Value="{DynamicResource {x:Static SystemColors.ControlLightLightBrushKey}}"/> <Setter Property="Fill" TargetName="L1" Value="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}"/> <Setter Property="Fill" TargetName="T1" Value="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}"/> <Setter Property="Margin" TargetName="ContentContainer" Value="3,3,1,1"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Geometry x:Key="UpArrow">M 0,4 L 3.5,0 L 7,4 Z</Geometry> <MenuScrollingVisibilityConverter x:Key="MenuScrollingVisibilityConverter"/> <Geometry x:Key="DownArrow">M 0,0 L 3.5,4 L 7,0 Z</Geometry> <Style x:Key="{ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}" BasedOn="{x:Null}" TargetType="{x:Type ScrollViewer}"> <Setter Property="HorizontalScrollBarVisibility" Value="Hidden"/> <Setter Property="VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ScrollViewer}"> <Grid SnapsToDevicePixels="true"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Border Grid.Column="0" Grid.Row="1"> <ScrollContentPresenter Margin="{TemplateBinding Padding}"/> </Border> <RepeatButton Style="{StaticResource MenuScrollButton}" Focusable="false" Grid.Column="0" Grid.Row="0" Command="{x:Static ScrollBar.LineUpCommand}" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}"> <RepeatButton.Visibility> <MultiBinding FallbackValue="Visibility.Collapsed" Converter="{StaticResource MenuScrollingVisibilityConverter}" ConverterParameter="0"> <Binding Path="ComputedVerticalScrollBarVisibility" RelativeSource="{RelativeSource TemplatedParent}"/> <Binding Path="VerticalOffset" RelativeSource="{RelativeSource TemplatedParent}"/> <Binding Path="ExtentHeight" RelativeSource="{RelativeSource TemplatedParent}"/> <Binding Path="ViewportHeight" RelativeSource="{RelativeSource TemplatedParent}"/> </MultiBinding> </RepeatButton.Visibility> <Path Fill="{DynamicResource {x:Static SystemColors.MenuTextBrushKey}}" Data="{StaticResource UpArrow}"/> </RepeatButton> <RepeatButton Style="{StaticResource MenuScrollButton}" Focusable="false" Grid.Column="0" Grid.Row="2" Command="{x:Static ScrollBar.LineDownCommand}" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}"> <RepeatButton.Visibility> <MultiBinding FallbackValue="Visibility.Collapsed" Converter="{StaticResource MenuScrollingVisibilityConverter}" ConverterParameter="100"> <Binding Path="ComputedVerticalScrollBarVisibility" RelativeSource="{RelativeSource TemplatedParent}"/> <Binding Path="VerticalOffset" RelativeSource="{RelativeSource TemplatedParent}"/> <Binding Path="ExtentHeight" RelativeSource="{RelativeSource TemplatedParent}"/> <Binding Path="ViewportHeight" RelativeSource="{RelativeSource TemplatedParent}"/> </MultiBinding> </RepeatButton.Visibility> <Path Fill="{DynamicResource {x:Static SystemColors.MenuTextBrushKey}}" Data="{StaticResource DownArrow}"/> </RepeatButton> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> <LinearGradientBrush x:Key="NavigationWindowDownArrowFill" EndPoint="0,1" StartPoint="0,0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#33B5DA" Offset="0"/> <GradientStop Color="#335799" Offset="1"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <Style x:Key="NavigationWindowMenuItem" TargetType="{x:Type MenuItem}"> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type MenuItem}"> <Grid> <Popup x:Name="PART_Popup" AllowsTransparency="true" IsOpen="{Binding (MenuItem.IsSubmenuOpen), RelativeSource={RelativeSource TemplatedParent}}" Placement="Bottom" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" VerticalOffset="2" Focusable="false"> <!-- <Microsoft_Windows_Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent"> --> <Border x:Name="SubMenuBorder" Background="{DynamicResource {x:Static SystemColors.MenuBrushKey}}" BorderBrush="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}" BorderThickness="1"> <ScrollViewer Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}" CanContentScroll="true"> <ItemsPresenter Margin="2" KeyboardNavigation.DirectionalNavigation="Cycle" KeyboardNavigation.TabNavigation="Cycle"/> </ScrollViewer> </Border> <!-- </Microsoft_Windows_Themes:SystemDropShadowChrome> --> </Popup> <Grid x:Name="Panel" HorizontalAlignment="Right" Width="26" Background="Transparent"> <Border x:Name="HighlightBorder" SnapsToDevicePixels="True" Visibility="Hidden" BorderBrush="#B0B5BACE" BorderThickness="1,1,1,1" CornerRadius="2"> <Border.Background> <LinearGradientBrush EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#20DDDDDD" Offset="0"/> <GradientStop Color="#80FFFFFF" Offset="1"/> </LinearGradientBrush> </Border.Background> <Border BorderBrush="#A0FFFFFF" BorderThickness="1" CornerRadius="1.5"/> </Border> <Path x:Name="Arrow" Fill="{StaticResource NavigationWindowDownArrowFill}" Stroke="White" StrokeLineJoin="Round" StrokeThickness="1" HorizontalAlignment="Right" Margin="{TemplateBinding Padding}" VerticalAlignment="Center" SnapsToDevicePixels="false" Data="M 0 0 L 4.5 5 L 9 0 Z"/> </Grid> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsHighlighted" Value="true"> <Setter Property="Visibility" TargetName="HighlightBorder" Value="Visible"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Fill" TargetName="Arrow" Value="#A5AABE"/> </Trigger> <!-- <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="true"> <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/> <Setter Property="SnapsToDevicePixels" TargetName="Shdw" Value="true"/> <Setter Property="Color" TargetName="Shdw" Value="#71000000"/> </Trigger> --> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <SolidColorBrush x:Key="CurrentEntryBackground" Opacity="0.25" Color="{StaticResource {x:Static SystemColors.HighlightColorKey}}"/> <Style x:Key="NavigationWindowNavigationButtonJournalEntryStyle" TargetType="{x:Type MenuItem}"> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="Header" Value="{Binding (JournalEntry.Name)}"/> <Setter Property="Command" Value="NavigationCommands.NavigateJournal"/> <Setter Property="CommandTarget" Value="{Binding TemplatedParent, RelativeSource={RelativeSource AncestorType={x:Type Menu}}}"/> <Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self}}"/> <Setter Property="JournalEntryUnifiedViewConverter.JournalEntryPosition" Value="{Binding (JournalEntryUnifiedViewConverter.JournalEntryPosition)}"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type MenuItem}"> <Grid x:Name="Panel" SnapsToDevicePixels="true" Background="Transparent"> <Path x:Name="Glyph" Stroke="{TemplateBinding Foreground}" StrokeEndLineCap="Triangle" StrokeStartLineCap="Triangle" StrokeThickness="2" HorizontalAlignment="Left" Margin="7,5" Width="10" Height="10" SnapsToDevicePixels="false"/> <ContentPresenter Margin="24,5,21,5" ContentSource="Header"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="JournalEntryUnifiedViewConverter.JournalEntryPosition" Value="Current"> <Setter Property="Background" TargetName="Panel" Value="{StaticResource CurrentEntryBackground}"/> <Setter Property="Data" TargetName="Glyph" Value="M 0,5 L 2.5,8 L 7,3 "/> <Setter Property="FlowDirection" TargetName="Glyph" Value="LeftToRight"/> <Setter Property="StrokeLineJoin" TargetName="Glyph" Value="Miter"/> </Trigger> <Trigger Property="IsHighlighted" Value="true"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/> <Setter Property="Background" TargetName="Panel" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsHighlighted" Value="true"/> <Condition Property="JournalEntryUnifiedViewConverter.JournalEntryPosition" Value="Forward"/> </MultiTrigger.Conditions> <Setter Property="Stroke" TargetName="Glyph" Value="White"/> <Setter Property="Data" TargetName="Glyph" Value="M 1,5 L 7,5 M 5,1 L 9,5 L 5,9"/> </MultiTrigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsHighlighted" Value="true"/> <Condition Property="JournalEntryUnifiedViewConverter.JournalEntryPosition" Value="Back"/> </MultiTrigger.Conditions> <Setter Property="Stroke" TargetName="Glyph" Value="White"/> <Setter Property="Data" TargetName="Glyph" Value="M 9,5 L 3,5 M 5,1 L 1,5 L 5,9"/> </MultiTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <JournalEntryUnifiedViewConverter x:Key="JournalEntryUnifiedViewConverter"/> <LinearGradientBrush x:Key="NavigationWindowNavigationButtonFillDisabled" EndPoint="0.5,1.0" StartPoint="0.5,0.0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#FFFFFF" Offset="0"/> <GradientStop Color="#EBEEF5" Offset="0.5"/> <GradientStop Color="#D8DDEB" Offset="0.5"/> <GradientStop Color="#DFE2F0" Offset="1.0"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x:Key="NavigationWindowNavigationButtonFillHover" EndPoint="0.5,1.0" StartPoint="0.5,0.0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#FFFFFF" Offset="0.0"/> <GradientStop Color="#DFEDF9" Offset="0.1"/> <GradientStop Color="#3086E1" Offset="0.47"/> <GradientStop Color="#003B91" Offset="0.47"/> <GradientStop Color="#1793EF" Offset="0.70"/> <GradientStop Color="#5AD4FF" Offset="0.85"/> <GradientStop Color="#BDFFFF" Offset="0.95"/> <GradientStop Color="#FFFFFF" Offset="1.0"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x:Key="NavigationWindowNavigationButtonFillPressed" EndPoint="0.5,1.0" StartPoint="0.5,0.0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#C0D2F5" Offset="0.0"/> <GradientStop Color="#5E7A9C" Offset="0.47"/> <GradientStop Color="#00062D" Offset="0.47"/> <GradientStop Color="#005F9F" Offset="0.70"/> <GradientStop Color="#1FA4E2" Offset="0.85"/> <GradientStop Color="#61DAFF" Offset="0.95"/> <GradientStop Color="#48CFFF" Offset="1.0"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x:Key="NavigationWindowNavigationButtonFillEnabled" EndPoint="0.5,1.0" StartPoint="0.5,0.0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#FFFFFF" Offset="0.0"/> <GradientStop Color="#CCD4E9" Offset="0.1"/> <GradientStop Color="#4881D2" Offset="0.47"/> <GradientStop Color="#001A5A" Offset="0.47"/> <GradientStop Color="#007BD6" Offset="0.70"/> <GradientStop Color="#54DAFF" Offset="0.85"/> <GradientStop Color="#86FFFF" Offset="0.95"/> <GradientStop Color="#FFFFFF" Offset="1.0"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x:Key="NavigationWindowNavigationButtonStrokeEnabled" EndPoint="0,1" StartPoint="0,0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#6C90C4" Offset="0"/> <GradientStop Color="#315BB4" Offset="0.5"/> <GradientStop Color="#002091" Offset="0.5"/> <GradientStop Color="#08377C" Offset="1"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x:Key="NavigationWindowNavigationArrowFill" EndPoint="0,1" StartPoint="0,0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#FFFFFF" Offset="0.5"/> <GradientStop Color="#EEEEEE" Offset="0.5"/> <GradientStop Color="#B0B0B0" Offset="1"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> <LinearGradientBrush x:Key="NavigationWindowNavigationArrowStrokeEnabled" EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#8AB1FB" Offset="0"/> <GradientStop Color="#002874" Offset="1"/> </LinearGradientBrush> <Style x:Key="NavigationWindowBackButtonStyle" TargetType="{x:Type Button}"> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="Command" Value="NavigationCommands.BrowseBack"/> <Setter Property="Focusable" Value="false"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Grid Width="24" Height="24" Background="Transparent"> <Ellipse x:Name="Circle" Fill="{StaticResource NavigationWindowNavigationButtonFillEnabled}" Stroke="{StaticResource NavigationWindowNavigationButtonStrokeEnabled}" StrokeThickness="1"/> <Path x:Name="Arrow" Fill="{StaticResource NavigationWindowNavigationArrowFill}" Stroke="{StaticResource NavigationWindowNavigationArrowStrokeEnabled}" StrokeThickness="0.75" HorizontalAlignment="Center" VerticalAlignment="Center" Data="M0.37,7.69 L5.74,14.20 A1.5,1.5,0,1,0,10.26,12.27 L8.42,10.42 14.90,10.39 A1.5,1.5,0,1,0,14.92,5.87 L8.44,5.90 10.31,4.03 A1.5,1.5,0,1,0,5.79,1.77 z"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Fill" TargetName="Circle" Value="{StaticResource NavigationWindowNavigationButtonFillDisabled}"/> <Setter Property="Stroke" TargetName="Circle" Value="#B5BACE"/> <Setter Property="Stroke" TargetName="Arrow" Value="#B0B5BACE"/> <Setter Property="Fill" TargetName="Arrow" Value="#D0FFFFFF"/> </Trigger> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Fill" TargetName="Circle" Value="{StaticResource NavigationWindowNavigationButtonFillHover}"/> </Trigger> <Trigger Property="IsPressed" Value="true"> <Setter Property="Fill" TargetName="Circle" Value="{StaticResource NavigationWindowNavigationButtonFillPressed}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="NavigationWindowForwardButtonStyle" TargetType="{x:Type Button}"> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="Command" Value="NavigationCommands.BrowseForward"/> <Setter Property="Focusable" Value="false"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Grid Width="24" Height="24" Background="Transparent"> <Ellipse x:Name="Circle" Fill="{StaticResource NavigationWindowNavigationButtonFillEnabled}" Stroke="{StaticResource NavigationWindowNavigationButtonStrokeEnabled}" StrokeThickness="1" Grid.Column="0"/> <Path x:Name="Arrow" Fill="{StaticResource NavigationWindowNavigationArrowFill}" Stroke="{StaticResource NavigationWindowNavigationArrowStrokeEnabled}" StrokeThickness="0.75" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="0.5,0" Grid.Column="0" Data="M0.37,7.69 L5.74,14.20 A1.5,1.5,0,1,0,10.26,12.27 L8.42,10.42 14.90,10.39 A1.5,1.5,0,1,0,14.92,5.87 L8.44,5.90 10.31,4.03 A1.5,1.5,0,1,0,5.79,1.77 z"> <Path.RenderTransform> <ScaleTransform ScaleX="-1"/> </Path.RenderTransform> </Path> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Fill" TargetName="Circle" Value="{StaticResource NavigationWindowNavigationButtonFillDisabled}"/> <Setter Property="Stroke" TargetName="Circle" Value="#B5BACE"/> <Setter Property="Stroke" TargetName="Arrow" Value="#B0B5BACE"/> <Setter Property="Fill" TargetName="Arrow" Value="#D0FFFFFF"/> </Trigger> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Fill" TargetName="Circle" Value="{StaticResource NavigationWindowNavigationButtonFillHover}"/> </Trigger> <Trigger Property="IsPressed" Value="true"> <Setter Property="Fill" TargetName="Circle" Value="{StaticResource NavigationWindowNavigationButtonFillPressed}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <ControlTemplate x:Key="FrameNavChromeTemplateKey" TargetType="{x:Type Frame}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"> <DockPanel> <Grid Height="22" Background="{StaticResource NavigationWindowNavigationChromeBackground}" DockPanel.Dock="Bottom"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="16"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Menu x:Name="NavMenu" Margin="1,0,0,0" Style="{StaticResource NavigationWindowMenu}" VerticalAlignment="Center" Height="16" Grid.ColumnSpan="3"> <MenuItem Style="{StaticResource NavigationWindowMenuItem}" Padding="0,2,4,0" ItemContainerStyle="{StaticResource NavigationWindowNavigationButtonJournalEntryStyle}" IsSubmenuOpen="{Binding (MenuItem.IsSubmenuOpen), Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"> <MenuItem.ItemsSource> <MultiBinding Converter="{StaticResource JournalEntryUnifiedViewConverter}"> <Binding Path="BackStack" RelativeSource="{RelativeSource TemplatedParent}"/> <Binding Path="ForwardStack" RelativeSource="{RelativeSource TemplatedParent}"/> </MultiBinding> </MenuItem.ItemsSource> </MenuItem> </Menu> <Path StrokeThickness="1" HorizontalAlignment="Left" Margin="2,0,0,0" VerticalAlignment="Center" IsHitTestVisible="false" SnapsToDevicePixels="false" Grid.Column="0" Grid.ColumnSpan="3" Data="M22.5767,21.035 Q27,19.37 31.424,21.035 A12.5,12.5,0,0,0,53.5,13 A12.5,12.5,0,0,0,37.765,0.926 Q27,4.93 16.235,0.926 A12.5,12.5,0,0,0,0.5,13 A12.5,12.5,0,0,0,22.5767,21.035 z"> <Path.LayoutTransform> <ScaleTransform ScaleX="0.667" ScaleY="0.667"/> </Path.LayoutTransform> <Path.Stroke> <LinearGradientBrush EndPoint="0,1" StartPoint="0,0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#FFB7C2E3" Offset="0.2"/> <GradientStop Color="#A0FFFFFF" Offset="0.9"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Path.Stroke> <Path.Fill> <LinearGradientBrush EndPoint="0,1" StartPoint="0,0"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="#A0C2CCE7" Offset="0"/> <GradientStop Color="#60FFFFFF" Offset="1"/> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Path.Fill> </Path> <Button Margin="3,0,1,0" Style="{StaticResource NavigationWindowBackButtonStyle}" Grid.Column="0"> <Button.LayoutTransform> <ScaleTransform ScaleX="0.667" ScaleY="0.667"/> </Button.LayoutTransform> </Button> <Button Margin="1,0,0,0" Style="{StaticResource NavigationWindowForwardButtonStyle}" Grid.Column="1"> <Button.LayoutTransform> <ScaleTransform ScaleX="0.667" ScaleY="0.667"/> </Button.LayoutTransform> </Button> <!--<TextBlock >--> <TextBlock Grid.Column="3" FontWeight="Bold" Text="{Binding Content.Title, ElementName=PART_FrameCP, Mode=Default}"/> <!--<TextBlock FontWeight="Bold" Text="{Binding BackStack, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Frame}}}" /> </TextBlock>--> </Grid> <ContentPresenter x:Name="PART_FrameCP"/> </DockPanel> </Border> <ControlTemplate.Triggers> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="CanGoForward" Value="false"/> <Condition Property="CanGoBack" Value="false"/> </MultiTrigger.Conditions> <Setter Property="IsEnabled" TargetName="NavMenu" Value="false"/> </MultiTrigger> </ControlTemplate.Triggers> </ControlTemplate> <Style TargetType="{x:Type Frame}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Frame}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"> <ContentPresenter x:Name="PART_FrameCP"/> </Border> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="NavigationUIVisibility" Value="Visible"> <Setter Property="Template" Value="{StaticResource FrameNavChromeTemplateKey}"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="JournalOwnership" Value="OwnsJournal"/> <Condition Property="NavigationUIVisibility" Value="Automatic"/> </MultiTrigger.Conditions> <Setter Property="Template" Value="{StaticResource FrameNavChromeTemplateKey}"/> </MultiTrigger> </Style.Triggers> </Style> </ResourceDictionary>
PowerShellCorpus/PoshCode/Experimental.IO 2.0.ps1
Experimental.IO 2.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 } Add-Type -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; namespace Huddled.Experimental.IO { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class TransformAttribute : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public override string ToString() { return string.Format("[Transform(Script='{{{0}}}')]", Script); } 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 TransformAttribute() { this.Script = ScriptBlock.Create("{`$args}"); } public TransformAttribute( ScriptBlock Script ) { this.Script = Script; } public ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } } "@ function Where-Wildcard { param( [Parameter(ValueFromPipeline=$true)] [string[]]$InputObject , [Parameter(Position=0)] [string[]]$Like = "*" , [Parameter(Position=1)] [string[]]$NotLike = $null ) process { foreach($item in $InputObject) { $filename = Split-Path $item -Leaf $passthru = $false foreach($pattern in $Like) { $passthru = $passthru -or $filename -like $pattern } foreach($pattern in $NotLike) { $passthru = $passthru -and !($filename -like $pattern) } if($passthru) { Write-Output $item } } } } function Get-LongPath { [CmdletBinding(DefaultParameterSetName="AllItems")] param( [Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)] [Alias("FullName")] [string[]]$LiteralPath = $pwd , [string[]]$Include = "*" , [string[]]$Exclude = $null , [Parameter(ParameterSetName="DirectoriesOnly")] [Alias("od","do")] [switch]$DirectoriesOnly , [Parameter(ParameterSetName="FilesOnly")] [Alias("of","fo")] [switch]$FilesOnly , [switch]$Recurse , [switch]$Indent , [switch]$OrderDirectoriesFirst ) begin { if($Recurse -and $Indent -and (Test-Path variable:script:pad)) { $script:pad += " " } else { $script:pad = "" } $null = $PSBoundParameters.Remove("LiteralPath") if($PSCmdlet.ParameterSetName -eq "FilesOnly") { Write-Verbose $LiteralPath } } process { foreach($Path in $LiteralPath) { if(![Microsoft.Experimental.IO.LongPathDirectory]::Exists($Path)){ $Include = Split-Path $Path -Leaf $Path = Split-Path $Path } switch($PSCmdlet.ParameterSetName) { "FilesOnly" { if($Recurse) { [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFileSystemEntries( $Path ) | ForEach-Object{ if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists( $_ ) ) { Get-LongPath $_ @PSBoundParameters } else { Where-Wildcard -InputObject $_ -Like $Include -NotLike $Exclude | ForEach-Object{ $script:pad + $_ } } } } else { [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFiles( $Path ) | Where-Wildcard -like $Include -notLike $Exclude } } "DirectoriesOnly" { if($Recurse) { [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateDirectories( $Path ) | ForEach-Object{ Where-Wildcard -InputObject $_ -Like $Include -NotLike $Exclude | ForEach-Object{ $script:pad + $_ + "\\" } if($recurse) { Get-LongPath $_ @PSBoundParameters } } } else { [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateDirectories( $Path ) | Where-Wildcard -Like $Include -notLike $Exclude } } "AllItems" { if($OrderDirectoriesFirst) { [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateDirectories( $Path ) | Where-Wildcard -Like $Include -NotLike $Exclude | ForEach-Object{ $script:pad + $_ + "\\" } [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFiles( $Path ) | Where-Wildcard -like $Include -notLike $Exclude } else { if($recurse) { [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFileSystemEntries( $Path ) | ForEach-Object{ if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists( $_ ) ) { Where-Wildcard -InputObject $_ -Like $Include -NotLike $Exclude | ForEach-Object{ $script:pad + $_ + "\\" } Get-LongPath $_ @PSBoundParameters } else { Where-Wildcard -InputObject $_ -Like $Include -NotLike $Exclude | ForEach-Object{ $script:pad + $_ } } } } else { [Microsoft.Experimental.IO.LongPathDirectory]::EnumerateFileSystemEntries( $Path ) | Where-Wildcard -like $Include -notLike $Exclude | ForEach-Object { if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists( $_ ) ) { $script:pad + $_ + "\\" } else { $script:pad + $_ } } } } } } } } 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 } } } } $ExperimentalFormatColums = 4 function Format-Color { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [string[]]$InputObject , [ConsoleColor]$Directories = 'Cyan' , [ConsoleColor]$Executable = 'Green' , [int]$Columns = $ExperimentalFormatColums ) begin { $NoNewLine = $columns -gt 0 $Count = 0 } process { foreach($item in $InputObject) { $Count = $Count + 1 $filename = Split-Path $item -Leaf $output = $item if($NoNewLine) { $width = $Host.UI.RawUI.BufferSize.Width / $Columns if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists( $item ) ) { $output = "$filename\\".PadRight( $width ).SubString(0,$width-1).PadRight( $width ) } else { $output = $filename.PadRight( $width ).SubString(0,$width-1).PadRight( $width ) } } if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists( $item ) ) { Write-Host $output -Fore $Directories -NoNewLine:$NoNewLine } elseif( Where-Wildcard -InputObject $item -Like "*.exe","*.cmd","*.bat","*.ps1") { Write-Host $output -Fore $Executable -NoNewLine:$NoNewLine } else { Write-Host $output -NoNewLine:$NoNewLine } # if($NoNewLine -and (($Count % $Columns) -eq 0)) { # Write-Host # } } } end { if($NoNewLine -and (($Count % $Columns) -ne 0)) { Write-Host } } } function Copy-LongPath { param( [Parameter(ValueFromPipeline=$true)] [string[]]$LiteralPath , [Parameter(ValueFromPipeline=$true)] [string]$Destination , [switch]$Force ) process { foreach($item in $LiteralPath) { if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists($Destination) ) { $target = Join-Path $Destination (Split-Path $item -Leaf) } else { $target = $Destination } [Microsoft.Experimental.IO.LongPathFile]::Copy($item, $target, $force) } } } function Move-LongPath { param( [Parameter(ValueFromPipeline=$true)] [string[]]$LiteralPath , [Parameter(ValueFromPipeline=$true)] [string]$Destination , [switch]$Force ) process { foreach($item in $LiteralPath) { if( [Microsoft.Experimental.IO.LongPathDirectory]::Exists($Destination) ) { $target = Join-Path $Destination (Split-Path $item -Leaf) } else { $target = $Destination } if([Microsoft.Experimental.IO.LongPathFile]::Exists($target) -and $Force) { [Microsoft.Experimental.IO.LongPathFile]::Delete($target) } [Microsoft.Experimental.IO.LongPathFile]::Copy($item, $target) } } } function Remove-LongPath { param( [Parameter(ValueFromPipeline=$true)] [string[]]$LiteralPath ) process { foreach($item in $LiteralPath) { [Microsoft.Experimental.IO.LongPathFile]::Delete($item) } } } function Get-ContentLongPath { param( [Parameter(ValueFromPipeline=$true,Position=0)] [string[]]$LiteralPath , [switch]$All ) process { foreach($path in $LiteralPath) { $stream = [Microsoft.Experimental.IO.LongPathFile]::Open( $path, "Open", "Read" ) $reader = New-Object System.IO.StreamReader $stream, $true if($All) { $reader.ReadToEnd() } else { while(!$reader.EndOfStream) { $reader.ReadLine() } } $reader.Close() $stream.Close() } } } function Set-ContentLongPath { param( [Parameter(Position=0)] [string[]]$LiteralPath , [Parameter(Position=1, ValueFromPipeline=$true)] [string[]]$Value , [System.Text.Encoding] [Huddled.Experimental.IO.Transform({ param([string]$Encoding) $coding = [System.Text.Encoding]::GetEncodings() | Where-Object { $_.Name -like $Encoding } | Select -First 1 if(!$coding) { $coding = [System.Text.Encoding]::GetEncodings() | Where-Object { $_.DisplayName -like $Encoding } | Select -First 1 } [Text.Encoding]::GetEncoding( $coding.CodePage ) })] $Encoding = "UTF-8" ) begin { $streams = @() $writers = @() foreach($item in $LiteralPath) { $stream = [Microsoft.Experimental.IO.LongPathFile]::Open( $LiteralPath, "OpenOrCreate", "Write" ) $streams += $stream $writers += New-Object System.IO.StreamWriter $stream, $encoding } } process { foreach($writer in $writers) { foreach($v in $Value) { $writer.WriteLine( $v ) } } } end { foreach($writer in $writers) { $writer.Close() } foreach($stream in $streams) { $stream.Close() } } } New-Alias fco Format-Color -ErrorAction SilentlyContinue New-Alias glp Get-LongPath -ErrorAction SilentlyContinue New-Alias cplp Copy-LongPath -ErrorAction SilentlyContinue New-Alias mvlp Move-LongPath -ErrorAction SilentlyContinue New-Alias rmlp Remove-LongPath -ErrorAction SilentlyContinue New-Alias gclp Get-ContentLongPath -ErrorAction SilentlyContinue New-Alias sclp Set-ContentLongPath -ErrorAction SilentlyContinue Export-ModuleMember -Alias * -Function Copy-LongPath, Format-Color, Get-ContentLongPath, Get-LongPath, Move-LongPath, Remove-LongPath, Set-ContentLongPath
PowerShellCorpus/PoshCode/Get-Tree.ps1
Get-Tree.ps1
#.Synopsis # Creates a fir tree in your console! #.Description # A simple christmas tree simulation with (optional) flashing lights. # Requires your font be set to a True Type font (best results with Consolas). #.Parameter Trim # Whether or not to trim the tree. NOTE: In violation of convention, this switch to true! # To disable the tree lights, use Get-Tree -Trim:$false #.Example # Get-Tree -Trim:$false #.Example # Get-tree Red, Cyan, Blue, Gray, Green # # Description # ----------- # Creates a tree with multi-colored lights in the five colors that work best... param( [switch]$Trim=$true , [ValidateSet("Red","Blue","Cyan","Yellow","Green","Gray","Magenta","All")] [Parameter(Position=0)] [String[]]$LightColor = @("Red") ) if($LightColor -contains "All") { $LightColor = "Red","Yellow","Green","Gray","Magenta","Cyan","Blue" } Clear-Host $OFS = "`n" $center = [Math]::Min( $Host.UI.RawUI.WindowSize.Width, $Host.UI.RawUI.WindowSize.Height ) - 10 $Sparkle = [string][char]0x0489 $DkShade = [string][char]0x2593 $Needles = [string][char]0x0416 $Width = 2 [string[]]$Tree = $( "$(" " * $Center) " "$(" " * $Center)$([char]0x039B)" "$(" " * ($Center - 1))$($Needles * 3)" for($i = 3; $i -lt $center; $i++) { (" " * ($Center - $i)) + (Get-Random $Needles, " ") + ($Needles * (($Width * 2) + 1)) + (Get-Random $Needles, " ") $Width++ } for($i = 0; $i -lt 4; $i++) { " " * ($Center + 2) } ) $TreeOn = $Host.UI.RawUI.NewBufferCellArray( $Tree, "DarkGreen", "DarkMagenta" ) $TreeOff = $Host.UI.RawUI.NewBufferCellArray( $Tree, "DarkGreen", "DarkMagenta" ) # Make the tree trunk black for($x=-2;$x -le 2;$x++) { for($y=0;$y -lt 4;$y++) { $TreeOn[($center+$y),($center+$x)] = $TreeOff[($center+$y),($center+$x)] = New-Object System.Management.Automation.Host.BufferCell $DkShade, "Black", "darkMagenta", "Complete" } } if($trim) { $ChanceOfLight = 50 $LightIndex = 0 for($y=0;$y -le $TreeOn.GetUpperBound(0);$y++) { for($x=0;$x -le $TreeOn.GetUpperBound(1);$x++) { # only put lights on the tree ... if($TreeOn[$y,$x].Character -eq $Needles) { $LightIndex += 1 if($LightIndex -ge $LightColor.Count) { $LightIndex = 0 } # distribute the lights randomly, but not next to each other if($ChanceOfLight -gt (Get-Random -Max 100)) { # Red for on and DarkRed for off. $Light = $LightColor[$LightIndex] $TreeOn[$y,$x] = New-Object System.Management.Automation.Host.BufferCell $Sparkle, $Light, "darkMagenta", "Complete" $TreeOff[$y,$x] = New-Object System.Management.Automation.Host.BufferCell $Sparkle, "Dark$Light", "darkMagenta", "Complete" $ChanceOfLight = 0 # Make sure the next spot won't have a light } else { # Increase the chance of a light every time we don't have one $ChanceOfLight += 3 } } } } # Set the star on top $TreeOn[0,$Center] = $TreeOff[0,$Center] = New-Object System.Management.Automation.Host.BufferCell $Sparkle, "Yellow", "darkMagenta", "Complete" } # Figure out where to put the tree $Coord = New-Object System.Management.Automation.Host.Coordinates (($Host.UI.RawUI.WindowSize.Width - ($Center*2))/2), 2 $Host.UI.RawUI.SetBufferContents( $Coord, $TreeOff ) while($trim) { # flash the lights on and off once per second, if we trimmed the tree sleep -milli 500 $Host.UI.RawUI.SetBufferContents( $Coord, $TreeOn ) sleep -milli 500 $Host.UI.RawUI.SetBufferContents( $Coord, $TreeOff ) }
PowerShellCorpus/PoshCode/Get-McAfeeInfo.ps1
Get-McAfeeInfo.ps1
#------------------------------------------------------------------ # Produces report for McAfee AntiVirus on a set of remote computers # Usage: get-content <list of servers.txt> | .\\GetMcAfeeInfo.ps1 # Optionally pipe output to Export-Csv, ConverTo-Html #------------------------------------------------------------------ Begin { # Pings $cn and if successful, pass $cn to output, otherwise, $null function SelectAlive ( $cn ) { $ping = New-Object System.Net.NetworkInformation.Ping # faster than ping, not to mention easier to parse $reply = $null $cn = $cn.trim() # removes any extraneous whitespace $reply = $ping.Send($cn) if ($reply.status -eq "Success") { Write-Output $cn } else { Write-Warning "$cn : not pingable" } } # Attempts to query registry for $cn and if successful, pass $cn to output, otherwise, $null function SelectRemoteRegistryAccess ( $cn ) { $ErrorActionPreference = "SilentlyContinue" # squelch errors $root = "LocalMachine" if ( [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey( $root, $cn ) ) { Write-Output $cn } else { Write-Warning "$cn : remote registry access not accessible" } } function GetHKLMRegValue ( $cn, $key, $value ) { $ErrorActionPreference = "SilentlyContinue" # squelch errors $root = "LocalMachine" $rootkey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey( $root, $cn ) $key = $rootkey.OpenSubKey( $key ) $key.GetValue( $value ) } # McAfee registry paths $sKeyPath85 = "SOFTWARE\\McAfee\\DesktopProtection" $sKeyPath85e = "SOFTWARE\\McAfee\\AVEngine" $sKeyPath80 = "SOFTWARE\\Network Associates\\TVD\\VirusScan Enterprise\\CurrentVersion" $sProductVer = "szProductVer" $sEngineVer80 = "szEngineVer" $sEngineVer85 = "EngineVersionMajor" $sVirDefVer80 = "szVirDefVer" $sVirDefVer85 = "AVDatVersion" } Process { # If the computer isn't pingable, move on to next in pipeline. if ( -not ( SelectAlive $_ ) ) { continue } # Can we access the remote registry? If not, then the service is stopped or firewall enabled, or its a Linux box :) if ( -not ( SelectRemoteRegistryAccess $_ ) ) { continue } # create custom object with properties for each datum # technique described here: http://bsonposh.com/archives/221 $Output = "" | Select-Object Server, ProductVersion, EngineVersion, DatVersion if ( GetHKLMRegValue -cn $_ -key $sKeyPath85 -value $sProductVer ) { $output.Server = $_ $output.ProductVersion = GetHKLMRegValue -cn $_ -key $sKeyPath85 -value $sProductVer $output.EngineVersion = GetHKLMRegValue -cn $_ -key $sKeyPath85 -value $sEngineVerValue $output.DatVersion = GetHKLMRegValue -cn $_ -key $sKeyPath85 -value $sVirDefVer85 } else { # do 8.0 } $output }
PowerShellCorpus/PoshCode/Get-InstalledProgram_v2.ps1
Get-InstalledProgram_v2.ps1
function Get-InstalledProgram() { param ( [String[]]$Computer = "n2-ivanyuta", $User ) if ($User -is [String]) { $Connection = Get-Credential -Credential $User } if ($Connection -eq $null){ foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp | where {$_.vendor -notlike "*Microsoft*" -and` $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard" } | select __SERVER,Name,Version,InstallDate $Install_soft } } else { foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection | where {$_.vendor -notlike "*Microsoft*" -and` $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard" } | select __SERVER,Name,Version,InstallDate $Install_soft } } }
PowerShellCorpus/PoshCode/New-ScriptCmdlet.ps1
New-ScriptCmdlet.ps1
# http://blogs.msdn.com/powershell/archive/2008/05/09/fun-with-script-cmdlets.aspx ######################################################################################## # function New-ScriptCmdlet() { [CmdletBinding(DefaultParameterSetName="Type")] PARAM( [Parameter(ParameterSetName="Type",ValueFromPipeline=$true,Position=1)] [Type] $type , [Parameter(ParameterSetName="CommandInfo",ValueFromPipeline=$true,Position=1)] [Management.Automation.CmdletInfo] $commandInfo , [Parameter(Position=0)] [string] $name ) Process { if (! $type) { if ($commandInfo.ImplementingType) { $type = $commandInfo.ImplementingType } } if ((! $type) -and (! $commandInfo)) { @" $(if ($name) { 'function ' + $name + '() {' }) [CmdletBinding()] param () begin {} process {} end {} $(if ($name) {'}' }) "@ } else { if (! ($type.IsSubclassOf([Management.Automation.Cmdlet]))) { throw "Must provide a cmdlet to create a proxy" } $commandMetaData = New-Object Management.Automation.CommandMetadata $type $proxyCommand = @" $(if ($name) { 'function ' + $name + '() {' }) $([Management.Automation.ProxyCommand]::Create($commandMetaData)) $(if ($name) {'}' }) "@ $executionContext.InvokeCommand.NewScriptBlock($proxyCommand) } } #}
PowerShellCorpus/PoshCode/gpupdate on remote pc's_1.ps1
gpupdate on remote pc's_1.ps1
############################################################################### # # Get all servers from a OU and run GPUpdate /force on this machines. # # Version 1.0 # # (C) 2009 - Arne Fokkema # www.ict-freak.nl # # Install the Quest AD cmdlets first!! # ############################################################################### # Requires QAD cmdlets if ((Get-PSSnapin "Quest.ActiveRoles.ADManagement" ` -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Quest.ActiveRoles.ADManagement" } $url = "http://live.sysinternals.com/psexec.exe" $target = "c:\\Tools\\psexec.exe" $TempFile = "C:\\Machines.txt" $Domain = Read-Host ("Enter the FQDN of the Domain") $OU = Read-Host ("Enter the name of the OU") # Check if psexec does exist if (test-path $target) { write-host "psexec.exe is already installed" } else { write-host "psexec.exe doesn't exist" $wc = New-Object System.Net.WebClient $wc.DownloadFile($url, $target); write-host "psexec.exe is now installed" } $Servers = Get-QADComputer -SearchRoot $Domain/$OU | Select Name | out-file $TempFile -force #Cleanup Textfile (Get-Content $TempFile) | Foreach-Object {$_ -replace "Name ", ""} | Set-Content $TempFile (Get-Content $TempFile) | Foreach-Object {$_ -replace "---- ", ""} | Set-Content $TempFile (Get-Content $TempFile) | Foreach-Object {$_ -replace " ", ""} | Set-Content $TempFile (Get-Content $TempFile) | where {$_ -ne ""} >$TempFile $colComputers = Get-Content $TempFile Foreach ($strComputer in $colComputers){c:\\Tools\\psexec.exe \\\\$strComputer gpupdate.exe /target:computer /force} RM $TempFile
PowerShellCorpus/PoshCode/New-XVM_15.ps1
New-XVM_15.ps1
#EXAMPLES <# New-XVM -ComputerName CNSHHYPERVSVR02 -Name "WS2012-TESTSVR01" -SwitchName "External(192.168.1.0/24)" -VhdType NoVHD New-XVM -ComputerName CNSHHYPERVSVR02 -Name "WS2012-TESTSVR02" -SwitchName "External(192.168.1.0/24)" -VhdType ExistingVHD -VhdPath D:\\vhds\\WS2012-TESTSVR02.vhdx New-XVM -ComputerName CNSHHYPERVSVR02 -Name "WS2012-TESTSVR03" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD New-XVM -ComputerName CNSHHYPERVSVR02 -Name "WS2012-TESTSVR04" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -DiskType Dynamic New-XVM -ComputerName CNSHHYPERVSVR02 -Name "WS2012-TESTSVR05" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB New-XVM -ComputerName CNSHHYPERVSVR02 -Name "WS2012-TESTSVR06" -SwitchName "External(192.168.1.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx' New-XVM -ComputerName CNSHHYPERVSVR02 -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] } } } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $configParams = $configParams -join " " $command += " $configParams -ErrorAction Stop" } Try { Invoke-Expression -Command $command } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } End {} }
PowerShellCorpus/PoshCode/Get-TopProcess_1.ps1
Get-TopProcess_1.ps1
param( [string] $sortCriteria = "Processor", [int] $Count = 5 ) function main { ## Store the performance counters we need ## for the CPU, and Disk I/O numbers $cpuPerfCounters = @{} $ioOtherOpsPerfCounters = @{} $ioOtherBytesPerfCounters = @{} $ioDataOpsPerfCounters = @{} $ioDataBytesPerfCounters = @{} $processes = $null $lastPoll = get-date $lastSnapshotCount = 0 $lastWindowHeight = 0 $processes = get-process | sort Id ## Go through all of the processes we captured foreach($process in $processes) { ## Get the disk activity, based on I/O Perf Counters, ## for the process in question. Then, add it as a note. $cpuPercent = @(for($i=0;$i -lt 10;$i++) { get-cpuPercent $process }) | measure-object -average [int]$Percent = $cpuPercent.Average #$process | add-member NoteProperty Disk $activity -force $process | add-member NoteProperty Processor $Percent -force } $output = $processes | sort -desc $sortCriteria | select -first $Count $output | format-table Id,ProcessName,MainWindowTitle,WorkingSet } ## As a heuristic, gets the total IO and Data operations per second, and ## returns their sum. function get-diskActivity ( $process = $(throw "Please specify a process for which to get disk usage.") ) { $processName = get-processName $process ## We store the performance counter objects in a hashtable. If we don't, ## then they fail to return any information for a few seconds. if(-not $ioOtherOpsPerfCounters[$processName]) { $ioOtherOpsPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Other Operations/sec",$processName) } if(-not $ioOtherBytesPerfCounters[$processName]) { $ioOtherBytesPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Other Bytes/sec",$processName) } if(-not $ioDataOpsPerfCounters[$processName]) { $ioDataOpsPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Data Operations/sec",$processName) } if(-not $ioDataBytesPerfCounters[$processName]) { $ioDataBytesPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","IO Data Bytes/sec",$processName) } ## If a process exits between the time we capture the processes and now, ## then we will be unable to get its NextValue(). This trap simply ## catches the error and continues. trap { continue; } ## Get the performance counter values $ioOther = (100 * $ioOtherOpsPerfCounters[$processName].NextValue()) + ($ioOtherBytesPerfCounters[$processName].NextValue()) $ioData = (100 * $ioDataOpsPerfCounters[$processName].NextValue()) + ($ioDataBytesPerfCounters[$processName].NextValue()) return [int] ($ioOther + $ioData) } ## Get the percentage of time spent by a process. ## Note: this is multiproc "unaware." We need to divide the ## result by the number of processors. function get-cpuPercent ( $process = $(throw "Please specify a process for which to get CPU usage.") ) { $processName = get-processName $process ## We store the performance counter objects in a hashtable. If we don't, ## then they fail to return any information for a few seconds. if(-not $cpuPerfCounters[$processName]) { $cpuPerfCounters[$processName] = new-object System.Diagnostics.PerformanceCounter("Process","% Processor Time",$processName) } ## If a process exits between the time we capture the processes and now, ## then we will be unable to get its NextValue(). This trap simply ## catches the error and continues. trap { continue; } ## Get the performance counter values $cpuTime = ($cpuPerfCounters[$processName].NextValue() / $env:NUMBER_OF_PROCESSORS) return [int] $cpuTime } ## Performance counters are keyed by process name. However, ## processes may share the same name, so duplicates are named ## <process>#1, <process>#2, etc. function get-processName ( $process = $(throw "Please specify a process for which to get the name.") ) { ## If a process exits between the time we capture the processes and now, ## then we will be unable to get its information. This simply ## ignores the error. $errorActionPreference = "SilentlyContinue" $processName = $process.ProcessName $localProcesses = get-process -ProcessName $processName | sort Id if(@($localProcesses).Count -gt 1) { ## Determine where this one sits in the list $processNumber = -1 for($counter = 0; $counter -lt $localProcesses.Count; $counter++) { if($localProcesses[$counter].Id -eq $process.Id) { break } } ## Append its unique identifier, if required $processName += "#$counter" } return $processName } . main
PowerShellCorpus/PoshCode/repr.ps1
repr.ps1
function repr { [CmdletBinding()] [OutputType([string])] Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] $InputObject) process { if($null -eq $InputObject) { $PSCmdlet.WriteObject('$null') } elseif($InputObject -is [bool]) { $PSCmdlet.WriteObject('$' + $InputObject.ToString().ToLowerInvariant()) } elseif($InputObject -is [scriptblock]) { $PSCmdlet.WriteObject("{$InputObject}") } elseif($InputObject -is [string]) { $PSCmdlet.WriteObject("'$InputObject'") } else { $PSCmdlet.WriteObject($InputObject.ToString()) } } }
PowerShellCorpus/PoshCode/Read-Choice_1.ps1
Read-Choice_1.ps1
function Read-Choice { #.Synopsis # Prompt the user for a choice, and return the (0-based) index of the selected item #.Parameter Message # The question to ask #.Parameter Choices # An array of strings representing the "menu" items, with optional ampersands (&) in them to mark (unique) characters to be used to select each item #.Parameter DefaultChoice # The (0-based) index of the menu item to select by default (defaults to zero). #.Parameter Title # An additional caption that can be displayed (usually above the Message) as part of the prompt #.Example # Read-Choice "WEBPAGE BUILDER MENU" "Create Webpage","View HTML code","Publish Webpage","Remove Webpage","E&xit" PARAM([string]$message, [string[]]$choices, [int]$defaultChoice=0, [string]$Title=$null ) if($choices[0].IndexOf('&') -lt 0) { $i = 0; $choices = $choices | ForEach-Object { if($_ -notmatch '&.') { "&$i $_" } else { $_ } $i++ } } $Host.UI.PromptForChoice( $Title, $message, [Management.Automation.Host.ChoiceDescription[]]$choices, $defaultChoice ) }
PowerShellCorpus/PoshCode/Get-HtmlHelp 3.2.ps1
Get-HtmlHelp 3.2.ps1
## Get-HtmlHelp - by Joel Bennett ## version 3.2 ##################################################################### ## Cool Example, using ShowUI: ## Import-Module HtmlHelp ## Import-Module ShowUI -Vers 1.4 ## function Show-Help { [CmdletBinding()]param([String]$Name) ## Window { WebBrowser -Name wb } -On_Loaded { ## $wb.NavigateToString((Get-HtmlHelp $Name)) ## $this.Title = "Get-Help $Name" ## } -Show ## } ## Show-Help Get-Help ## ##################################################################### ## Import System.Web in order to use HtmlEncode functionality Add-Type -Assembly System.Web function ConvertTo-Dictionary([hashtable]$ht) { $kvd = new-object "System.Collections.Generic.Dictionary``2[[System.String],[System.String]]" foreach($kv in $ht.GetEnumerator()) { $kvd.Add($kv.Key,$kv.Value) } return $kvd } function htmlEncode { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ [System.Web.HttpUtility]::HtmlEncode($Text) } } function trim { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)][String]$string) process{ $string.Trim() } } function trimUrl{ param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ [System.Web.HttpUtility]::UrlEncode($Text).Trim() } } function trimHtml{ param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ [System.Web.HttpUtility]::HtmlEncode($Text).Trim() } } function HHSplit { param( $Separator="\\s*\\r?\\n", [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [String]$inputObject ) process{ foreach($item in [regex]::Split($inputObject,$Separator)) { $item.Trim() | Where {$_.Length} } } } function HHjoin { param( [Parameter(Position=0)] $Separator=$ofs, [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [String[]] $inputObject ) begin { [string[]]$array = $inputObject } process { $array += $inputObject } end { if($array.Length -gt 1) { [string]::Join($Separator,$array) } else { $array } } } function Out-HtmlTag { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text, $Tag="p") process{ $html = $Text | out-string -width ([int]::MaxValue) | HHSplit | trimHtml | HHjoin "</$tag>`n<$tag>" $html = $html -replace '(\\S+)(http://.*?)([\\s\\p{P}](?:\\s|$))','<a href="$2">$1</a>$3' "<$tag>$html</$tag>" } } function Out-HtmlList { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ "<li>$($Text | out-string -width ([int]::MaxValue) | HHSplit | trimHtml | HHjoin "</li>`n<li>")</li>" } } function Out-HtmlDefList { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]$Node, [String[]]$Term, [String[]]$Definition ) # begin { "<dl>"} process{ $tx = $Node foreach($t in $Term) { $tx = $tx.$t; Write-Verbose "${t}: $tx" } $dx = $Node foreach($d in $Definition) { $dx = $dx.$d; Write-Verbose "${t}: $dx" } if($tx) { $tx = $tx | trimHtml } else { return } if($dx) { $dx = $dx | trimHtml } else { $dx = "" } "<dt>{0}</dt><dd>{1}</dd>" -f $tx, $dx } # end { "</dl>"} } function Out-HtmlBr { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ $Text | out-string -width ([int]::MaxValue) | HHSplit | trimHtml | HHjoin "<br />" } } ## Utility Functions function Get-UtcTime { Param($Format="") [DateTime]::Now.ToUniversalTime().ToString($Format) } function Encode-Twice { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)][String]$string) process { [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $string ) ) } } ## Get-HtmlHelp - A Helper function for generating help: ## Usage: Get-HtmlHelp Get-* function Get-HtmlHelp { #.Synopsis # Generates HTML for help #.Description # Takes the output of Get-Help for cmdlets for functions and outputs in HTML form with some basic styling. # #.Example # C:\\PS>Get-HtmlHelp Get-HtmlHelp > Get-HtmlHelp.html # Generates this help into the specified html file. #.Example # C:\\PS>Get-HtmlHelp *-ScheduledJob -OutputFolder . # Generates HTML help for all of the *-ScheduledJob commands and saves them as .html files in the current folder. #.Example # C:\\PS>Get-Command -Module HtmlHelp | Get-HtmlHelp | ForEach { Set-Content $_.Name $_ } # Generates HTML help into files taking advantage of the "Name" property on the output to determine the file name. #.Example # C:\\PS>Import-Module HtmlHelp, ShowUI # C:\\PS>function Show-Help { [CmdletBinding()]param([String]$Name) # >> Window { WebBrowser -Name wb } -On_Loaded { # >> $wb.NavigateToString((Get-HtmlHelp $Name)) # >> $this.Title = "Get-Help $Name" # >> } -Show # >> } # C:\\PS>Show-Help Get-Help # # Creates a function Show-Help to show the HTML rendered help in ShowUI without saving it to file. [CmdletBinding()] param( # The command(s) you want to generate help for. [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [String[]]$Name, # The base Url for links to related commands. [string]$BaseUrl = "http://technet.microsoft.com/en-us/library/", # If set, the output goes to files in the folder. [String]$OutputFolder ) process { foreach($help in $Name | Get-Command -EA "SilentlyContinue" | Get-Help -Full) { $output = $help | Convert-HelpToHtml $baseUrl | Add-Member -Name Name -Type NoteProperty -Value $(Split-Path $help.Name -Leaf) -Passthru if($OutputFolder) { Set-Content $(Join-Path $OutputFolder "$($output.Name).html") $output } else { $Output } } } } function textile { param([string]$text) $text -replace '(?<=\\r\\n\\r\\n|^)\\*\\s(.*)(?=\\r\\n)',"<ul>`r`n<li>`$1</li>" <# start of a list #>` -replace '(?<=\\r\\n)\\*\\s+((?:.|\\r\\n(?![\\*\\r]))+)(?=\\r\\n\\r\\n|\\r\\n\\*|$)',"<li>`$1</li>" <# middle of a list #>` -replace '</li>(?=\\r\\n\\r\\n|$)',"</li>`r`n</ul>" <# end of the list #>` -replace '(?<=\\r\\n\\r\\n|^)([^\\n]*)(?=\\r\\n\\r\\n|$)',"<p>`r`n`$1`r`n</p>" <# regular paragraphs #>` -replace '(?<=\\r\\n\\r\\n)([^\\r\\n]*\\s+[^\\r\\n]*)\\r\\n(-+)(?=\\r\\n\\r\\n)',"<h3>`$1</h3>" <# headers #>` -replace '(?<=[^\\r\\n>])(\\r\\n)(?=[^\\r\\n]+)',"<br />`$1" <# remaining linebreaks #>` -replace " "," &nbsp;" # Because the content is originally for get-help, preserve whitespace } function Convert-ParameterHelp { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)]$ParameterItem) process { $name = $( if($ParameterItem.position -ne "named") { "[-<strong>{0}</strong>]" -f $ParameterItem.name } else { "-<strong>{0}</strong>" -f $ParameterItem.name } ) if($ParameterItem.required -eq "false") { "<nobr>[{0} {1}]</nobr>" -f $name, $ParameterItem.parameterValue } else { "<nobr>{0} {1}</nobr>" -f $name, $ParameterItem.parameterValue } } } function Convert-SyntaxItem { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)]$SyntaxItem) process { "<li>{0} {1}</li>" -f $SyntaxItem.name, $($SyntaxItem.parameter | Convert-ParameterHelp | join " ") } } function Convert-HelpToHtml { param( [string]$baseUrl, [Parameter(ValueFromPipeline=$true)] $Help ) PROCESS { # throw "Can only process -Full view help output" # Name isn't needed, since this is going as the body, but ... # $data = "<html><head><title>$(trimHtml($help.Name))</title></head><body>"; # $data += "<h1>$(trimHtml($help.Name))</h1>" $data = @" <html> <head> <title>$(trimHtml($help.Name))</title> <style type="text/css"> h1, h2, h3, h4, h5, h6 { color: #369 } ul.syntax { list-style: none outside; font-size: .9em; font-family: Consolas, "DejaVu Sans Mono", "Lucida Console", monospace; } ul.syntax li { margin: 3px 0px; } table.parameters th { text-align: left; } </style> </head> <body> <h1 id='$(trimHtml($help.Name))'>$(trimHtml($help.Name))</h1> "@ # Synopsis $data += "`n<h2>Synopsis</h2>`n$($help.Synopsis | Out-HtmlTag -Tag p)" # Syntax $data += "`n<h2 class='syntax'>Syntax</h2>`n<ul class='syntax'>$($help.Syntax.syntaxItem | Convert-SyntaxItem)</ul>" # Related Commands if($help.relatedLinks.navigationLink) { $data += "`n<h2>Related Commands</h2>`n" foreach ($relatedLink in $help.relatedLinks.navigationLink) { $uri = "" if( $relatedLink.uri -ne "" ) { $text = $uri = $relatedLink.uri if($relatedLink.linkText) { $text = $relatedLink.linkText } } elseif($relatedLink.linkText) { $text = $relatedLink.linkText $cmd = get-command $text -EA "SilentlyContinue" if($cmd -and $cmd.PSSnapin) { $uri = "$baseUrl/$(trimUrl $cmd.PSSnapin.Name)/$(trimUrl $text)" } elseif($cmd -and $cmd.Module) { $uri = "$baseUrl/$(trimUrl $cmd.Module.Name)/$(trimUrl $text)" } else { $uri = "$baseUrl/$(trimUrl $text)" } } $data += "<a href='$uri'>$(trimHtml $text)</a><br>" } } # Detailed Description if($help.Description) { $data += "`n<h2>Detailed Description</h2>`n$($help.Description | Out-HtmlTag -Tag p)" } # Parameters $data += "`n<h2>Parameters</h2>" foreach($param in $help.parameters.parameter) { $data += "`n<h4>-$(trimHtml($param.Name)) [&lt;$(trimHtml($param.type.name))&gt;]</h4>" if($Param.Description) { $data += $param.Description | Out-HtmlTag -Tag p } $data += "`n<table class='parameters'>" $data += "`n<tr><th>Required? &nbsp;</th><td> $(trimHtml($param.Required))</td></tr>" $data += "`n<tr><th>Position? &nbsp;</th><td> $(trimHtml($param.Position))</td></tr>" if($param.DefaultValue) { $data += "`n<tr><th>Default value? &nbsp;</th><td> $(trimHtml($param.defaultValue))</td></tr>" } $data += "`n<tr><th>Accept pipeline input? &nbsp;</th><td> $(trimHtml($param.pipelineInput))</td></tr>" if($param.globbing) { $data += "`n<tr><th>Accept wildcard characters? &nbsp;</th><td> $(trimHtml($param.globbing))</td></tr>" } $data += "</table>`n`n" } # Input Type if($help.inputTypes -and $help.inputTypes.inputType) { $data += "`n<h3>Input Type</h3>`n<dl class='input'>$( $help.inputTypes.inputType | Out-HtmlDefList -Term type, name -Definition description )</dl>" } # Output Type if($help.returnValues -and $help.returnValues.returnValue ) { $data += "`n<h3>Output Type</h3>`n<dl class='output'>$( $help.returnValues.returnValue | Out-HtmlDefList -Term type, name -Definition description )</dl>" } # Notes if($help.alertSet -and $help.alertSet.alert) { $data += "`n<h2>Notes</h2>`n$($help.alertSet.alert | Out-HtmlTag -Tag p)" } # Examples if($help.Examples.example -and $help.Examples.example.Length) { $data += "<h2>Examples</h2>" foreach($example in $help.Examples.example){ if($example.title) { $data += "<h4>$(trimHtml($example.title.trim(' -')))</h4>`n" } $data += "<code><strong>C:\\PS&gt;</strong>&nbsp;$(($example.code | Out-HtmlBr) -replace "<br />C:\\\\PS&gt;","<br />`n<strong>C:\\PS&gt;</strong>&nbsp;")</code>" $data += "<p>$($example.remarks | out-string -width ([int]::MaxValue) | Out-HtmlTag -Tag p)</p>" } } $data += "`n</body></html>" write-output $data }} Export-ModuleMember Get-HtmlHelp
PowerShellCorpus/PoshCode/ConvertTo-Hex_2.ps1
ConvertTo-Hex_2.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 ''
PowerShellCorpus/PoshCode/Get-RecurseMember.ps1
Get-RecurseMember.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-GroupMember '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-TextObject.ps1
Convert-TextObject.ps1
##############################################################################\n##\n## Convert-TextObject\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\nConvert a simple string into a custom PowerShell object.\n\n.EXAMPLE\n\n"Hello World" | Convert-TextObject\nGenerates an Object with "P1=Hello" and "P2=World"\n\n.EXAMPLE\n\n"Hello World" | Convert-TextObject -Delimiter "ll"\nGenerates an Object with "P1=He" and "P2=o World"\n\n.EXAMPLE\n\n"Hello World" | Convert-TextObject -Pattern "He(ll.*o)r(ld)"\nGenerates an Object with "P1=llo Wo" and "P2=ld"\n\n.EXAMPLE\n\n"Hello World" | Convert-TextObject -PropertyName FirstWord,SecondWord\nGenerates an Object with "FirstWord=Hello" and "SecondWord=World\n\n.EXAMPLE\n\n"123 456" | Convert-TextObject -PropertyType $([string],[int])\nGenerates an Object with "Property1=123" and "Property2=456"\nThe second property is an integer, as opposed to a string\n\n.EXAMPLE\n\nPS >$ipAddress = (ipconfig | Convert-TextObject -Delim ": ")[2].P2\nPS >$ipAddress\n192.168.1.104\n\n#>\n\n[CmdletBinding(DefaultParameterSetName = "ByDelimiter")]\nparam(\n ## If specified, gives the .NET Regular Expression with which to\n ## split the string. The script generates properties for the\n ## resulting object out of the elements resulting from this split.\n ## If not specified, defaults to splitting on the maximum amount\n ## of whitespace: "\\s+", as long as Pattern is not\n ## specified either.\n [Parameter(ParameterSetName = "ByDelimiter", Position = 0)]\n [string] $Delimiter = "\\s+",\n\n ## If specified, gives the .NET Regular Expression with which to\n ## parse the string. The script generates properties for the\n ## resulting object out of the groups captured by this regular\n ## expression.\n [Parameter(Mandatory = $true,\n ParameterSetName = "ByPattern",\n Position = 0)]\n [string] $Pattern,\n\n ## If specified, the script will pair the names from this object\n ## definition with the elements from the parsed string. If not\n ## specified (or the generated object contains more properties\n ## than you specify,) the script uses property names in the\n ## pattern of P1,P2,...,PN\n [Parameter(Position = 1)]\n [Alias("PN")]\n [string[]] $PropertyName = @(),\n\n ## If specified, the script will pair the types from this list with\n ## the properties from the parsed string. If not specified (or the\n ## generated object contains more properties than you specify,) the\n ## script sets the properties to be of type [string]\n [Parameter(Position = 2)]\n [Alias("PT")]\n [type[]] $PropertyType = @(),\n\n ## The input object to process\n [Parameter(ValueFromPipeline = $true)]\n [string] $InputObject\n)\n\nbegin {\n Set-StrictMode -Version Latest\n}\n\nprocess {\n $returnObject = New-Object PSObject\n\n $matches = $null\n $matchCount = 0\n\n if($PSBoundParameters["Pattern"])\n {\n ## Verify that the input contains the pattern\n ## Populates the matches variable by default\n if(-not ($InputObject -match $pattern))\n {\n return\n }\n\n $matchCount = $matches.Count\n $startIndex = 1\n }\n else\n {\n ## Verify that the input contains the delimiter\n if(-not ($InputObject -match $delimiter))\n {\n return\n }\n\n ## If so, split the input on that delimiter\n $matches = $InputObject -split $delimiter\n $matchCount = $matches.Length\n $startIndex = 0\n }\n\n ## Go through all of the matches, and add them as notes to the output\n ## object.\n for($counter = $startIndex; $counter -lt $matchCount; $counter++)\n {\n $currentPropertyName = "P$($counter - $startIndex + 1)"\n $currentPropertyType = [string]\n\n ## Get the property name\n if($counter -lt $propertyName.Length)\n {\n if($propertyName[$counter])\n {\n $currentPropertyName = $propertyName[$counter - 1]\n }\n }\n\n ## Get the property value\n if($counter -lt $propertyType.Length)\n {\n if($propertyType[$counter])\n {\n $currentPropertyType = $propertyType[$counter - 1]\n }\n }\n\n Add-Member -InputObject $returnObject NoteProperty `\n -Name $currentPropertyName `\n -Value ($matches[$counter].Trim() -as $currentPropertyType)\n }\n\n $returnObject\n}
PowerShellCorpus/PoshCode/New-XVM_12.ps1
New-XVM_12.ps1
#Example #New-XVM -ComputerName HYPERVSVR02 -Name "TLG-INET2" -SwitchName "External(192.168.1.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows #Server 2012 RC Base.vhdx' 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" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $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 } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -ComputerName $ComputerName -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } 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/Invoke-Web 4.2.ps1
Invoke-Web 4.2.ps1
function ConvertTo-Dictionary { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Hashtable")] [Hashtable[]]$Hashtable, [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="WebHeaders")] [System.Collections.Specialized.NameObjectCollectionBase]$Headers, [Parameter(Mandatory=$true,ParameterSetName="Hashtable")] [Type]$TKey, [Parameter(Mandatory=$true,ParameterSetName="Hashtable")] [Type]$Tvalue ) begin { switch($PSCmdlet.ParameterSetName) { "Hashtable" { $dictionary = New-Object "System.Collections.Generic.Dictionary[[$($TKey.FullName)],[$($TValue.FullName)]]" } "WebHeaders" { $dictionary = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" } } } process { switch($PSCmdlet.ParameterSetName) { "Hashtable" { foreach($ht in $Hashtable) { foreach($key in $ht.Keys) { $dictionary.Add( $key, $ht.$key ) } } } "WebHeaders" { foreach($key in $Headers.AllKeys) { $dictionary.Add($key, $Headers[$key]) } } } } end { return $dictionary } } function ConvertFrom-Dictionary { [CmdletBinding()] param($Dictionary, [Switch]$Encode) foreach($key in $Dictionary.Keys) { "{0} = {1}" -f $key, $( if($Encode) { [System.Net.WebUtility]::UrlEncode( $Dictionary.$key ) } else { $Dictionary.$key } ) } } ## Get-WebFile (aka wget for PowerShell) function Invoke-Web { #.Synopsis # Downloads a file or page from the web, or sends web API posts/requests #.Description # Creates an HttpWebRequest to download a web file or post data #.Example # Invoke-Web http://PoshCode.org/PoshCode.psm1 # # Downloads the latest version of the PoshCode module to the current directory #.Example # Invoke-Web http://PoshCode.org/PoshCode.psm1 ~\\Documents\\WindowsPowerShell\\Modules\\PoshCode\\ # # Downloads the latest version of the PoshCode module to the default PoshCode module directory... #.Example # $RssItems = @(([xml](Invoke-Web http://poshcode.org/api/ -passthru)).rss.channel.GetElementsByTagName("item")) # # Returns the most recent items from the PoshCode.org RSS feed #.Notes # History: # v4.2 - Fixed bugs when sending content in the body. # - Added -ForceBasicAuth to allow client-side to specify Authentication: Basic header. # v4.1 - Reworked most of it with PowerShell 3's Invoke-WebRequest as inspiration # - Added a bunch of parameters, the ability to do PUTs etc., and session/cookie persistence # - Did NOT parse the return code and get you the FORMs the way PowerShell 3 does -- upgrade! ;) # v3.12 - Added full help # v3.9 - Fixed and replaced the Set-DownloadFlag # v3.7 - Removed the Set-DownloadFlag code because it was throwing on Windows 7: # "Attempted to read or write protected memory." # v3.6.6 Add UserAgent calculation and parameter # v3.6.5 Add file-name guessing and cleanup # 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) [CmdletBinding(DefaultParameterSetName="NoSession")] param( # The URL of the file/page to download [Parameter(Mandatory=$true,Position=0)] [System.Uri][Alias("Url")]$Uri # = (Read-Host "The URL to download") , # Specifies the body of the request. The body is the content of the request that follows the headers. # You can also pipe a request body to Invoke-WebRequest # Note that you should probably set the ContentType if you're setting the Body [Parameter(ValueFromPipeline=$true)] $Body , # Specifies the content type of the web request, such as "application/x-www-form-urlencoded" (defaults to "application/x-www-form-urlencoded" if the Body is set to a hashtable, dictionary, or other NameValueCollection) [String]$ContentType , # Specifies the client certificate that is used for a secure web request. Enter a variable that contains a certificate or a command or expression that gets the certificate. # To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have sufficient authority, the command fails. [System.Security.Cryptography.X509Certificates.X509Certificate[]] $Certificate , # Sends the results to the specified output file. Enter a path and file name. If you omit the path, the default is the current location. # By default, Invoke-WebRequest returns the results to the pipeline. To send the results to a file and to the pipeline, use the Passthru parameter. [string]$OutFile , # Leave the file unblocked instead of blocked [Switch]$Unblocked , # Rather than saving the downloaded content to a file, output it. # This is for text documents like web pages and rss feeds, and allows you to avoid temporarily caching the text in a file. [switch]$Passthru , # Supresses the Write-Progress during download [switch]$Quiet , # Specifies a name for the session variable. Enter a variable name without the dollar sign ($) symbol. # When you use the session variable in a web request, the variable is populated with a WebRequestSession object. # You cannot use the SessionVariable and WebSession parameters in the same command [Parameter(Mandatory=$true,ParameterSetName="CreateSession")] [String]$SessionVariable , # Specifies a web request session to store data for subsequent requests. # You cannot use the SessionVariable and WebSession parameters in the same command [Parameter(Mandatory=$true,ParameterSetName="UseSession")] $WebSession , # Pass the default credentials [switch]$UseDefaultCredentials , # Specifies a user account that has permission to send the request. The default is the current user. # Type a user name, such as "User01" or "Domain01\\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] [Alias("")]$Credential = [System.Management.Automation.PSCredential]::Empty , # Specifies that Authorization: Basic should always be sent. Requires $Credential to be set, and should only be used with https [ValidateScript({if(!($Credential -or $WebSession){ throw "ForceBasicAuth requires the Credential parameter be set"} else { $true }})] $ForceBasicAuth , # Sets the KeepAlive value in the HTTP header to False. By default, KeepAlive is True. KeepAlive establishes a persistent connection to the server to facilitate subsequent requests. $DisableKeepAlive , # Specifies the headers for the web request. Enter a hash table or dictionary. [System.Collections.IDictionary]$Headers , # Determines how many times Windows PowerShell redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fails. # Our default value is 5 (but .Net's default is 50). A value of 0 (zero) prevents all redirection. [int]$MaximumRedirection = 5 , # Specifies the method used for the web request. Valid values are Default, Delete, Get, Head, Options, Post, Put, and Trace. Default value is Get. [ValidateSet("Default", "Delete", "Get", "Head", "Options", "Post", "Put", "Trace")] [String]$Method = "Get" , # Uses a proxy server for the request, rather than connecting directly to the Internet resource. Enter the URI of a network proxy server. # Note: if you have a default proxy configured in your internet settings, there is no need to set it here. [Uri]$Proxy , # Pass the default credentials to the Proxy [switch]$ProxyUseDefaultCredentials , # Pass specific credentials to the Proxy [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $ProxyCredential= [System.Management.Automation.PSCredential]::Empty , # Text to include at the front of the UserAgent string [string]$UserAgent = "Mozilla/5.0 (Windows NT; Windows NT $([Environment]::OSVersion.Version.ToString(2)); $PSUICulture) WindowsPowerShell/$($PSVersionTable.PSVersion.ToString(2)); PoshCode/4.0; http://PoshCode.org" ) process { Write-Verbose "Downloading '$Uri'" $EAP,$ErrorActionPreference = $ErrorActionPreference, "Stop" $request = [System.Net.HttpWebRequest]::Create($Uri) if($DebugPreference -ne "SilentlyContinue") { Set-Variable WebRequest -Scope 2 -Value $request } $ErrorActionPreference = $EAP # Not everything is a GET request ... $request.Method = $Method.ToUpper() # Now that we have a web request, we'll use the session values first if we have any if($WebSession) { $request.CookieContainer = $WebSession.Cookies $request.Headers = $WebSession.Headers if($WebSession.UseDefaultCredentials) { $request.UseDefaultCredentials } elseif($WebSession.Credentials) { $request.Credentials = $WebSession.Credentials } $request.ClientCertificates = $WebSession.Certificates $request.UserAgent = $WebSession.UserAgent $request.Proxy = $WebSession.Proxy $request.MaximumAutomaticRedirections = $WebSession.MaximumRedirection } else { $request.CookieContainer = $Cookies = New-Object System.Net.CookieContainer } # And override session values with user values if they provided any $request.UserAgent = $UserAgent $request.MaximumAutomaticRedirections = $MaximumRedirection $request.KeepAlive = !$DisableKeepAlive # Authentication normally uses EITHER credentials or certificates, but what do I know ... if($Certificate) { $request.ClientCertificates.AddRange($Certificate) } if($UseDefaultCredentials) { $request.UseDefaultCredentials = $true } elseif($Credential -ne [System.Management.Automation.PSCredential]::Empty) { $request.Credentials = $Credential.GetNetworkCredential() } # You don't have to specify a proxy to specify proxy credentials (maybe your default proxy takes creds) if($Proxy) { $request.Proxy = New-Object System.Net.WebProxy $Proxy } if($request.Proxy -ne $null) { if($ProxyUseDefaultCredentials) { $request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials } elseif($ProxyCredentials -ne [System.Management.Automation.PSCredential]::Empty) { $request.Proxy.Credentials = $ProxyCredentials } } if($ForceBasicAuth) { if(!$request.Credentials) { throw "ForceBasicAuth requires Credentials!" } } $request.Headers.Add('Authorization', 'Basic ' + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($request.Credentials.UserName+":"+$request.Credentials.Password ))); } if($SessionVariable) { Set-Variable $SessionVariable -Scope 1 -Value $WebSession } if($Headers) { foreach($h in $Headers.Keys) { $request.Headers.Add($h, $Headers[$h]) } } if($Body) { if($Body -is [System.Collections.IDictionary] -or $Body -is [System.Collections.Specialized.NameObjectCollectionBase]) { if(!$ContentType) { $ContentType = "application/x-www-form-urlencoded" } [String]$Body = ConvertFrom-Dictionary $Body -Encode:$($ContentType -eq "application/x-www-form-urlencoded") } else { $Body = $Body | Out-String } $encoding = New-Object System.Text.ASCIIEncoding $bytes = $encoding.GetBytes($Body); $request.ContentType = $ContentType $request.ContentLength = $bytes.Length $writer = $request.GetRequestStream(); $writer.Write($bytes, 0, $bytes.Length) $writer.Close() } try { $response = $request.GetResponse(); if($DebugPreference -ne "SilentlyContinue") { Set-Variable WebResponse -Scope 2 -Value $response } } catch [System.Net.WebException] { Write-Error $_.Exception -Category ResourceUnavailable return } catch { # Extra catch just in case, I can't remember what might fall here Write-Error $_.Exception -Category NotImplemented return } Write-Verbose "Retrieved $($Response.ResponseUri)" if((Test-Path variable:response) -and $response.StatusCode -eq 200) { # Magics to figure out a file location based on the response if($OutFile -and !(Split-Path $OutFile)) { $OutFile = Join-Path (Convert-Path (Get-Location -PSProvider "FileSystem")) $OutFile } elseif((!$Passthru -and !$OutFile) -or ($OutFile -and (Test-Path -PathType "Container" $OutFile))) { [string]$OutFile = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value $OutFile = $OutFile.trim("\\/""'") $ofs = "" $OutFile = [Regex]::Replace($OutFile, "[$([Regex]::Escape(""$([System.IO.Path]::GetInvalidPathChars())$([IO.Path]::AltDirectorySeparatorChar)$([IO.Path]::DirectorySeparatorChar)""))]", "_") $ofs = " " if(!$OutFile) { $OutFile = $response.ResponseUri.Segments[-1] $OutFile = $OutFile.trim("\\/") if(!$OutFile) { $OutFile = Read-Host "Please provide a file name" } $OutFile = $OutFile.trim("\\/") if(!([IO.FileInfo]$OutFile).Extension) { $OutFile = $OutFile + "." + $response.ContentType.Split(";")[0].Split("/")[1] } } $OutFile = Join-Path (Convert-Path (Get-Location -PSProvider "FileSystem")) $OutFile } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $response.CharacterSet ) [string]$output = "" } [int]$goal = $response.ContentLength $reader = $response.GetResponseStream() if($OutFile) { try { $writer = new-object System.IO.FileStream $OutFile, "Create" } catch { # Catch just in case, lots of things could go wrong ... Write-Error $_.Exception -Category WriteError return } } [byte[]]$buffer = new-object byte[] 4096 [int]$total = [int]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); Write-Verbose "Read $count" if($OutFile) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $Uri" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $Uri" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($OutFile) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } if(Test-Path variable:response) { $response.Close(); } if($SessionVariable) { Set-Variable $SessionVariable -Scope 1 -Value ([PSCustomObject]@{ Headers = ConvertTo-Dictionary -Headers $request.Headers Cookies = $response.Cookies UseDefaultCredentials = $request.UseDefaultCredentials Credentials = $request.Credentials Certificates = $request.ClientCertificates UserAgent = $request.UserAgent Proxy = $request.Proxy MaximumRedirection = $request.MaximumAutomaticRedirections }) } if($WebSession) { $WebSession.Cookies = $response.Cookies } }}