full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/GithubGist/Elindalyne_1878488_raw_240aa6a875ecd145dd0dd7e7ba7a6376b1091a44_Bootstrap-EC2-Windows-CloudInit.ps1
|
Elindalyne_1878488_raw_240aa6a875ecd145dd0dd7e7ba7a6376b1091a44_Bootstrap-EC2-Windows-CloudInit.ps1
|
# Windows AMIs don't have WinRM enabled by default -- this script will enable WinRM
# AND install the CloudInit.NET service, 7-zip, curl and .NET 4 if its missing.
# Then use the EC2 tools to create a new AMI from the result, and you have a system
# that will execute user-data as a PowerShell script after the instance fires up!
# This has been tested on Windows 2008 R2 Core x64 and Windows 2008 SP2 x86 AMIs provided
# by Amazon
#
# To run the script, open up a PowerShell prompt as admin
# PS> Set-ExecutionPolicy Unrestricted
# PS> icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://raw.github.com/gist/1672426/Bootstrap-EC2-Windows-CloudInit.ps1'))
# Alternatively pass the new admin password and encryption password in the argument list (in that order)
# PS> icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://raw.github.com/gist/1672426/Bootstrap-EC2-Windows-CloudInit.ps1')) -ArgumentList "adminPassword cloudIntEncryptionPassword"
# The script will prompt for a a new admin password and CloudInit password to use for encryption
param(
[Parameter(Mandatory=$true)]
[string]
$AdminPassword,
[Parameter(Mandatory=$true)]
[string]
$CloudInitEncryptionPassword
)
Start-Transcript -Path 'c:\bootstrap-transcript.txt' -Force
Set-StrictMode -Version Latest
Set-ExecutionPolicy Unrestricted
$log = 'c:\Bootstrap.txt'
while (($AdminPassword -eq $null) -or ($AdminPassword -eq ''))
{
$AdminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty Administrator password" -AsSecureString)))
}
while (($CloudInitEncryptionPassword -eq $null) -or ($CloudInitEncryptionPassword -eq ''))
{
$CloudInitEncryptionPassword= [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty password to use for encrypting CloudInit.NET scripts" -AsSecureString)))
}
Import-Module BitsTransfer
$systemPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::System)
$sysNative = [IO.Path]::Combine($env:windir, "sysnative")
#http://blogs.msdn.com/b/david.wang/archive/2006/03/26/howto-detect-process-bitness.aspx
$Is32Bit = (($Env:PROCESSOR_ARCHITECTURE -eq 'x86') -and ($Env:PROCESSOR_ARCHITEW6432 -eq $null))
Add-Content $log -value "Is 32-bit [$Is32Bit]"
#http://msdn.microsoft.com/en-us/library/ms724358.aspx
$coreEditions = @(0x0c,0x27,0x0e,0x29,0x2a,0x0d,0x28,0x1d)
$IsCore = $coreEditions -contains (Get-WmiObject -Query "Select OperatingSystemSKU from Win32_OperatingSystem" | Select -ExpandProperty OperatingSystemSKU)
Add-Content $log -value "Is Core [$IsCore]"
cd $Env:USERPROFILE
#change admin password
net user Administrator $AdminPassword
Add-Content $log -value "Changed Administrator password"
#.net 4
if ((Test-Path "${Env:windir}\Microsoft.NET\Framework\v4.0.30319") -eq $false)
{
$netUrl = if ($IsCore) {'http://download.microsoft.com/download/3/6/1/361DAE4E-E5B9-4824-B47F-6421A6C59227/dotNetFx40_Full_x86_x64_SC.exe' } `
else { 'http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe' }
Start-BitsTransfer $netUrl dotNetFx40_Full.exe
Start-Process -FilePath 'dotNetFx40_Full.exe' -ArgumentList '/norestart /q /ChainingPackage ADMINDEPLOYMENT' -Wait -NoNewWindow
del dotNetFx40_Full.exe
Add-Content $log -value "Found that .NET4 was not installed and downloaded / installed"
}
#configure powershell to use .net 4
$config = @'
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- http://msdn.microsoft.com/en-us/library/w4atty68.aspx -->
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" />
<supportedRuntime version="v2.0.50727" />
</startup>
</configuration>
'@
if (Test-Path "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe")
{
$config | Set-Content "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe.config"
Add-Content $log -value "Configured 32-bit Powershell on x64 OS to use .NET 4"
}
if (Test-Path "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe")
{
$config | Set-Content "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe.config"
Add-Content $log -value "Configured host OS specific Powershell at ${Env:windir}\system32\ to use .NET 4"
}
#winrm
if ($Is32Bit)
{
#this really only applies to oses older than 2008 SP2 or 2008 R2 or Win7
#this uri is Windows 2008 x86 - powershell 2.0 and winrm 2.0
#Start-BitsTransfer 'http://www.microsoft.com/downloads/info.aspx?na=41&srcfamilyid=863e7d01-fb1b-4d3e-b07d-766a0a2def0b&srcdisplaylang=en&u=http%3a%2f%2fdownload.microsoft.com%2fdownload%2fF%2f9%2fE%2fF9EF6ACB-2BA8-4845-9C10-85FC4A69B207%2fWindows6.0-KB968930-x86.msu' Windows6.0-KB968930-x86.msu
#Start-Process -FilePath "wusa.exe" -ArgumentList 'Windows6.0-KB968930-x86.msu /norestart /quiet' -Wait
#Add-Content $log -value ""
}
#check winrm id, if it's not valid and LocalAccountTokenFilterPolicy isn't established, do it
$id = &winrm id
if (($id -eq $null) -and (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -ErrorAction SilentlyContinue) -eq $null)
{
New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -value 1 -propertyType dword
Add-Content $log -value "Added LocalAccountTokenFilterPolicy since winrm id could not be executed"
}
#enable powershell servermanager cmdlets (only for 2008 r2 + above)
if ($IsCore)
{
DISM /Online /Enable-Feature /FeatureName:MicrosoftWindowsPowerShell /FeatureName:ServerManager-PSH-Cmdlets /FeatureName:BestPractices-PSH-Cmdlets
Add-Content $log -value "Enabled ServerManager and BestPractices Cmdlets"
#enable .NET flavors - on server core only -- errors on regular 2008
DISM /Online /Enable-Feature /FeatureName:NetFx2-ServerCore /FeatureName:NetFx2-ServerCore-WOW64 /FeatureName:NetFx3-ServerCore /FeatureName:NetFx3-ServerCore-WOW64
Add-Content $log -value "Enabled .NET frameworks 2 and 3 for x86 and x64"
}
#7zip
$7zUri = if ($Is32Bit) { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922.msi/download' } `
else { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922-x64.msi/download' }
Start-BitsTransfer $7zUri 7z922.msi
Start-Process -FilePath "msiexec.exe" -ArgumentList '/i 7z922.msi /norestart /q INSTALLDIR="c:\program files\7-zip"' -Wait
SetX Path "${Env:Path};C:\Program Files\7-zip" /m
$Env:Path += ';C:\Program Files\7-Zip'
del 7z922.msi
Add-Content $log -value "Installed 7-zip from $7zUri and updated path"
#vc 2010 redstributable
$vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe'} `
else { 'http://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe' }
Start-BitsTransfer $vcredist 'vcredist.exe'
Start-Process -FilePath 'vcredist.exe' -ArgumentList '/norestart /q' -Wait
del vcredist.exe
Add-Content $log -value "Installed VC++ 2010 Redistributable from $vcredist and updated path"
#vc 2008 redstributable
$vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-795376989c03/vcredist_x86.exe'} `
else { 'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe' }
Start-BitsTransfer $vcredist 'vcredist.exe'
Start-Process -FilePath 'vcredist.exe' -ArgumentList '/norestart /q' -Wait
del vcredist.exe
Add-Content $log -value "Installed VC++ 2008 Redistributable from $vcredist and updated path"
#chocolatey - standard one line installer doesn't work on Core b/c Shell.Application can't unzip
if (-not $IsCore)
{
Invoke-Expression ((new-object net.webclient).DownloadString('http://bit.ly/psChocInstall'))
}
else
{
$tempDir = Join-Path $env:TEMP "chocInstall"
if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)}
$file = Join-Path $tempDir "chocolatey.zip"
(new-object System.Net.WebClient).DownloadFile("http://chocolatey.org/api/v1/package/chocolatey", $file)
&7z x $file `-o`"$tempDir`"
Add-Content $log -value 'Extracted Chocolatey'
$chocInstallPS1 = Join-Path (Join-Path $tempDir 'tools') 'chocolateyInstall.ps1'
& $chocInstallPS1
Add-Content $log -value 'Installed Chocolatey / Verifying Paths'
[Environment]::SetEnvironmentVariable('ChocolateyInstall', 'c:\nuget', [System.EnvironmentVariableTarget]::User)
if ($($env:Path).ToLower().Contains('c:\nuget\bin') -eq $false) {
$env:Path = [Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::Machine);
}
Import-Module -Name 'c:\nuget\chocolateyInstall\helpers\chocolateyinstaller.psm1'
& C:\NuGet\chocolateyInstall\chocolatey.ps1 update
Add-Content $log -value 'Updated chocolatey to the latest version'
}
Add-Content $log -value "Installed Chocolatey"
cinst curl
#cloudinit.net
curl http://cloudinitnet.codeplex.com/releases/80468/download/335000 `-L `-d `'`' `-o cloudinit.zip
&7z e cloudinit.zip `-o`"c:\program files\CloudInit.NET`"
del cloudinit.zip
Add-Content $log -value 'Downloaded / extracted CloudInit.NET'
$configFile = 'c:\program files\cloudinit.net\install-service.ps1'
(Get-Content $configFile) | % { $_ -replace "3e3e2d3848336b7d3b547b2b55",$CloudInitEncryptionPassword } | Set-Content $configFile
cd 'c:\program files\cloudinit.net'
. .\install.ps1
Start-Service CloudInit
Add-Content $log -value "Updated config file with CloudInit encryption password and ran installation scrpit"
#this script will be fired off after the reboot
#http://www.codeproject.com/Articles/223002/Reboot-and-Resume-PowerShell-Script
@'
$log = 'c:\Bootstrap.txt'
$systemPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::System)
Remove-ItemProperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -name 'Restart-And-Resume'
&winrm quickconfig `-q
Add-Content $log -value "Ran quickconfig for winrm"
#run SMRemoting script to enable event log management, etc - available only on R2
$remotingScript = [IO.Path]::Combine($systemPath, 'Configure-SMRemoting.ps1')
if (-not (Test-Path $remotingScript)) { $remotingScript = [IO.Path]::Combine($sysNative, 'Configure-SMRemoting.ps1') }
Add-Content $log -value "Found Remoting Script: [$(Test-Path $remotingScript)] at $remotingScript"
if (Test-Path $remotingScript)
{
. $remotingScript -force -enable
Add-Content $log -value 'Ran Configure-SMRemoting.ps1'
}
#wait 15 seconds for CloudInit Service to start / fail
Start-Sleep -m 15000
#clear event log and any cloudinit logs
wevtutil el | % {Write-Host "Clearing $_"; wevtutil cl "$_"}
del 'c:\cloudinit.log' -ErrorAction SilentlyContinue
del 'c:\afterRebootScript.ps1' -ErrorAction SilentlyContinue
'@ | Set-Content 'c:\afterRebootScript.ps1'
Set-ItemProperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -name 'Restart-And-Resume' `
-value "$(Join-Path $env:windir 'system32\WindowsPowerShell\v1.0\powershell.exe') c:\afterRebootScript.ps1"
Write-Host "Press any key to reboot and finish image configuration"
[void]$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
Restart-Computer
|
PowerShellCorpus/GithubGist/DamianZaremba_d3905de95f6571d4f196_raw_16de971ef6d214c6bd55e2453958b0242996c1de_setup_mssql.ps1
|
DamianZaremba_d3905de95f6571d4f196_raw_16de971ef6d214c6bd55e2453958b0242996c1de_setup_mssql.ps1
|
$ErrorActionPreference = "Stop"
$client = new-object System.Net.WebClient
# Reset vagrant password so it's not expired
([adsi]"WinNT://vagrant-2012-r2/vagrant").SetPassword("P@55w0rd!")
# Setup UAC wrapper ;(
if(!(Test-Path -Path "C:\uacts_x64.zip")) {
Write-Output "Setting up UAC wrapper"
$client.DownloadFile("http://www.itknowledge24.com/files/uacts_x64.zip", "C:\uacts_x64.zip")
$shell = new-object -com shell.application
$zip = $shell.NameSpace("C:\uacts_x64.zip")
foreach($item in $zip.items())
{
$shell.Namespace("C:\").copyhere($item)
}
# Install
$p = [System.Diagnostics.Process]::Start('C:\setup.exe')
$p.WaitForExit()
}
# Disable the firewall
Write-Output "Disabling the firewall"
netsh advfirewall set allprofiles state off
# Install .NET
Write-Output "Installing .NET"
import-module servermanager
add-windowsfeature as-net-framework
# Download SQL server
if(!(Test-Path -Path "C:\SQLEXPR_x64_ENU.exe")) {
Write-Output "Downloading SQL server"
$client.DownloadFile("http://download.microsoft.com/download/8/D/D/8DD7BDBA-CEF7-4D8E-8C16-D9F69527F909/ENU/x64/SQLEXPR_x64_ENU.exe", "C:\SQLEXPR_x64_ENU.exe")
}
# Install SQL server
Write-Output "Installing SQL server"
# This crap is to work around UAC and no admin rights authing via ssh key
$service = new-object -ComObject("Schedule.Service")
$service.Connect()
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = "Install SQL server"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$triggers = $TaskDefinition.Triggers
$trigger = $triggers.Create(1)
$trigger.StartBoundary = [datetime]::Now.AddMinutes(0.5).ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.Enabled = $true
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = 'C:\SQLEXPR_x64_ENU.exe'
$action.Arguments = '/Q /IACCEPTSQLSERVERLICENSETERMS /HIDECONSOLE /ENU /ACTION=INSTALL /FEATURES=SQL,Tools /INSTANCENAME=SQLEXPRESS /INDICATEPROGRESS /SQLCOLLATION=Latin1_General_BIN /SQLSVCSTARTUPTYPE=Automatic /SQLSVCACCOUNT="NT AUTHORITY\SYSTEM" /SQLSYSADMINACCOUNTS="BUILTIN\ADMINISTRATORS" /TCPENABLED=1 /SECURITYMODE="SQL" /SAPWD="P@55w0rd!" /UpdateEnabled="false"'
$rootFolder = $service.GetFolder("\")
$rootFolder.RegisterTaskDefinition("Install SQL server",$TaskDefinition,6,"System",$null,5)
# Wait for SQL server install to finish
while ($true) {
if (Get-Service 'MSSQL$SQLEXPRESS' -ErrorAction SilentlyContinue | Where-Object {$_.status -eq "running"}) {
break
}
# Wait 10 seconds
Write-Output "Waiting for SQL server install to finish...."
Start-Sleep -s 10
}
# Wait to make sure everything is in place
Start-Sleep -s 10
Write-Output "SQL server install finished, setting up port"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null
$MachineObject = new-object ('Microsoft.SqlServer.Management.Smo.WMI.ManagedComputer') .
$ProtocolUri = "ManagedComputer[@Name='" + (get-item env:\computername).Value + "']/ServerInstance[@Name='SQLEXPRESS']/ServerProtocol"
$tcp = $MachineObject.getsmoobject($ProtocolUri + "[@Name='Tcp']")
$tcp.IsEnabled = $true
$tcp.alter()
Start-Sleep -s 2
restart-service -f "SQL Server (SQLEXPRESS)"
Write-Output "Done!"
|
PowerShellCorpus/GithubGist/wschwarz_5073004_raw_eeb6557fb79e8c39e49715826c418ba1fafbf705_xslt-transform.ps1
|
wschwarz_5073004_raw_eeb6557fb79e8c39e49715826c418ba1fafbf705_xslt-transform.ps1
|
function process-XSLT
{param([string]$a)
$xsl = "C:\path_to_xslt\CleanUp.xslt"
$inputstream = new-object System.IO.MemoryStream
$xmlvar = new-object System.IO.StreamWriter($inputstream)
$xmlvar.Write("$a")
$xmlvar.Flush()
$inputstream.position = 0
$xml = new-object System.Xml.XmlTextReader($inputstream)
$output = New-Object System.IO.MemoryStream
$xslt = New-Object System.Xml.Xsl.XslCompiledTransform
$arglist = new-object System.Xml.Xsl.XsltArgumentList
$reader = new-object System.IO.StreamReader($output)
$xslt.Load($xsl)
$xslt.Transform($xml, $arglist, $output)
$output.position = 0
$transformed = [string]$reader.ReadToEnd()
$reader.Close()
return $transformed
}
|
PowerShellCorpus/GithubGist/fearthecowboy_c214e02ae59f9b3fbede_raw_ff712075b7eeea5368edec7ee20aa118601e40f5_associate-powershell.ps1
|
fearthecowboy_c214e02ae59f9b3fbede_raw_ff712075b7eeea5368edec7ee20aa118601e40f5_associate-powershell.ps1
|
#==============================================================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#==============================================================================
#==============================================================================
#
# This script makes it so you can execute .ps1 scripts either by double clicking
# or anywhere you can run an command (ie, from cmd.exe command line, or the
# WinKey-R Run Dialog)
#
# WARNING: There is a reason that this is not the default in Windows. This
# certainly would make it simpler to accidentally run a script when you expected
# something else.
#
# I Like this because it makes it easier for me to use my system like I always
# have; I make a lot of scripts to automate so much, and I don't always run from
# the powershell prompt; I use cmd.exe for a lot of stuff too.
#
#==============================================================================
# Ensure this script is elevated.
#==============================================================================
If (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Start-Process -wait -FilePath PowerShell.exe -windowstyle hidden -Verb Runas -WorkingDirectory (pwd) -ArgumentList $(@($MyInvocation.Line.Replace($MyInvocation.InvocationName, $MyInvocation.MyCommand.Definition) ,"$($MyInvocation.InvocationName) $args")[$MyInvocation.MyCommand.Definition -ne ""]) ; return
}
# Set the open command for .ps1 files to execute via powershell.exe
#==============================================================================
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
Set-ItemProperty -Path "HKCR:\Microsoft.PowerShellScript.1\Shell\open\command" -name '(Default)' -Value '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1" %*'
# Ensure that .ps1 is in the ExtPath (for calling via cmd.exe)
#==============================================================================
function Append-ToEnvironment{ param( [string] $var, [string] $value, [System.EnvironmentVariableTarget]$Context = "System" )
[System.Environment]::SetEnvironmentVariable( $var, (("$([System.Environment]::GetEnvironmentVariable($var, $context))".Split(';',[StringSplitOptions]'RemoveEmptyEntries') + $val | select -uniq ) -join ';') , $context )
}
Append-ToEnvironment "PATHEXT", ".ps1"
|
PowerShellCorpus/GithubGist/scott-kloud_d42dc0d6d0d32534bea4_raw_df082cafbbe82828d93ef11513d842a8c6b5ae4e_Migrate-AzureVM.ps1
|
scott-kloud_d42dc0d6d0d32534bea4_raw_df082cafbbe82828d93ef11513d842a8c6b5ae4e_Migrate-AzureVM.ps1
|
<#
.SYNOPSIS
Migrates a Azure Virtual Machine to another subscription or data centre
.DESCRIPTION
Shutsdown the source VM
Exports the VM config to a temporary file
Loops through all Azure disks attached to the source VM
Schedules an async copy of the underlying VHD to the destination storage account
- optionally overwrites existing VHD in destination if it exists
Waits for all copy jobs to complete
Adds Azure disks in the destination subscription for every disk copied
- optionally removes the existing Azure Disk if it exists
Restores VM in the destination cloud service
Starts the migrated VM
.NOTES
File Name : Migrate-AzureVM.ps1
Requires : Windows Azure Cmdlets Snapin v8.7.1 or greater
Author : Scott Scovell
Version : 1.0 - 07/11/2014 - Scott Scovell - Created script
Assumptions:
- Azure Service Management certificates are installed on the machine running the script
- Azure Subscription profiles have been created on the machine running the script (use Get-AzureSubscription to check)
- Destination storage accounts, cloud services, vnets, etc already exist
Constraints:
- No support for internal load balanced endpoints. Will fail if ILB instance not found
.EXAMPLE
.\Migrate-AzureVM.ps1 -SourceSubscription "MySub" -SourceServiceName "MyCloudService" -VMName "MyVM" `
-DestSubscription "MyOtherSub" -DestStorageAccountName "mydeststorage" -DestServiceName "MyDestCloudService" -DestVNETName "MyRegionalVNet" `
-IsReadOnlySecondary $false -Overwrite $false -RemoveDestAzureDisk $false
#>
param
(
# Name of the source Azure subscription
[string] $SourceSubscription = "MySub",
# Name of the source cloud service
[string] $SourceServiceName = "MyCloudService",
# Name of the VM to migrate
[string] $VMName = "MyVM",
# Name of the destination Azure subscription
[string] $DestSubscription = "MyOtherSub",
# Name of the destination storage account
[string] $DestStorageAccountName = "mydeststorage",
# Name of the destination cloud service
[string] $DestServiceName = "MyDestCloudService",
# Name of the destination VNET - blank if none used
[string] $DestVNETName = "MyRegionalVNet",
# Indicates if we are copying from the source storage accounts read-only secondary location
[switch] $IsReadOnlySecondary = $false,
# Indicates if we are overwriting if the VHD already exists
[switch] $Overwrite = $false,
# Indicates if we remove an Azure Disk if it already exists in the destination repository
[switch] $RemoveDestAzureDisk = $false
)
#region === Runtime Configuration ===========================================
# Script Path/Directories
$ScriptPath = (Split-Path ((Get-Variable MyInvocation).Value).MyCommand.Path)
# Date Format
$DateFormat = Get-Date -Format "yyyyMMdd_HHmmss"
# Zero out errors
$Error.Clear()
# Define collections to keep track of async operations
$copyTasks = @()
# Define storage account context collection so we can reuse these
$storageContexts = @{}
# Show verbose output
$VerbosePreference = "Continue"
# Define Stop/Start Instance Status values
$StoppedStatus = "StoppedDeallocated"
$StartedStatus = "ReadyRole"
#endregion configuration
#region === Functions =======================================================
<#
.SYNOPSIS
Write to output including a timestamp and computer name
.EXAMPLE
Write-Log "message"
.OUTPUTS
None
#>
function Write-Log
{
param
(
[string] $Message,
[switch] $IsError = $false
)
if($IsError)
{
Write-Error "$([DateTime]::Now.ToLongTimeString()) - $Message"
}
else
{
Write-Verbose "$([DateTime]::Now.ToLongTimeString()) - $Message"
}
}
<#
.SYNOPSIS
Stops the specified VM and waits until the instance enters the stopped state
.DESCRIPTION
Checks the state of the VM instance
Stops the VM
Loops until the state of the VM equals the stopped state
.EXAMPLE
Stop-AzureVMAndWait -ServiceName "MyCloudService" -VMName "MyVMName"
.OUTPUTS
None
#>
function Stop-AzureVMAndWait
{
param
(
# Name of the service hosting the VM
[Parameter(Mandatory = $true)]
[String]
$ServiceName,
# Name of the VM
[Parameter(Mandatory = $true)]
[String]
$VMName
)
Write-Log "Checking current VM state..."
# Gather current status of the VM
$vmStatus = Get-AzureVM -ServiceName $ServiceName -Name $VMName
# Check if VM exists
if ($vmStatus -eq $null) {
Write-Log "$VMName is not been provisioned"
return
}
# Attempt to stop VM
if ($vmStatus.InstanceStatus -ne $StoppedStatus) {
Write-Log "Stopping $VMName..."
# Stop VM
foreach($retry in (1..3)) {
Stop-AzureVM -ServiceName $ServiceName -Name $VMName -Force -Verbose -ErrorVariable lastError -ErrorAction SilentlyContinue | Out-Null
if ($?) { break } # Success
else {
# Failure
if ($retry -eq 3) {
Write-Log "$VMName failed to stop after $retry retires"
return
}
# Wait
Sleep -Seconds 3
}
}
# Wait for VM to shutdown
$vmStatus = Get-AzureVM -ServiceName $ServiceName -Name $VMName
While ($vmStatus.InstanceStatus -ne $StoppedStatus)
{
# Take a break
Write-Log "Waiting for VM to enter $StoppedStatus state... Current Status: $($vmStatus.InstanceStatus)"
Start-Sleep -Seconds 15
# Gather current status
$vmStatus = Get-AzureVM -ServiceName $ServiceName -Name $VMName
}
}
Write-Log "$VMName is in the $StoppedStatus state"
}
<#
.SYNOPSIS
Starts the specified VM and waits until the instance enters the ready state
.DESCRIPTION
Checks the state of the VM instance
Starts the VM
Loops until the state of the VM equals the ready state
.EXAMPLE
Stop-AzureVMAndWait -ServiceName "MyCloudService" -VMName "MyVMName"
.OUTPUTS
None
#>
function Start-AzureVMAndWait
{
param
(
# Name of the service hosting the VM
[Parameter(Mandatory = $true)]
[String]
$ServiceName,
# Name of the VM
[Parameter(Mandatory = $true)]
[String]
$VMName
)
Write-Log "Checking current VM state..."
# Gather current status of the VM
$vmStatus = Get-AzureVM -ServiceName $ServiceName -Name $VMName
# Check if VM exists
if ($vmStatus -eq $null) {
Write-Log "$VMName is not been provisioned"
return
}
# Attempt to stop VM
if ($vmStatus.InstanceStatus -ne $StoppedStatus) {
Write-Log "Starting $VMName..."
# Stop VM
foreach($retry in (1..3)) {
Start-AzureVM -ServiceName $ServiceName -Name $VMName -Verbose -ErrorVariable lastError -ErrorAction SilentlyContinue | Out-Null
if ($?) { break } # Success
else {
# Failure
if ($retry -eq 3) {
Write-Log "$VMName failed to start after $retry retires"
return
}
# Wait
Sleep -Seconds 3
}
}
# Wait for VM to shutdown
$vmStatus = Get-AzureVM -ServiceName $ServiceName -Name $VMName
While ($vmStatus.InstanceStatus -ne $StartedStatus)
{
# Take a break
Write-Log "Waiting for VM to enter $StartedStatus state... Current Status: $($vmStatus.InstanceStatus)"
Start-Sleep -Seconds 15
# Gather current status
$vmStatus = Get-AzureVM -ServiceName $ServiceName -Name $VMName
}
}
Write-Log "$VMName is in the $StartedStatus state"
}
<#
.SYNOPSIS
Returns a reference to the storage account context
.EXAMPLE
Get-AzureStorageContext -SubscriptionName "MySub" -StorageAccountName "mystorage"
.OUTPUTS
[AzureStorageContext]
#>
function Get-AzureStorageContext
{
param
(
[string] $SubscriptionName,
[string] $StorageAccountName
)
# Set subscription context
Select-AzureSubscription -SubscriptionName $SubscriptionName -Current
# Check our collection if we have already generated a storage context for this account
$context = $storageContexts[$StorageAccountName]
if ($context -eq $null)
{
# Generate context for this storage account
$storageAccountKey = (Get-AzureStorageKey -StorageAccountName $StorageAccountName).Primary
$context = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $storageAccountKey
# Add context to collection for next time
$storageContexts[$StorageAccountName] = $context
}
return $context
}
<#
.SYNOPSIS
Start the async copy of the underlying VHD to the corresponding destination storage account
.EXAMPLE
Copy-AzureDiskAsync -SourceDisk $disk
.OUTPUTS
None
#>
function Copy-AzureDiskAsync
{
param
(
# Reference to source Azure disk to copy
[Parameter(Mandatory = $true)]
$SourceDisk
)
# Gather container and blob details from the source disk
$container = ($SourceDisk.MediaLink.Segments[1]).Replace("/","")
$blobName = $SourceDisk.MediaLink.Segments | Where-Object { $_ -like "*.vhd" }
$sourceUri = $SourceDisk.MediaLink.AbsoluteUri
# Gather storage account details.
$srcStorageAccount = $SourceDisk.MediaLink.Host.Replace(".blob.core.windows.net", "")
$destStorageAccount = $DestStorageAccountName.ToLower()
Write-Log "Preparing to copy source disk $($SourceDisk.DiskName) to $destStorageAccount..."
# Get storage contexts for source and destination
$srcContext = Get-AzureStorageContext -SubscriptionName $SourceSubscription -StorageAccountName $srcStorageAccount
$destContext = Get-AzureStorageContext -SubscriptionName $DestSubscription -StorageAccountName $destStorageAccount
# [BUG: For some reason after we get the destination context we end up with an array of context instead. !?!]
$srcContext = $storageContexts[$srcStorageAccount]
$destContext = $storageContexts[$destStorageAccount]
if ($srcContext -eq $null -or $destContext -eq $null)
{
if ($srcContext -eq $null) { Write-Log "Could not access source storage account $srcStorageAccount" -IsError }
if ($destContext -eq $null) { Write-Log "Could not access destination storage account $destStorageAccount" -IsError }
throw "Failed to create storage contexts for storage accounts"
}
# Create destination container if it doesnt already exist
if ((Get-AzureStorageContainer -Name $container -Context $destContext -ErrorAction SilentlyContinue) -eq $null)
{
Write-Log "Creating container $container in destination storage account..."
New-AzureStorageContainer -Name $container -Context $destContext
}
# Check if the VHD already exists in the destination container
$blob = Get-AzureStorageBlob -Container $container -Blob $blobName -Context $destContext -ErrorAction SilentlyContinue
if ($blob -ne $null -and $Overwrite -eq $false)
{
throw "A blob with the name $blobName already exists in the destination storage account"
}
Write-Log "Scheduling the async copy of source disk $($SourceDisk.DiskName) to $destStorageAccount..."
# [SS: Check if we are copying from a RA-GRS secondary storage account]
if ($IsReadOnlySecondary -eq $true)
{
# Append "-secondary" to the media location URI to reference the RA-GRS copy
$sourceUri = $sourceUri.Replace($srcStorageAccount, "$srcStorageAccount-secondary")
}
# [SS: Need to be in the source subscription context for the copy operation to work correctly]
# Set context to source subscription
Select-AzureSubscription -SubscriptionName $SourceSubscription -Current
# Schedule a blob copy operation of the source disk to the destination storage account
if ($Overwrite -eq $true)
{
# Use the Force flag to overwrite destination blob if it exists
$copyTask = Start-AzureStorageBlobCopy -Context $srcContext -SrcUri $sourceUri `
-DestContext $destContext -DestContainer $container -DestBlob $blobName `
-Force `
-ErrorAction SilentlyContinue -ErrorVariable LastError
}
else
{
# Without the force flag
$copyTask = Start-AzureStorageBlobCopy -Context $srcContext -SrcUri $sourceUri `
-DestContext $destContext -DestContainer $container -DestBlob $blobName `
-ErrorAction SilentlyContinue -ErrorVariable LastError
}
# Check if the copy task was created successfully
if ($copyTask -eq $null)
{
throw "Failed to schedule async copy task of blob: $blob to storage account: $destStorageAccount. Details: $LastError"
}
Write-Log "Copy of source disk $($SourceDisk.DiskName) to $destStorageAccount has been scheduled successfully"
return $copyTask
}
<#
.SYNOPSIS
Monitor async copy tasks and wait for all to complete
.EXAMPLE
WaitAll-AsyncCopyJobs
.OUTPUTS
None
#>
function WaitAll-AsyncCopyJobs
{
# Monitor async tasks and wait for all to complete
$delaySeconds = 10
Write-Log "Checking storage copy job status every $delaySeconds seconds."
do
{
$continue = $false
$progressId = 1
foreach ($copyTask in $copyTasks)
{
# [SS: For some reason we get some non blob copy tasks in the collection so we need to filter these out]
# Check the copy state for the blob
if ($copyTask.ICloudBlob -ne $null)
{
$copyState = $copyTask | Get-AzureStorageBlobCopyState
$copyStatus = $copyState.Status
# Display progress
Write-Progress -Id $progressId -Activity "Copying..." -PercentComplete (($copyState.BytesCopied/$copyState.TotalBytes)*100) -CurrentOperation $copyTask.Name -Status $copyState.Status
}
else { $copyStatus = [Microsoft.WindowsAzure.Storage.Blob.CopyStatus]::Invalid }
# Continue checking status as long as at least one operations is still pending
if ($copyStatus -eq [Microsoft.WindowsAzure.Storage.Blob.CopyStatus]::Pending ) { $continue = $true }
$progressId += 1
}
# Pause if we are checking again
if ($continue) { Start-Sleep -Seconds $delaySeconds }
} while ($continue)
Write-Log "All async tasks have completed. Check output for failures."
# Display final state
$copyTasks | Get-AzureStorageBlobCopyState | Format-Table -AutoSize -Property Status,BytesCopied,TotalBytes,Source
}
#endregion Functions
#region === Script Execution ================================================
try
{
#
#region - Shutdown and Export VM configuration
#
# Set source subscription context
Select-AzureSubscription -SubscriptionName $SourceSubscription -Current
# Stop VM
Stop-AzureVMAndWait -ServiceName $SourceServiceName -VMName $VMName
# Export VM config to temporary file
$exportPath = "{0}\{1}-{2}-State.xml" -f $ScriptPath, $SourceServiceName, $VMName
Export-AzureVM -ServiceName $SourceServiceName -Name $VMName -Path $exportPath
if (-not(Test-Path $exportPath))
{
throw "Failed to export VM state. Aborting..."
}
#endregion
#
#
#region - Copy all attached VHDs to destination storage using async copy jobs
#
# Get list of azure disks that are currently attached to the VM
$disks = Get-AzureDisk | ? { $_.AttachedTo.RoleName -eq $VMName }
# Loop through each disk
foreach($disk in $disks)
{
try
{
# Start the async copy of the underlying VHD to the corresponding destination storage account
$copyTasks += Copy-AzureDiskAsync -SourceDisk $disk
}
catch {} # Support for existing VHD in destination storage account
}
# Monitor async copy tasks and wait for all to complete
WaitAll-AsyncCopyJobs
#endregion
#
#
#region - Re-construct OS and Data disks
#
# Set destination subscription context
Select-AzureSubscription -SubscriptionName $DestSubscription -Current
# Load VM config
$vmConfig = Import-AzureVM -Path $exportPath
# Loop through each disk again
$diskNum = 0
foreach($disk in $disks)
{
# Construct new Azure disk name as [DestServiceName]-[VMName]-[Index]
$destDiskName = "{0}-{1}-{2}" -f $DestServiceName,$VMName,$diskNum
Write-Log "Checking if $destDiskName exists..."
# Check if an Azure Disk already exists in the destination subscription
$azureDisk = Get-AzureDisk -DiskName $destDiskName -ErrorAction SilentlyContinue -ErrorVariable LastError
if ($azureDisk -ne $null)
{
Write-Log "$destDiskName already exists"
if ($RemoveDisk -eq $true)
{
# Remove the disk from the repository
Remove-AzureDisk -DiskName $destDiskName
Write-Log "Removed AzureDisk $destDiskName"
$azureDisk = $null
}
# else keep the disk and continue
}
# Determine media location
$container = ($disk.MediaLink.Segments[1]).Replace("/","")
$blobName = $disk.MediaLink.Segments | Where-Object { $_ -like "*.vhd" }
$destMediaLocation = "http://{0}.blob.core.windows.net/{1}/{2}" -f $DestStorageAccountName,$container,$blobName
# Attempt to add the azure OS or data disk
if ($disk.OS -ne $null -and $disk.OS.Length -ne 0)
{
# OS disk
if ($azureDisk -eq $null)
{
$azureDisk = Add-AzureDisk -DiskName $destDiskName -MediaLocation $destMediaLocation -Label $destDiskName -OS $disk.OS -ErrorAction SilentlyContinue -ErrorVariable LastError
}
# Update VM config
$vmConfig.OSVirtualHardDisk.DiskName = $azureDisk.DiskName
}
else
{
# Data disk
if ($azureDisk -eq $null)
{
$azureDisk = Add-AzureDisk -DiskName $destDiskName -MediaLocation $destMediaLocation -Label $destDiskName -ErrorAction SilentlyContinue -ErrorVariable LastError
}
# Update VM config
# Match on source disk name and update with dest disk name
$vmConfig.DataVirtualHardDisks.DataVirtualHardDisk | ? { $_.DiskName -eq $disk.DiskName } | ForEach-Object {
$_.DiskName = $azureDisk.DiskName
}
}
# Next disk number
$diskNum = $diskNum + 1
}
#endregion
#
#
#region - Restore VM in destination cloud service
#
Write-Log "Restoring $VMName to $DestServiceName..."
# Restore VM
$existingVMs = Get-AzureService -ServiceName $DestServiceName | Get-AzureVM
if ($existingVMs -eq $null -and $DestVNETName.Length -gt 0)
{
# Restore first VM to the cloud service specifying VNet
$vmConfig | New-AzureVM -ServiceName $DestServiceName -VNetName $DestVNETName -WaitForBoot
}
else
{
# Restore VM to the cloud service
$vmConfig | New-AzureVM -ServiceName $DestServiceName -WaitForBoot
}
# Startup VM
Start-AzureVMAndWait -ServiceName $DestServiceName -VMName $VMName
#endregion
#
}
catch
{
Write-Log "Exception caught while migrating $VMName. Details: $Error"
}
#endregion Script Execution
|
PowerShellCorpus/GithubGist/kyam_9972571_raw_05cd9403b70a5fc03a425f82280174ccc8253766_gistfile1.ps1
|
kyam_9972571_raw_05cd9403b70a5fc03a425f82280174ccc8253766_gistfile1.ps1
|
#
# HKEY_CLASSES_ROOT 2147483648
# HKEY_CURRENT_USER 2147483649
# HKEY_LOCAL_MACHINE 2147483650
# HKEY_USERS 2147483651
# HKEY_CURRENT_CONFIG 2147483653
# HKEY_DYN_DATA 2147483654
#
#
$loc = Get-Location
$dir = $loc.Path
$csvfile = $dir + "\" + $Args[0]
$outputfile = $dir + "\" + $Args[1]
function ConvertLocalTime($time)
{
$d = [DateTime]::Parse($time)
$lt = $d.ToLocalTime()
return $lt.ToString()
}
function OutputTitle
{
$title = "Name,DetectError,DetectLastTime,DownloadError,DownloadLastTime,InstallError,InstallLastTime"
Write-Output $title | Add-Content -Encoding UTF8 $outputfile
Write-Host $title
}
function GetUpdateRegistry($computer, $key)
{
$hklm = 2147483650
$wup_regpath = "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results"
$regpath = $wup_regpath + "\" + $key
$wmipath = "\\" + $computer + "\root\default:stdRegProv"
$wmi = [wmiclass]$wmipath
$LastError = ($wmi.GetDWORDValue($hklm,$regpath,"LastError")).uValue
$LastSuccessTime = ($wmi.GetStringValue($hklm,$regpath,"LastSuccessTime")).svalue
return New-Object psobject -property @{
LastError=$LastError;
LastSuccessTime=$LastSuccessTime;
}
}
function BuildRecord($computer, $detect, $download, $install)
{
$record = $computer + ","
if (($detect.LastError -ne $null) -and ($detect.LastSuccessTime -ne $null)) {
$record += $detect.LastError.ToString("X") + "," + (ConvertLocalTime($detect.LastSuccessTime)) + ","
} else {
$record += ",,"
}
if (($download.LastError -ne $null) -and ($download.LastSuccessTime -ne $null)) {
$record += $download.LastError.ToString("X") + "," + (ConvertLocalTime($download.LastSuccessTime)) + ","
} else {
$record += ",,"
}
if (($install.LastError -ne $null) -and ($install.LastSuccessTime -ne $null)) {
$record += $install.LastError.ToString("X") + "," + (ConvertLocalTime($install.LastSuccessTime)) + ","
} else {
$record += ",,"
}
return $record
}
function BuildNoResponseRecord ($computer) {
$record = "$computer,,,,,,,"
return $record
}
function GetCurrentPCRegistry ($plist) {
$wup_regpath = "hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results"
$wup_detect_path = $wup_regpath + "\Detect"
$wup_download_path = $wup_regpath + "\Download"
$wup_install_path = $wup_regpath + "\Install"
foreach ($pc in $plist) {
$wup_detect = Get-ItemProperty -Path $wup_detect_path
$wup_download = Get-ItemProperty -Path $wup_download_path
$wup_install = Get-ItemProperty -Path $wup_install_path
$record = $pc.Name + "," +
$wup_detect.LastError + "," + (ConvertLocalTime($wup_detect.LastSuccessTime)) + "," +
$wup_download.LastError + "," + (ConvertLocalTime($wup_download.LastSuccessTime)) + "," +
$wup_install.LastError + "," + (ConvertLocalTime($wup_install.LastSuccessTime))
Write-Output $record | Add-Content -Encoding UTF8 $outputfile
Write-Host $record
}
}
function GetPCRegistry ($computer) {
$pcreg = @{}
$wup_regpath = "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results"
$pcreg.Detect = GetUpdateRegistry $computer "Detect"
$pcreg.Download = GetUpdateRegistry $computer "Download"
$pcreg.Install = GetUpdateRegistry $computer "Install"
return $pcreg
}
function ProcessPc ($pc_list)
{
foreach ($pc in $pc_list) {
$record = $null
$result = Test-Connection -ComputerName $pc.Name -Quiet
if ($result) {
$reg = GetPCRegistry $pc.Name
$record = BuildRecord $pc.Name $reg.Detect $reg.Download $reg.Install
} else {
$record = BuildNoResponseRecord $pc.Name
}
Write-Output $record | Add-Content -Encoding UTF8 $outputfile
Write-Host $record
}
}
$pclist = Import-Csv $csvfile
OutputTitle
ProcessPc $pclist
|
PowerShellCorpus/GithubGist/thorade_0808b5fd73becf3a35b6_raw_7e742e56f154513b1ec448e814ad36462d4c10f2_remove_bakmo.ps1
|
thorade_0808b5fd73becf3a35b6_raw_7e742e56f154513b1ec448e814ad36462d4c10f2_remove_bakmo.ps1
|
# This Windows PowerShell script
# recursively deletes Dymola *.bak-mo backup files
# from all folders below itself
# get current directory
$curDir = Split-Path -Parent $MyInvocation.MyCommand.Path
# delete files
get-childitem $curDir -include *.bak-mo -recurse | foreach ($_) {remove-item $_.fullname}
|
PowerShellCorpus/GithubGist/willbar_9266405_raw_d0b41134e18c4a0b2e71741e9031fc724d243129_MachineSetup.ps1
|
willbar_9266405_raw_d0b41134e18c4a0b2e71741e9031fc724d243129_MachineSetup.ps1
|
Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions
Enable-RemoteDesktop
cinst sublimetext3
cinst git
cinst git-credential-winstore
cinst poshgit
cinst NuGet.CommandLine
cinst NuGetPackageExplorer
cinst pscx
cinst ScriptCs
cinst sysinternals
cinst fiddler4
|
PowerShellCorpus/GithubGist/toddb_1133509_raw_cb725dae031784cec91843a28bd9347354896b7e_test-tasks.ps1
|
toddb_1133509_raw_cb725dae031784cec91843a28bd9347354896b7e_test-tasks.ps1
|
<#
Usage for Gallio tests:
Task Test-System -Description "Runs the system tests via Gallio" {
Test-Gallio $proj $configuration $platform $dll "system" "Test.System"
# Test-Gallio ".\src\Test.Unit\Test.Unit.csproj" Release x64 ".\src\Test.Unit\bin\Release\x64\Test.Unit.dll" "unit"
}
}
#>
function Test-Gallio($proj, $configuration, $platform, $dll, $report_name, $namespace_filter){
Add-PSSnapIn Gallio
exec { msbuild $proj "/p:Configuration=$configuration" "/p:Platform=$platform" }
$result = Run-Gallio $dll -filter Namespace:/$namespace_filter/ -ReportTypes text,html -ReportNameFormat $report_name-test-report
$report_dir = resolve-path .
get-content "$report_dir\Reports\$report_name-test-report.txt" | Write-Host
Write-Host $result.ResultsSummary
if ($result.Statistics.FailedCount -gt 0) {
Write-Warning "Some unit tests have failed."
$Error = $result.ResultsSummary
exit $result.ResultCode
}
}
|
PowerShellCorpus/GithubGist/weipah_2506769_raw_0e386ce799a041707e330d8e5921c7efb48d9131_XADGroupCopy.ps1
|
weipah_2506769_raw_0e386ce799a041707e330d8e5921c7efb48d9131_XADGroupCopy.ps1
|
function XADGroupCopy() {
param(
[parameter(Mandatory=$true,Position=0,HelpMessage="Von welchem User sollen Berechtigungen kopiert werden?")]
[String]
$fromUser,
[parameter(Mandatory=$true,Position=1,HelpMessage="Welcher User erhaelt die neuen Gruppen?")]
[String]
$toUser
)
$antwort = read-host "Sind Sie sicher? $fromUser --> $toUser (ja/nein)?"
if ($antwort -eq "ja") {
$UserGroups = Get-ADUser –Identity $fromUser -Properties memberOf | Select-Object -ExpandProperty memberOf
# check if Groups are Found
$UserGroups | % {
# Add User to each Group
Add-ADGroupMember -Identity "$($_)" -Members $toUser -ErrorAction SilentlyContinue
}
}
else {
write-host "Abbruch: Es wurden keine Gruppen kopiert!"
}
}
|
PowerShellCorpus/GithubGist/jincod_03ed02181c83faf93081_raw_e8ed03a6c823f1cdf6b597d528eff62119cacc3c_changes.ps1
|
jincod_03ed02181c83faf93081_raw_e8ed03a6c823f1cdf6b597d528eff62119cacc3c_changes.ps1
|
$buildId = 10048
$teamcityUrl = "http://teamcity:8080"
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("username:password"))
@((Invoke-RestMethod $teamcityUrl/httpAuth/app/rest/changes?build=id:$buildId -Headers @{"Authorization" = "Basic $auth"}).changes.change) | % { (Invoke-RestMethod $teamcityUrl/httpAuth/app/rest/changes/id:$($_.id) -Headers @{"Authorization" = "Basic $auth"}).change.comment}
|
PowerShellCorpus/GithubGist/xcud_4955455_raw_8e2e62bbbebe86311c0556ea2254f4718981299f_Get-Content.ps1
|
xcud_4955455_raw_8e2e62bbbebe86311c0556ea2254f4718981299f_Get-Content.ps1
|
<#
.Synopsis
Extend Get-Content to include a -Fast parameter; much less flexible but more performant
.Example
PS> (Measure-Command { Get-Content .\data.xml} ).TotalMilliseconds
1609.3267
PS> (Measure-Command { Get-Content .\data.xml -Fast} ).TotalMilliseconds
39.2511
#>
function Get-Content {
[CmdletBinding(DefaultParameterSetName='Path', SupportsTransactions=$true, HelpUri='http://go.microsoft.com/fwlink/?LinkID=113310')]
param(
[Parameter(ValueFromPipelineByPropertyName=$true)]
[long]
${ReadCount},
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias('First','Head')]
[long]
${TotalCount},
[Parameter(ValueFromPipelineByPropertyName=$true)]
[Alias('Last')]
[int]
${Tail},
[Parameter(ParameterSetName='Path', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)]
[string[]]
${Path},
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath')]
[string[]]
${LiteralPath},
[string]
${Filter},
[string[]]
${Include},
[string[]]
${Exclude},
[switch]
${Force},
[Parameter(ValueFromPipelineByPropertyName=$true)]
[pscredential]
${Credential},
[switch]
${Fast}
)
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-Content', [System.Management.Automation.CommandTypes]::Cmdlet)
if($PSBoundParameters['Fast'])
{
$scriptCmd = {& Invoke-Command { [System.IO.File]::ReadAllText($PSBoundParameters['Path']) } }
}
else
{
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
}
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Get-Content
.ForwardHelpCategory Cmdlet
#>
}
|
PowerShellCorpus/GithubGist/mwjcomputing_4717642_raw_a936466520dda8f7cf58b515c4a42ddba453cf20_Get-DaysUntilBSidesDetroit.ps1
|
mwjcomputing_4717642_raw_a936466520dda8f7cf58b515c4a42ddba453cf20_Get-DaysUntilBSidesDetroit.ps1
|
function Get-DaysUntilBSidesDetroit {
Write-Host "There are $((New-Timespan -end '6/7/2013 9:00:00AM').Days) days until BSidesDetroit."
}
|
PowerShellCorpus/GithubGist/william-gross_77fd0fdc9e3ce03f093f_raw_8b0e6339696280f7e4563da52aa443821a10449f_hasync.ps1
|
william-gross_77fd0fdc9e3ce03f093f_raw_8b0e6339696280f7e4563da52aa443821a10449f_hasync.ps1
|
cd humanizer-annotations
git pull https://enduracode.kilnhg.com/Code/Ewl/ReSharperAnnotations/Humanizer.git
git push origin
|
PowerShellCorpus/GithubGist/NotMyself_e310fc01b941491fcd89_raw_e3fefeda5ef3b32064555a1e696c35b8ecb71272_gistfile1.ps1
|
NotMyself_e310fc01b941491fcd89_raw_e3fefeda5ef3b32064555a1e696c35b8ecb71272_gistfile1.ps1
|
task Run-Site -depends Clean, MsBuild-Release {
$iisexpress = "$env:ProgramFiles\IIS Express\iisexpress.exe"
start $iisexpress @("/port:8080 /path:$workPath\_PublishedWebsites\UIWeb")
}
|
PowerShellCorpus/GithubGist/biacz_f4ec5140d75d708d413d_raw_5f0de8b55a6d94df24ebd2f429880bae6e8ca280_gistfile1.ps1
|
biacz_f4ec5140d75d708d413d_raw_5f0de8b55a6d94df24ebd2f429880bae6e8ca280_gistfile1.ps1
|
# Variables, Functions and Data Collection
$DaysData = "7"
$ErrorActionPreference = "Stop"
$MyReport = @()
$Creds = Get-Credential
$HTMLHeader = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html><head><title>My Systems Report</title>
<style type="text/css">
<!--
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}
#report { width: 835px; }
table{
border-collapse: collapse;
border: none;
font: 10pt Verdana, Geneva, Arial, Helvetica, sans-serif;
color: black;
margin-bottom: 10px;
}
table td{
font-size: 12px;
padding-left: 0px;
padding-right: 20px;
text-align: left;
}
table th {
font-size: 12px;
font-weight: bold;
padding-left: 0px;
padding-right: 20px;
text-align: left;
}
h2{ clear: both; font-size: 130%; }
h3{
clear: both;
font-size: 115%;
margin-left: 20px;
margin-top: 30px;
}
p{ margin-left: 20px; font-size: 12px; }
table.list{ float: left; }
table.list td:nth-child(1){
font-weight: bold;
border-right: 1px grey solid;
text-align: right;
}
table.list td:nth-child(2){ padding-left: 7px; }
table tr:nth-child(even) td:nth-child(even){ background: #CCCCCC; }
table tr:nth-child(odd) td:nth-child(odd){ background: #F2F2F2; }
table tr:nth-child(even) td:nth-child(odd){ background: #DDDDDD; }
table tr:nth-child(odd) td:nth-child(even){ background: #E5E5E5; }
div.column { width: 320px; float: left; }
div.first{ padding-right: 20px; border-right: 1px grey solid; }
div.second{ margin-left: 30px; }
table{ margin-left: 20px; }
-->
</style>
</head>
<body>
"@
$HTMLEnd = @"
</div><hr noshade size=3 width="100%"></body></html>
"@
foreach ($VIServer in $VIServers) {
if (!(get-pssnapin -name VMware.VimAutomation.Core -erroraction silentlycontinue)) {
add-pssnapin VMware.VimAutomation.Core
}
$OpenConnection = $global:DefaultVIServers | where { $_.Name -eq $VIServer }
if($OpenConnection.IsConnected) {
$VIConnection = $OpenConnection
write-output "Reusing open connection to $VIServer"
}
else {
$VIConnection = Connect-VIServer $VIServer -Credential $Creds
write-output "Connecting to $VIServer"
}
Connect-VIServer $VIServer -Credential $Creds
write-output "Collecting VM information"
$VM = Get-VM | Sort Name
write-output "Collecting Host information"
$VMH = Get-VMHost | Sort Name
write-output "Collecting Cluster information"
$Clusters = Get-Cluster | Sort Name
write-output "Collecting Datastore information"
$Datastores = Get-Datastore | Sort Name | Where-Object {$_.Name -notmatch "local" }
write-output "Collecting detailed VM information"
$FullVM = Get-View -ViewType VirtualMachine | Where {-not $_.Config.Template}
write-output "Collecting Template information"
$VMTmpl = Get-Template
write-output "Collecting detailed Host information"
$HostsViews = Get-View -ViewType hostsystem
write-output "Collecting detailed Cluster information"
$clusviews = Get-View -ViewType ClusterComputeResource
write-output "Collecting detailed Datastore information"
$storageviews = Get-View -ViewType Datastore
write-output "Collecting vCenter Event Data"
$VIEvent = Get-VIEvent -maxsamples ([int]::MaxValue) -Start $(get-date).AddDays(-$DaysData)
Function GuestOSVersions() {
# —- VM Guest OS Pivot Table —-
$VMOSversions = @{ }
$FullVM | % {
# Prefer to use GuestFullName but try AltGuestName first
if ($_.Config.AlternateGuestName) { $VMOSversion = $_.Config.AlternateGuestName }
if ($_.Guest.GuestFullName) { $VMOSversion = $_.Guest.GuestFullName }
# Seeing if any of these options worked
if (!($VMOSversion)) {
# No 'version' so checking for tools
if (!($_.Guest.ToolsStatus.Value__ )) {
$VMOSversion = "Unknown – no VMTools"
} else {
# Still no 'version', must be old tools
$toolsversion = $_.Config.Tools.ToolsVersion
$VMOSversion = "Unknown – tools version $toolsversion"
}
}
$VMOSversions.$VMOSversion++
}
$myCol = @()
foreach ( $gosname in $VMOSversions.Keys | sort) {
$MyDetails = "" | select OS, Count
$MyDetails.OS = $gosname
$MyDetails.Count = $VMOSversions.$gosname
$myCol += $MyDetails
}
$vVMOSversions = $myCol | sort Count -desc
If (($vVMOSversions | Measure-Object).count -gt 0) {
$Header = "VMs by Operating System : $($vVMOSversions.count)"
$vVMOSversions
}
$vVMOSversions = $null
}
# Starting the report
$Info = New-Object -TypeName PSObject -Property @{
"Number of Hosts" = (@($VMH).Count)
"Number of VMs" = (@($VM).Count)
"Number of Templates" = (@($VMTmpl).Count)
"Number of Clusters" = (@($Clusters).Count)
"Number of Datastores" = (@($Datastores).Count)
"Active VMs" = (@($FullVM | Where { $_.Runtime.PowerState -eq "poweredOn" }).Count)
"In-active VMs" = (@($FullVM | Where { $_.Runtime.PowerState -eq "poweredOff" }).Count)
}
$ProblemHosts = @($VMH | where {$_.ConnectionState -ne "Connected" -and $_.ConnectionState -ne "Maintenance"} | Select name, @{N="Connection State";E={$_.ExtensionData.Runtime.ConnectionState}}, @{N="Power State";E={$_.ExtensionData.Runtime.PowerState}})
$VMsPerDS= @($StorageViews | where { $_.Name -notmatch "Datastore" -and $_.Name -notmatch "swap" } | Select Name, @{N="NumVM";E={($_.vm).Count}} | Sort NumVM -Descending)
$VMsPerHost = Get-VMHost | Select Name, @{N=“NumVM“;E={($_ | Get-VM).Count}} | Sort NumVM -Descending
$CreatedVMs = @($VIEvent | where {$_.Gettype().Name -eq "VmCreatedEvent" -or $_.Gettype().Name -eq "VmBeingClonedEvent" -or $_.Gettype().Name -eq "VmBeingDeployedEvent"} | Select createdTime, UserName, fullFormattedMessage)
$RemovedVMs = @($VIEvent | where {$_.Gettype().Name -eq "VmRemovedEvent"}| Select CreatedTime, UserName, fullFormattedMessage)
$CDConnected = @($FullVM | ?{$_.runtime.powerState -eq "PoweredOn" | ?{$_ -is [VMware.Vim.VirtualCdrom] -And $_.connectable.connected}} | Select Name)
$PoweredOffVMs = @($VM | Where { $_.PowerState -eq "PoweredOff"} | Select Name)
$ResetVMs = @($VIEvent | where {$_.Gettype().Name -eq "VmResettingEvent"}| Select createdTime, UserName, fullFormattedMessage)
$VMOSVersions = GuestOSVersions
$MyReport += "General Information about $VIServer"
$MyReport += $Info | ConvertTo-Html -Fragment
$MyReport += $VMOSVersions | convertto-html -fragment
if ($ProblemHosts -gt "") {
$MyReport += "ProblemHosts"
$MyReport += $ProblemHosts | ConvertTo-Html -Fragment
}
$MyReport += "VMsPerDS"
$MyReport += $VMsPerDS | ConvertTo-Html -Fragment
$MyReport += "Created VMs"
$MyReport += $CreatedVMs | ConvertTo-Html -Fragment
$MyReport += "Removed VMs"
$MyReport += $RemovedVMs | ConvertTo-Html -Fragment
if ($CDConnected -gt "") {
$MyReport += "CD Connected"
$MyReport += $CDConnected | ConvertTo-Html -Fragment
}
if ($ProblemHosts -gt "") {
$MyReport += "Powered Off"
$MyReport += $PoweredOffVMs | ConvertTo-Html -Fragment
}
$MyReport += "Reset VMs"
$MyReport += $ResetVMs | ConvertTo-Html -Fragment
$MyReport += "VMsPerHost"
$MyReport += $VMsPerHost | ConvertTo-Html -Fragment
$HTMLMessage = $HTMLHeader + $MyReport + $HTMLEnd
write-output "sending message for $VIServer"
Disconnect-VIServer $VIServer -Force -Confirm:$false
Send-MailMessage -To $EmailTo -From $EmailFrom -SmtpServer $SMTPSRV -Subject "Weekly Report for $VIServer" -BodyAsHtml -Body $HTMLMessage
}
|
PowerShellCorpus/GithubGist/desek_1edf1f404d7ec58531be_raw_033aa363143b537a64b9573931c57a4ab9bf01d1_ProcessSCSMDW.ps1
|
desek_1edf1f404d7ec58531be_raw_033aa363143b537a64b9573931c57a4ab9bf01d1_ProcessSCSMDW.ps1
|
$smdir = (Get-ItemProperty "HKLM:\Software\Microsoft\System Center\2010\Service Manager\Setup").InstallDirectory
Import-Module "$smdir\Microsoft.EnterpriseManagement.Warehouse.Cmdlets.psd1"
$SleepTimer = 120
$JobTypes = @(
"DWMaintenance",
"MPSyncJob",
"Extract_",
"Transform.",
"Load.",
"Process."
)
$Jobs = Get-SCDWJob
Foreach ($Job in $Jobs)
{
Disable-SCDWJobSchedule -JobName $Job.Name -Verbose
Disable-SCDWJob -JobName $Job.Name -Verbose
Stop-SCDWJob -JobName $Job.Name -Verbose
Start-Sleep -Seconds ($SleepTimer/4)
}
Start-Sleep -Seconds ($SleepTimer*2)
Foreach ($JobType in $JobTypes)
{
Foreach ($Job in ($Jobs | Where-Object {$_.Name -like "$($JobType)*"}))
{
Write-Output "[$(Get-Date -Format HH:mm:ss)] $($Job.Name): Starting"
Enable-SCDWJob -JobName $Job.Name -Verbose
Start-Sleep -Seconds $SleepTimer
Start-SCDWJob -JobName $Job.Name -Verbose
do {
Write-Output "[$(Get-Date -Format HH:mm:ss)] $($Job.Name): Running"
Start-Sleep -Seconds $SleepTimer
} while ((Get-SCDWJob -JobName $Job.Name).Status -eq "Running")
Write-Output "[$(Get-Date -Format HH:mm:ss)] $($Job.Name): Completed"
}
}
$Jobs = Get-SCDWJob
Foreach ($Job in $Jobs)
{
If ($Job.IsEnabled -eq $false)
{
Enable-SCDWJob -JobName $Job.Name -Verbose
}
Enable-SCDWJobSchedule -JobName $Job.Name -Verbose
}
|
PowerShellCorpus/GithubGist/rchaganti_656fd3a8e6b6368ed5dc_raw_2f86a220c12150f4ae3e089ab3fa7f6f72763393_Get-AzureStatus.ps1
|
rchaganti_656fd3a8e6b6368ed5dc_raw_2f86a220c12150f4ae3e089ab3fa7f6f72763393_Get-AzureStatus.ps1
|
Function Get-AzureStatus {
$response = Invoke-RestMethod -Uri 'http://azure.microsoft.com/en-us/status/feed/'
if ($response) {
foreach ($item in $response) {
Write-Host "$($item.Title) : " -NoNewline
Write-Host -ForegroundColor Red "$($item.Description)"
}
} else {
Write-Host -ForegroundColor Green "All is well!"
}
}
|
PowerShellCorpus/GithubGist/jeffpatton1971_354c4c0948a93ea5b9e0_raw_75d2377924c917331b17b92f8e63edce1f473782_Setup-Server.ps1
|
jeffpatton1971_354c4c0948a93ea5b9e0_raw_75d2377924c917331b17b92f8e63edce1f473782_Setup-Server.ps1
|
<#
This script will configure the local machine for the SQL MP
Low Privilege Environment
We need to set the following items on the server
Add SQLDefaultAction account and SQLMonitor account to
Performance Monitor Users
Add SQLDefaultAction account and SQLMonitor account to
EventLog Readers
Add SQLDefaultAction account and SQLMPLowPriv group to
Users
Grant SQLDefaultAction account and SQLMPLowPriv group
Logon Locally User Right
Grant SQLDefaultAction account and SQLMPLowPriv group
Read Permission
HKLM:\Software\Microsoft\Microsoft SQL Server\
Grant SQLMPLowPriv group
Read Permission
HKLM:\Software\Microsoft\Microsoft SQL Server\$INSTANCEID\MSSQLServer\Parameters
Grant SQLDefaultAction account and SQLMPLowPriv group
Execute Methods, Enable Account, Remote Enable, Read Security Permission
WMI:\root\cimv2
WMI:\root\default
WMI:\root\Microsoft\SqlServer\ComputerManagement
For each item we need to test if true, and if false
perform the required item.
This may be able to be turned into a DSC flow.
#>
Param
(
$Computername = $env:COMPUTERNAME,
[string] $ActionAccount,
[string] $LowPrivGroup
)
Import-Module C:\temp\SqlManagement.psm1
Import-Module C:\temp\ActiveDirectoryManagement.psm1
[System.Management.Automation.PSCredential] $SqlDefaultAction = (New-Object System.Management.Automation.PSCredential($ActionAccount,(New-Object System.Security.SecureString($null))))
[System.Security.Principal.NTAccount]$Account = New-Object System.Security.Principal.NTAccount($SqlDefaultAction.UserName);
[string]$sqlDaSid = $Account.Translate([System.Security.Principal.SecurityIdentifier]).ToString();
[System.Management.Automation.PSCredential] $SQLMPLowPriv = (New-Object System.Management.Automation.PSCredential($LowPrivGroup,(New-Object System.Security.SecureString($null))))
[System.Security.Principal.NTAccount]$Account = New-Object System.Security.Principal.NTAccount($SQLMPLowPriv.UserName);
[string]$sqlLpSid = $Account.Translate([System.Security.Principal.SecurityIdentifier]).ToString();
#
# Test group membership for the following groups
# Performance Monitor Users
# EventLog Readers
# Users
#
$Groups = @("Performance Monitor Users","Event Log Readers","Users");
foreach ($Group in $Groups)
{
$Members = Get-LocalGroupMembers -ComputerName $Computername -GroupName $Group;
if (!($Members |Where-Object {$_.Name -eq $SqlDefaultAction.GetNetworkCredential().UserName}))
{
#
# Account not found
#
Add-UserToLocalGroup -ComputerName $Computername -UserName $SqlDefaultAction.GetNetworkCredential().UserName -LocalGroup $Group -UserDomain $SqlDefaultAction.GetNetworkCredential().Domain;
}
if (!($Members |Where-Object {$_.Name -eq $SQLMPLowPriv.GetNetworkCredential().UserName}))
{
#
# Account not found
#
Add-UserToLocalGroup -ComputerName $Computername -UserName $SQLMPLowPriv.GetNetworkCredential().UserName -LocalGroup $Group -UserDomain $SQLMPLowPriv.GetNetworkCredential().Domain;
}
}
#
# Test logon locally right for the following accounts
# SQLDefaultAction
# SQLMPLowPriv
#
# http://gallery.technet.microsoft.com/PowerShell-script-to-add-b005e0f6#content
#
$tmp = [System.IO.Path]::GetTempFileName()
secedit.exe /export /cfg "$($tmp)"
$Configuration = Get-Content -Path $tmp
$currentSetting = ""
foreach($Line in $Configuration)
{
if( $Line -like "SeInteractiveLogonRight*")
{
$x = $Line.split("=",[System.StringSplitOptions]::RemoveEmptyEntries)
$currentSetting = $x[1].Trim()
}
}
Remove-Item $tmp;
if (!(($currentSetting.Contains($sqlDaSid)) -and ($currentSetting.Contains($sqlLpSid))))
{
if (!($currentSetting.Contains($sqlDaSid)))
{
$currentSetting += ",*$($sqlDaSid)";
}
if (!($currentSetting.Contains($sqlLpSid)))
{
$currentSetting += ",*$($sqlLpSid)";
}
Write-Host $currentSetting
$outFile = @"
[Unicode]
Unicode=yes
[Version]
signature="`$CHICAGO`$"
Revision=1
[Privilege Rights]
SeInteractiveLogonRight = $($currentSetting)
"@
$tmp = [System.IO.Path]::GetTempFileName()
$outFile | Set-Content -Path $tmp -Encoding Unicode -Force
Push-Location (Split-Path $tmp);
try
{
secedit.exe /configure /db "secedit.sdb" /cfg "$($tmp)" /areas USER_RIGHTS
}
finally
{
Pop-Location
Remove-Item $tmp
}
}
else
{
Write-Host "NO ACTIONS REQUIRED! Account already in ""Allow Logon Locally"""
}
#
# http://msdn.microsoft.com/en-us/library/ms147899(v=vs.110).aspx
#
# Test Read Permission for the following registry entries
# HKLM:\Software\Microsoft\Microsoft SQL Server\
#
# Will need to get each instance first
#
# HKLM:\Software\Microsoft\Microsoft SQL Server\$INSTANCEID\MSSQLServer\Parameters
#
$Registry = "HKLM:\Software\Microsoft\Microsoft SQL Server\";
try
{
$Acl = Get-Acl $Registry -ErrorAction SilentlyContinue;
$Aces = ($Acl |Select-Object -Property Access).Access;
if (!($Aces |Where-Object {$_.IdentityReference -eq $SqlDefaultAction.UserName}))
{
#
Write-Host "Missing permission for SqlDefaultAction"
#
$Ace = New-Object System.Security.AccessControl.RegistryAccessRule(
$SqlDefaultAction.UserName,
[System.Security.AccessControl.RegistryRights]::ReadKey,
[System.Security.AccessControl.InheritanceFlags]::ContainerInherit,
[System.Security.AccessControl.PropagationFlags]::None,
[System.Security.AccessControl.AccessControlType]::Allow);
$Acl.SetAccessRule($Ace);
}
if (!($Aces |Where-Object {$_.IdentityReference -eq $SQLMPLowPriv.UserName}))
{
#
write-host "Missing permission for SQLMPLowPriv"
#
$Ace = New-Object System.Security.AccessControl.RegistryAccessRule(
$SQLMPLowPriv.UserName,
[System.Security.AccessControl.RegistryRights]::ReadKey,
[System.Security.AccessControl.InheritanceFlags]::ContainerInherit,
[System.Security.AccessControl.PropagationFlags]::None,
[System.Security.AccessControl.AccessControlType]::Allow);
$Acl.SetAccessRule($Ace);
}
$Instances = Get-SQLInstance;
foreach ($Instance in $Instances)
{
$InstanceReg = "$($Registry)$($Instance.InstanceID)\MSSQLServer\Parameters";
Write-Host $InstanceReg
$Acl = Get-Acl $InstanceReg;
$Aces = (Acl |Select-Object -Property Access).Access;
if (!($Aces |Where-Object {$_.IdentityReference -eq $SQLMPLowPriv.UserName}))
{
#
Write-Host "Missing permission for SQLMPLowPriv"
#
$Ace = New-Object System.Security.AccessControl.RegistryAccessRule(
$SQLMPLowPriv.UserName,
[System.Security.AccessControl.RegistryRights]::ReadKey,
[System.Security.AccessControl.InheritanceFlags]::ContainerInherit,
[System.Security.AccessControl.PropagationFlags]::None,
[System.Security.AccessControl.AccessControlType]::Allow);
$Acl.SetAccessRule($Ace);
}
}
}
catch
{
Write-Host "SQL Not Installed"
}
#
# Test Execute Methods, Enable Account, Remote Enable, Read Security Permission on WMI entries
# WMI:\root\cimv2
# WMI:\root\default
#
# This entry depends on the sql version installed, so we just need to match ComputerManagement
#
# WMI:\root\Microsoft\SqlServer\ComputerManagement
#
#
$Namespaces = @("root\cimv2","root\default","root\Microsoft\SqlServer\ComputerManagement10","root\Microsoft\SqlServer\ComputerManagement11");
Write-Host $Namespaces
foreach ($Namespace in $Namespaces)
{
try
{
$Error.Clear()
$Security = Get-WmiObject -Class __SystemSecurity -Namespace $Namespace -ErrorAction SilentlyContinue
$Descriptor = @($null);
$Result = $Security.PsBase.InvokeMethod("GetSD",$Descriptor)
if ($Result -eq 0)
{
$daSDDL = "(A;;CCDCWPRC;;;$($sqlDaSid))";
$converter = New-Object System.Management.ManagementClass Win32_SecurityDescriptorHelper;
$rootSDDL = $converter.BinarySDToSDDL($Descriptor[0]);
if (!($rootSDDL.SDDL.Contains($sqlDaSid)))
{
$NewSDDL = $rootSDDL.SDDL += $daSDDL;
$WMIbinarySD = $converter.SDDLToBinarySD($NewSDDL);
$WMIconvertedPermissions = ,$WMIbinarySD.BinarySD;
$Result = $security.PsBase.InvokeMethod("SetSD",$WMIconvertedPermissions);
}
$lpSDDL = "(A;;CCDCWPRC;;;$($sqlLpSid))";
if (!($rootSDDL.SDDL.Contains($sqlLpSid)))
{
$NewSDDL = $rootSDDL.SDDL += $lpSDDL;
$WMIbinarySD = $converter.SDDLToBinarySD($NewSDDL);
$WMIconvertedPermissions = ,$WMIbinarySD.BinarySD;
$Result = $security.PsBase.InvokeMethod("SetSD",$WMIconvertedPermissions);
}
}
else
{
Write-Error "An error occurred retreiving Security Definitions from WMI.`r`nError Number : $($Result)";
break;
}
}
catch
{
$_
}
}
#
# http://msdn.microsoft.com/en-us/library/aa394063(v=vs.85).aspx
#
# Don't need these, but don't want to lose them
#
$amFlags = @{1="FILE_READ_DATA";2="FILE_WRITE_DATA";4="FILE_APPEND_DATA";8="FILE_READ_EA";16="FILE_WRITE_EA";32="FILE_EXECUTE";64="FILE_DELETE_CHILD";128="FILE_READ_ATTRIBUTES";256="FILE_WRITE_ATTRIBUTES";65536="DELETE";131072="READ_CONTROL";262144="WRITE_DAC";524288="WRITE_OWNER";1048576="SYNCHRONIZE"}
$afFlags = @{1="OBJECT_INHERIT_ACE"; 2="CONTAINER_INHERIT_ACE";4="NO_PROPAGATE_INHERIT_ACE";8="INHERIT_ONLY_ACE";16="INHERITED_ACE"}
<#
This script will configure the SQL Server for the SQL MP
Low Privilege Environment
#>
|
PowerShellCorpus/GithubGist/steelcm_2558512_raw_14f084721ec45e0baa90e1ff57cb0eec2aec9dc9_gistfile1.ps1
|
steelcm_2558512_raw_14f084721ec45e0baa90e1ff57cb0eec2aec9dc9_gistfile1.ps1
|
PS C:\> netstat -an | select-string -pattern "listening"
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
TCP 0.0.0.0:81 0.0.0.0:0 LISTENING
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:383 0.0.0.0:0 LISTENING
|
PowerShellCorpus/GithubGist/colinbowern_5937673_raw_828317b19e3d5f3e7bc26936e973e6026e47367c_Import-SQLPS.ps1
|
colinbowern_5937673_raw_828317b19e3d5f3e7bc26936e973e6026e47367c_Import-SQLPS.ps1
|
$CurrentFolder = $(Get-Location).Path
Import-Module SQLPS -DisableNameChecking
Set-Location $CurrentFolder
|
PowerShellCorpus/GithubGist/kmoormann_3406887_raw_9e3b225896735628626211fb4a2e4084325cdc21_CopyFilesInFolder.ps1
|
kmoormann_3406887_raw_9e3b225896735628626211fb4a2e4084325cdc21_CopyFilesInFolder.ps1
|
function Global:CopyFilesInFolder([string] $FromDir, [string] $ToDir, [string] $FileExtension)
{
#Destination for files
$From = $FromDir + "*" + $FileExtension
Copy-Item $From $ToDir
}
|
PowerShellCorpus/GithubGist/pcgeek86_b5f29ab8a11b414b230f_raw_0dd49062baf8ef6999e289ee3c9d7438c838f2d4_gistfile1.ps1
|
pcgeek86_b5f29ab8a11b414b230f_raw_0dd49062baf8ef6999e289ee3c9d7438c838f2d4_gistfile1.ps1
|
$MyFilter = New-WmiEventFilter –Name WatchFolderRoboCopy –Query 'SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA "CIM_DirectoryContainsFile" AND TargetInstance.GroupComponent = "Win32_Directory.Name=\"c:\\\\FileHistory\""' –EventNamespace "root\cimv2"
$MyConsumer = New-WmiEventConsumer –ConsumerType CommandLine –Name WatchFolderRoboCopy –CommandLineTemplate "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -<<<ParameterName1>>> %TargetInstance.<<<WmiPropertyName>>>%"
New-WmiFilterToConsumerBinding –Filter $MyFilter –Consumer $MyConsumer
|
PowerShellCorpus/GithubGist/ykhroki_ce9ce661302c28656898_raw_cbe82c67cbd45fbbbf99866ae3a84fd0e4cb68e4_expire-homedir.ps1
|
ykhroki_ce9ce661302c28656898_raw_cbe82c67cbd45fbbbf99866ae3a84fd0e4cb68e4_expire-homedir.ps1
|
# By Request: Searching files by age (and other properties) via PowerShell (#PowerShell)
# <http://www.systemcentercentral.com/by-request-searching-files-by-age-and-other-properties-via-powershell-powershell/>
# “Delete Files Older Than” Batch Script - ServerFault
# <http://serverfault.com/questions/259707/delete-files-older-than-batch-script>
#
$Files = Get-ChildItem -Recurse -Path C:\Users\ | Where {($_.LastWriteTime -lt (Get-Date).AddDays(-7)) -and ($_.Length -ge 20MB)}
Foreach ($File in $Files)
{
Write-Host "Deleting File $File" -foregroundcolor "Red";
Remove-Item $File | out-null
}
|
PowerShellCorpus/GithubGist/jtuttas_5354953_raw_42e7e9cc2cc21dace8f3316caa1a443ec6b0a49e_drehFuntion.ps1
|
jtuttas_5354953_raw_42e7e9cc2cc21dace8f3316caa1a443ec6b0a49e_drehFuntion.ps1
|
cls
function dreh([String]$a) {
$out=""
for ($i=$a.Length-1;$i -ge 0;$i--) {
$out=$out+$a.Chars($i)
}
return $out
}
$a=dreh ("Hallo")
Write-Host ("Gedreht ("+$a+")")
|
PowerShellCorpus/GithubGist/tkinz27_fd92ba9af0e0309614ee_raw_a7f4617532509ea872a261ad1b95d3ffe25151c4_copy.ps1
|
tkinz27_fd92ba9af0e0309614ee_raw_a7f4617532509ea872a261ad1b95d3ffe25151c4_copy.ps1
|
#!powershell
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# WANT_JSON
# POWERSHELL_COMMON
$params = Parse-Args $args;
$src= Get-Attr $params "src" $FALSE;
If ($src -eq $FALSE)
{
Fail-Json (New-Object psobject) "missing required argument: src";
}
$dest= Get-Attr $params "dest" $FALSE;
If ($dest -eq $FALSE)
{
Fail-Json (New-Object psobject) "missing required argument: dest";
}
$result = New-Object psobject @{
changed = $FALSE
};
If (Test-Path $dest)
{
$dest_md5 = (Get-FileHash -Path $dest -Algorithm MD5).Hash.ToLower();
$src_md5 = (Get-FileHash -Path $src -Algorithm MD5).Hash.ToLower();
If ( $src_md5 -ne $dest_md5)
{
Copy-Item -Path $src -Destination $dest -Force;
}
$dest_md5 = (Get-FileHash -Path $dest -Algorithm MD5).Hash.ToLower();
If ( $src_md5 -eq $dest_md5)
{
$result.changed = $TRUE;
}
Else
{
Fail-Json (New-Object psobject) "Failed to place file";
}
}
Else
{
Copy-Item -Path $src -Destination $dest;
$result.changed = $TRUE;
}
Exit-Json $result;
|
PowerShellCorpus/GithubGist/pieterjd_5465325_raw_50816aacba1df4862c6bc2675b164478c3217b4e_listInstalledUpdates.ps1
|
pieterjd_5465325_raw_50816aacba1df4862c6bc2675b164478c3217b4e_listInstalledUpdates.ps1
|
$Session = New-Object -ComObject Microsoft.Update.Session
$Searcher = $Session.CreateUpdateSearcher()
$HistoryCount = $Searcher.GetTotalHistoryCount()
$Searcher.QueryHistory(1,$HistoryCount) | Select-Object Date, Title,ClientApplicationID ,Description | Out-GridView
$Searcher.QueryHistory(1,$HistoryCount) | Select-Object * | Out-GridView
|
PowerShellCorpus/GithubGist/mrxinu_4142383_raw_72888cae5fa44e09145e8e146fcafecc4bda6afd_get-macs.ps1
|
mrxinu_4142383_raw_72888cae5fa44e09145e8e146fcafecc4bda6afd_get-macs.ps1
|
#
# Script: get-macs.ps1
#
# Purpose: Connect to a list of servers and get their MACs and IP
# addresses and output the results.
#
# Written by Steven Klassen <sklassen@gmail.com>
#
# Usage: .\get-macs.ps1 <computer_list>
#
#############################################################################
$debug = 1
# make sure the input file exists first
if ((${args}[0] -ne $null) -and (test-path ${args}[0])) {
$computers = get-content ${args}[0]
}
else {
write-host "Usage: .\get-macs.p1 <computer_list>"
exit 1
}
foreach ($computer in $computers) {
$interfaces = get-wmiobject -class 'win32_NetworkAdapterConfiguration' -name 'root\cimv2' `
-computer $computer -filter 'IPEnabled = true' 2>$null
foreach ($interface in $interfaces) {
$tokens = $computer, $interface.MACAddress, $interface.IpAddress
# skip blank lines
if ($interface.IpAddress -eq $null) {
continue
}
# string them up with commas (and output)
[String]::join(',', $tokens)
}
}
exit 0
|
PowerShellCorpus/GithubGist/bak-t_7946132_raw_feddd78abb4ca37708b80cd9f7022b172bc43c28_create-package.ps1
|
bak-t_7946132_raw_feddd78abb4ca37708b80cd9f7022b172bc43c28_create-package.ps1
|
$ErrorActionPreference = "Stop"
#$version = "1.0.5-alpha"
$version = "1.0.4.1-patched"
$packageSpec = "..\smartconf\SmartConf\SmartConf.nuspec"
$solutionFile = "..\smartconf\SmartConf.sln"
$projectFile = "..\smartconf\SmartConf\SmartConf.csproj"
$solutionConfiguration = "Release"
function Main() {
# internal variables
$packageTmpDir = ".\_pkg"
$packageLibDir = Join-Dirs $packageTmpDir "lib"
$packageNetSpecificDir = Join-Dirs $packageLibDir (Get-FrameworkAbbrevatedName (Get-TargetProjectFramework $projectFile))
$projectDir = [System.IO.Path]::GetDirectoryName($projectFile)
Build-Solution
# recreate directory tree
Recreate-Path $packageTmpDir
Recreate-Path $packageLibDir
Recreate-Path $packageNetSpecificDir
#copy necessary files
Copy-Item (Join-Dirs $projectDir "bin" $solutionConfiguration "*") -Destination $packageNetSpecificDir -Include "*.dll","*.xml" -Recurse
Copy-Item $packageSpec $packageTmpDir
Build-Package (Join-Dirs $packageTmpDir $([System.IO.Path]::GetFileName($packageSpec)))
}
function Build-Package($packageSpecFile) {
Exec {
NuGet.exe pack $packageSpecFile -version $version
}
}
function Build-Solution() {
Exec {
MSBuild.exe $solutionFile /t:Rebuild /p:Configuration=$solutionConfiguration /p:Platform="Any CPU"
}
}
function Get-TargetProjectFramework($projectFile) {
$projectFileContent = [xml](Get-Content $projectFile)
#$frameworkVersionNode = $projectFileContent.SelectSingleNode("/Project/PropertyGroup/TargetFrameworkVersion")
$frameworkVersionNode = $projectFileContent.GetElementsByTagName("TargetFrameworkVersion") | select -First 1
if (!$frameworkVersionNode) {
throw "Target framework not found in project file `"$projectFile`""
}
return $frameworkVersionNode.InnerText
}
function Get-FrameworkAbbrevatedName($version) {
"net" + ($version -replace "[v\.]","")
}
function Recreate-Path($path) {
if (Test-Path $path) {
[void](Remove-Item -Path $path -Recurse)
}
[void](md $path)
}
function Join-Dirs() {
[System.IO.Path]::Combine([string[]]$args)
}
function Exec([scriptblock]$cmd, [hashtable]$warningCodes = @{}, [string]$errorMessage = "Error executing command: " + $cmd) {
& $cmd
if ($LastExitCode -ne 0) {
$sExitCode = $LastExitCode.ToString()
if ($warningCodes.Contains($sExitCode)) {
$warningMessage = $warningCodes[$sExitCode]
if (! [string]::IsNullOrEmpty($warningMessage)) {
Write-Warning "$warningMessage"
}
return
}
throw $errorMessage
}
}
Main
|
PowerShellCorpus/GithubGist/danielthor_e141a530dfa7a9636274_raw_6ffa851d8b57e9e63a8aa0b2fa2a666f72a6a399_export_from_ad.ps1
|
danielthor_e141a530dfa7a9636274_raw_6ffa851d8b57e9e63a8aa0b2fa2a666f72a6a399_export_from_ad.ps1
|
# Export data from AD
# Give PS access to import snapins
Set-ExecutionPolicy Unrestricted
# Add AD module
Import-Module ActiveDirectory
# Add Quest snapin for nifty commands
# Requirers install: http://www.quest.com/powershell/activeroles-server.aspx
# Manual: http://wiki.powergui.org/index.php
Add-PSSnapin Quest.ActiveRoles.ADManagement
# In my case I had different companies in AD, looping not required
$companies = @('Company 1', 'Company 2', 'Company 3', '...')
foreach ($company in $companies) {
# GetQADUser
# -Enabled: Only enabled users
# -SizeLimit 5000: Go beyond default 1000 user limit
# -OrganizationalUnit: OU to search in
#
# select
# Which AD-attributes to get
# more can be found here: http://www.kouti.com/tables/userattributes.htm
#
# export-csv
# -Encoding: What encoding to use
# -Append: Append output to file
Get-QADUser -Enabled -SizeLimit 5000 -OrganizationalUnit "ou=Users,ou=$company,ou=Company,ou=Data,dc=contoso,dc=com" |
select Name,Email,Title,Company,Department,Description,telephoneNumber,mobile,DN |
export-csv c:\Temp\export_2014-10-20.csv -Encoding UTF8 -Append
}
|
PowerShellCorpus/GithubGist/kyam_5577021_raw_bfcbd8863c1041b39b47f70edad230e6655be214_add-domainuser.ps1
|
kyam_5577021_raw_bfcbd8863c1041b39b47f70edad230e6655be214_add-domainuser.ps1
|
#
# http://gallery.technet.microsoft.com/scriptcenter/68546b6d-4fee-47e1-9635-a5378576406c
#
# \\domain\\kyam ... domain user
# \\computer1 ... computer-name
#
#
$user = [ADSI]("WinNT://domain/kyam")
$group = [ADSI]("WinNT://computer1/Administrators")
$group.PSBase.Invoke("Add",$user.PSBase.Path)
|
PowerShellCorpus/GithubGist/rwhitmire_6033474_raw_37c61cb63a0f67910ffc3b8c70204430c6cb0d51_posh-git-setup.ps1
|
rwhitmire_6033474_raw_37c61cb63a0f67910ffc3b8c70204430c6cb0d51_posh-git-setup.ps1
|
Set-ExecutionPolicy Unrestricted
Set-ExecutionPolicy Bypass
# add this to profile
$env:path += ";" + (Get-Item "Env:ProgramFiles(x86)").Value + "\Git\bin"
|
PowerShellCorpus/GithubGist/joshtransient_5984597_raw_f23dbdb9ac64f17955abd4d1d039563e9a0af766_Reset-SPVersions.ps1
|
joshtransient_5984597_raw_f23dbdb9ac64f17955abd4d1d039563e9a0af766_Reset-SPVersions.ps1
|
### BEGIN VARIABLES ###
$siteUrl="https://sharepoint/" #Enter the URL to your site.
$csvFile=".\sites.csv"
$useCsvFile=$false
$outPut="C:\metrics\scripts\VersionDeletionReport.xml"
$deleteVersion=$false #CAUTION!!!When set to false will only report on files that would be Deleted, else versions are deleted.
[Int]$keepMajorVersions=3
[int]$keepMinorVersions=1
$setVersionLimit=$false #When set to true will set Major Versions to $keepMajorVersions. If minor versions are enabled, will set number of minor versions to $keepMinorVersions
$libraryExclusions="Style Library","Site Collection Images" #Type the title of the library to be excluded. format should be: $libraryExclusions="Style Library","Site Collection Images"
### END VARIABLES ###
[system.reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint")
function DeleteVersion {
if($deleteVersion -eq $true) {
for($x=$deleteVersions.Count; $x -ne -1;$x--) {
Try {
if($file.Versions.GetVersionFromLabel($file.versions[$deleteVersions[$x]].versionlabel)) {
Start-Sleep -Seconds 1
$fileVersion=$file.Versions.GetVersionFromLabel($file.versions[$deleteVersions[$x]].versionlabel)
$fileVersion.versionLabel
$file.name
$file.Versions.DeleteByLabel($file.versions[$deleteVersions[$x]].versionLabel)
}
}
Catch [System.Management.Automation.RuntimeException] {
#Index operation failed. The array index evaluated to null
}
}
}
try { $item.SystemUpdate() }
Catch [System.Exception] {
#No updates were made
}
}
function GetVersions {
$deleteVersions=New-Object system.Collections.ArrayList
$versionsArray=New-Object system.Collections.ArrayList
for($i=0;$i -lt $counter;$i++) {
if($file.Versions[$i].VersionLabel) {
$strVersion=($file.Versions[$i].VersionLabel).Split(".")
if([int]$($strVersion[0]) -lt ($file.MajorVersion - $keepMajorVersions)) {
if($file.Versions[$i].IsCurrentVersion -eq $false) {
if($strVersion[1] -eq 0) { $versionType="Major" }
else {
$versionType="Minor"
}
VersionInformation
[Void]$deleteVersions.Add($i)
}
}
if([int]$($strVersion[0]) -ge ($file.MajorVersion - $keepMajorVersions)) {
if([int]$($strVersion[1]) -ne 0) {
[Void]$versionsArray.Add($i)
}
}
}
}
GetMinorVersions
DeleteVersion
}
function Remove-MinorVersions {
for($r=0;$r -le $newArray.Count;$r++) {
Try {
$strCurrentMinorVersion=($file.Versions[$newArray[$r]].versionLabel).Split(".")
[int]$intCurrentMinorVersion=$strCurrentMinorVersion[1]
if($newArray.Count -gt $keepMinorVersions) {
if(($intCurrentMinorVersion -gt ($highVersion - $keepMinorVersions))) {
;#Not deleting version
}
elseif(($intCurrentMinorVersion -le ($highVersion - $keepMinorVersions))) {
$i=$newArray[$r]
VersionInformation
[Void]$deleteVersions.Add($newArray[$r])
}
}
}
Catch [System.Exception] { ; }
}
}
function Find-HighVersion {
$highVersion=0
for($s=0;$s -le $newArray.Count;$s++) {
Try {
$strMinorVersion=($file.Versions[$newArray[$s]].VersionLabel).Split(".")
[int]$intHighVersion=$strMinorVersion[1]
if($intHighVersion -ge $highVersion) { $highVersion=$intHighVersion }
}
Catch [System.Exception] { ; }
}
Remove-MinorVersions
}
function GetMinorVersions {
$pVersion="-1000.1000"
$pVersion=$pVersion.Split(".")
$newArray=New-Object system.Collections.ArrayList
for($t=0;$t -lt $versionsArray.Count;$t++) {
$strMinorVersion=($file.Versions[$versionsArray[$t]].VersionLabel).Split(".")
if(($t -eq ($versionsArray.Count - 1)) -or(([int]$($strMinorVersion[0]) - [int]$($pVersion[0])) -gt 0)) {
if($t -eq ($versionsArray.Count - 1)) {
#Checks to see if it is the same Minor version
if(([int]$($strMinorVersion[0]) - [int]$($pVersion[0])) -gt 0) {
Find-HighVersion
$newArray.Clear()
[Void]$newArray.Add($versionsArray[$t])
}
else {
[Void]$newArray.Add($versionsArray[$t])
}
}
if($newArray.Count -gt 0) { Find-HighVersion }
if($t -ne ($versionsArray.Count - 1)) {
$pVersion=$strMinorVersion
$newArray.Clear()
[Void]$newArray.Add($versionsArray[$t])
}
}
elseif(([int]$($strMinorVersion[0]) - [int]$($pVersion[0])) -eq 0) {
[Void]$newArray.Add($versionsArray[$t])
}
}
}
function VersionInformation {
$webUrl=$web.url
$listName=$list.title
$itemUrl=$file.Versions[$i].File.url
$itemName=$file.Versions[$i].File.name
$versionLabel=$file.Versions[$i].VersionLabel
[Int32]$fileSizeBytes=$file.Versions[$i].Size
$fileSizeKb=$fileSizeBytes / 1024
[Int32]$global:totalSpaceKb=$totalSpaceKb + $fileSizeKb
$itemInfo=@"
<New>
<Site>$webUrl</Site>
<List>$listName</List>
<VersionType>$versionType</VersionType>
<ItemUrl>$itemUrl</ItemUrl>
<ItemName>$itemName</ItemName>
<Action>Deleted Version</Action>
<Version>$versionLabel</Version>
<FileSize>$fileSizeKb</FileSize>
</New>
"@
out-file -inputobject $itemInfo -filepath $output -encoding ASCII -append -width 50
}
function Set-VersionLimit {
if($list.EnableVersioning -eq $true) {
$list.MajorVersionLimit=$keepMajorVersions
if($list.EnableMinorVersions -eq $true) {
$list.MajorWithMinorVersionsLimit=$keepMinorVersions
}
$list.Update()
}
}
$createXml=@"
<?xml version="1.0" encoding="ISO-8859-1" ?>
<VersionReport>
"@
out-file -inputobject $createxml -filepath $output -encoding ASCII -width 50
$site=New-Object Microsoft.SharePoint.SPSite("$SiteUrl")
$webs=$site.AllWebs
Write-Host $webs.count
:Beginning_Loop foreach($web in $webs) {
if($useCsvFile -eq $true) {
$csvSites=Import-Csv $csvFile
foreach($csvSite in $csvSites) {
if($csvSite.sites -eq $web.title) {
write-host Found Match
$foundMatch=$true
break
}
}
}
if(($foundMatch -eq $true) -or ($useCsvFile -eq $false)) {
foreach($list in $web.lists) {
if($list.baseTemplate -eq "DocumentLibrary") {
Write-Host $list.title
foreach($libraryExclusion in $libraryExclusions) {
if($list.Title -eq $libraryExclusion) { break }
}
foreach($item in $list.items) {
$file=$item.file
$counter=$file.versions.count
GetVersions
if($setVersionLimit -eq $true) { Set-VersionLimit }
}
}
}
}
$foundMatch=$false;
$web.dispose()
}
$site.dispose()
$totalSpaceMb=$totalSpaceKb / 1024
$totalSpaceGb=$totalSpaceMb / 1024
Write-Host Total Space recovered as Kb is $totalSpaceKb
Write-Host Total Space recovered as Mb is $totalSpaceMb
Write-Host Total Space recovered as Gb is $totalSpaceGb
out-file -inputobject "</VersionReport>" -filepath $output -encoding ASCII -append -width 50
(get-content $output) | foreach-object {$_ -replace "&","&"} | set-content $output
$totalSpaceMb=0
$totalSpaceGb=0
$totalSpaceKb=0
$totalSpacebytes=0
|
PowerShellCorpus/GithubGist/brianvp_af04dfd4d986b8388037_raw_e1ba6df77dba3bbb37e5d0ee6c266500d35a6fbf_gistfile1.ps1
|
brianvp_af04dfd4d986b8388037_raw_e1ba6df77dba3bbb37e5d0ee6c266500d35a6fbf_gistfile1.ps1
|
# Initial Draft - needs cleanup
Function getInputGrid($choice)
{
#7 10 10
if ($choice -eq "DefaultInput")
{
return '..........
..........
..#.......
...#......
.###......
..........
..........
..........
..........
..........'
}
#32 17 17
elseif ($choice -eq "challenge")
{
return '.................
.................
....###...###....
.................
..#....#.#....#..
..#....#.#....#..
..#....#.#....#..
....###...###....
.................
....###...###....
..#....#.#....#..
..#....#.#....#..
..#....#.#....#..
.................
....###...###....
.................
.................'
}
#10 10 10
elseif ($choice -eq 'StillLife')
{
return '..........
.##.......
.##.......
.....##...
.....#.#..
......#...
..##......
.#..#.....
..##......
..........'
} #10 5 5
elseif ($choice -eq 'oscillate')
{
return '.....
.....
.###.
.....
.....'
}
#50 20 20
elseif ($choice -eq 'glider')
{
return '....................
..#.................
...#................
.###................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................'
}
}
function outputGrid($grid, $height, $iteration)
{
Write-Host "Iteration #" $iteration
for ($i = 0 ; $i -lt $height; $i++ )
{
Write-Host -NoNewline $grid[$i]
Write-Host ""
}
}
function nextIteration($grid)
{
$nextGrid = @()
#create a copy of the current grid to modify for the next state
for ($i = 0 ; $i -lt $grid.length ; $i++ )
{
$nextGrid += ,@($grid[$i].Clone())
}
for ($i = 0 ; $i -lt $grid.length ; $i++ )
{
for ($j = 0 ; $j -lt $grid[$i].length ; $j++ )
{
if ($grid[$i][$j] -eq '.') #current cell is off
{
$neighborsOn = neighborsOn $grid $i $j
if ($neighborsOn -eq 3 )
{
$nextGrid[$i][$j] = '#' # turn current cell on
}
}
else #current cell is on
{
$neighborsOn = neighborsOn $grid $i $j
if ($neighborsOn -lt 2 -or $neighborsOn -gt 3)
{
$nextGrid[$i][$j] = '.' # turn current cell off
}
}
}
}
return $nextGrid
}
function neighborsOn($grid, $row, $col)
{
$numOn = 0
$gridHeight = $grid.length
$gridWidth = $grid[0].length
#NW
$y = $row - 1
$x = $col - 1
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
#N
$y = $row - 1
$x = $col
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
#NE
$y = $row - 1
$x = $col + 1
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
#E
$y = $row
$x = $col + 1
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
#SE
$y = $row + 1
$x = $col + 1
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
#S
$y = $row + 1
$x = $col
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
#SW
$y = $row + 1
$x = $col - 1
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
#W
$y = $row
$x = $col - 1
if ($y -lt 0 ) {$y = $gridHeight - 1}
if ($y -ge $gridHeight ) {$y = 0}
if ($x -lt 0 ) {$x = $gridWidth - 1}
if ($x -ge $gridWidth ) {$x = 0}
if ($grid[$y][$x] -eq '#')
{
$numOn += 1
}
return $numOn;
}
$iterations = 50 #Read-Host "Number of Iterations"
$gridWidth = 20 #Read-Host "Grid Width"
$gridHeight = 20 #Read-Host "Grid Height"
$choice = 'glider' #Read-Host "Choose Input Grid: A, B"
# load the input Grid into an array
$inputGrid = getInputGrid($choice)
$inputGrid = [char[]]$inputGrid
$grid = @()
$offset = 0
for ($i = 0 ; $i -lt $gridHeight ; $i++)
{
$currentRow = @()
for ($j = 0 ; $j -lt $gridWidth ; $j++)
{
$currentRow += ,@($inputGrid[$j + $offset])
}
$offset += $j + 2 #add two to account for CR/LF at end of each line
$grid += ,@($currentRow)
}
#perform the simulation
for ($i = 0 ; $i -le $iterations ; $i++ )
{
Clear-Host
outputGrid $grid $gridHeight $i
Start-Sleep 1
$grid = nextIteration $grid
}
|
PowerShellCorpus/GithubGist/kolesnick_7639633_raw_b05b0944b6a815ab07c72da7e6311ebde3edac47_hg-branchowners.ps1
|
kolesnick_7639633_raw_b05b0944b6a815ab07c72da7e6311ebde3edac47_hg-branchowners.ps1
|
hg branches | %{ $_.Split(' ')[0] } | group { hgbranchowner $_ } | %{
write $_.Name
$_.Group | write
write ''
}
|
PowerShellCorpus/GithubGist/ao-zkn_2e77e54bec663289a33d_raw_df43aa78d74a541aa9073ece4071970edeeb8d5e_Rotate-Daily.ps1
|
ao-zkn_2e77e54bec663289a33d_raw_df43aa78d74a541aa9073ece4071970edeeb8d5e_Rotate-Daily.ps1
|
# ------------------------------------------------------------------
# 日付でファイルのローテーションを行う
# 関数名:Rotate-Daily
# 引数 :FilePath ファイルパス
# :DailyRollingFormat 日付フォーマット(デフォルト:yyyy-MM-dd)
# 戻り値:なし
# ------------------------------------------------------------------
function Rotate-Daily([String]$FilePath,[String]$DailyRollingFormat = "yyyy-MM-dd"){
# ファイルが存在する場合
if(Test-Path -LiteralPath $FilePath -PathType Leaf){
# ファイル作成日
$creationDate = $(Get-ItemProperty $FilePath).CreationTime.ToString($DailyRollingFormat)
# 現在日付
$currentDate = Get-Date -Format $DailyRollingFormat
# ローテート対象
if($creationDate -ne $currentDate){
$dailyRollingName = (Split-Path $FilePath -Leaf) + "." + $creationDate
$dailyRollingPath = Join-Path -path (Split-Path $FilePath -Parent) -ChildPath $dailyRollingName
Move-Item -LiteralPath $FilePath -Destination $dailyRollingPath -Force
}
}
}
|
PowerShellCorpus/GithubGist/Novakov_3675315_raw_8d8a9deef32293cdcdbfc2f4f28e46b5e1252c52_gistfile1.ps1
|
Novakov_3675315_raw_8d8a9deef32293cdcdbfc2f4f28e46b5e1252c52_gistfile1.ps1
|
$TOOLS = "D:\Tools"
$WIM_FILE = "C:\ISOs\install_win2008_r2_std_core.wim"
$IMG_INDEX = 1
$VHD_FILE = "C:\VHD - DA\win2008r2_offline.vhd"
$VHD_SIZE = 20480
$LETTER = "Z"
$MOUNT = "$($LETTER):"
$ANSWER_FILE = "c:\ISOs\win2008_r2_offline.xml"
$FEATURES = "NetFx2-ServerCore",
"IIS-WebServerRole",
"MicrosoftWindowsPowerShell",
"ServerManager-PSH-Cmdlets"
function private:Notify
{
param($text)
Write-Host -ForegroundColor Green $text
}
Set-Alias bootsect "$($TOOLS)\bootsect.exe"
Set-Alias imagex "$($TOOLS)\imagex.exe"
if(Test-Path $VHD_FILE)
{
Notify "VHD file exist. Removing..."
Remove-Item -Force $VHD_FILE
}
Notify "Creating VHD disk"
$cmd = "create vdisk file=`"$($VHD_FILE)`" type=expandable maximum=$($VHD_SIZE)
attach vdisk
create partition primary
format fs=ntfs quick
active
assign letter=$($LETTER)
exit"
$cmd | diskpart
Notify "Extracting image"
imagex /apply $WIM_FILE $IMG_INDEX $MOUNT
Notify "Caching unattended installation answer file"
Copy-Item -Path $ANSWER_FILE -Destination "$($MOUNT)\Windows\system32\sysprep\Unattend.xml"
Notify "Applying unatteded installation answer file"
dism /image:$MOUNT /apply-unattend:$ANSWER_FILE
Notify "Installing features"
foreach($feature in $FEATURES)
{
Notify "Installing feature $($feature)"
dism /image:$MOUNT /enable-feature /featureName:$feature
}
Notify "Installing bootloader"
bootsect /nt60 $MOUNT /force /mbr
Notify "Creating BCD"
bcdboot "$($MOUNT)\Windows" /s $MOUNT
Notify "Detaching VHD disk"
$cmd = "select vdisk file=`"$($VHD_FILE)`"
detach vdisk
exit"
$cmd | diskpart
Notify "Installation done"
|
PowerShellCorpus/GithubGist/adamfisher_4317c41f4eae800b356f_raw_c880614a3a35ad66462d0b6e57f99c0779670ed7_Disable%20Windows%20Hibernation.ps1
|
adamfisher_4317c41f4eae800b356f_raw_c880614a3a35ad66462d0b6e57f99c0779670ed7_Disable%20Windows%20Hibernation.ps1
|
powercfg /hibernate off
|
PowerShellCorpus/GithubGist/thethomaseffect_6933803_raw_a5b82b800906512cadb05ed1d7a0afbc9090534a_csharp_in_powershell.ps1
|
thethomaseffect_6933803_raw_a5b82b800906512cadb05ed1d7a0afbc9090534a_csharp_in_powershell.ps1
|
$Source = @"
namespace CSharpPSTest
{
public static class PSTest
{
private static string _result = "Default Value";
public static string Get()
{
return "Get Success: " + _result;
}
public static string Set(string s)
{
_result = s;
return "Set Success: " + _result;
}
}
}
"@
Add-Type -TypeDefinition $Source -Language CSharp
|
PowerShellCorpus/GithubGist/NeilHanlon_11064226_raw_80ffe34812e49c2fa91705eb779f9e18c9b4afd9_2014response.ps1
|
NeilHanlon_11064226_raw_80ffe34812e49c2fa91705eb779f9e18c9b4afd9_2014response.ps1
|
$list = ipcsv '.\2014respond.csv';
#$list | ForEach-Object { Write-Host ($_.LastName)($_.FirstName.Substring(0,1)) }
$process = ForEach ($user in $list)
{
$user3 = $user.LastName +""+ $user.FirstName.Substring(0,1)
try{
$user2 = Get-ADUser $user3 -Properties mail
}
catch{
$user2.mail = "ERROR"
}
[PSCustomObject]@{RespondantID=$user.RespondentID;FirstName=$user.FirstName;LastName=$user.LastName;Email=$user2.mail}
}
$process | export-csv -Path '.\emails.csv'
|
PowerShellCorpus/GithubGist/mst8000_cd1afed4008d3c90a155_raw_af3f627a28f14c1b411871f4e407df4bf63519fe_Calender.ps1
|
mst8000_cd1afed4008d3c90a155_raw_af3f627a28f14c1b411871f4e407df4bf63519fe_Calender.ps1
|
$offset = (Get-Date).AddDays(-(Get-Date).Day + 1).DayOfWeek.value__
$last = (Get-Date).AddDays(-(Get-Date).Day + 1).AddMonths(1).AddDays(-1).Day
for ($($day = -$offset + 1; $count = 1); $day -le $last ; $day++, $count++) {
if ($day -le 0) {
Write-Host -n " "
} elseif ($count % 7 -eq 0) {
Write-Host $day.ToString().PadLeft(3)
} else {
Write-Host -n $day.ToString().PadLeft(3)
}
}
if ($count % 7 -ne 1) { Write-Host "" }
|
PowerShellCorpus/GithubGist/IISResetMe_0b8033cb7382d88208b0_raw_888232a1113bf9953c25f81c7e1dc17a0e2e8640_LazyWebclient.ps1
|
IISResetMe_0b8033cb7382d88208b0_raw_888232a1113bf9953c25f81c7e1dc17a0e2e8640_LazyWebclient.ps1
|
param($u)(&{if($c-is[System.Net.WebClient]){$c}else{($global:c=New-Object System.Net.WebClient)}}).DownloadString($u)
|
PowerShellCorpus/GithubGist/roberto-reale_712c70d55f3dc9d49335_raw_d70cd32997d51113c11fcddffb7a0e48fba8fc1a_rename_files_iso8601_with_progressive_id.ps1
|
roberto-reale_712c70d55f3dc9d49335_raw_d70cd32997d51113c11fcddffb7a0e48fba8fc1a_rename_files_iso8601_with_progressive_id.ps1
|
#
# rename a bunch of files as follows
#
# YYYY-MM-DD_NAME.EXT ==> YYYY-MM-DD_nnnn_NAME.EXT
#
# where nnnn is a progressive identifier
#
# initialize the progressive identifier
$id = 0;
# for each file in the local path
Get-ChildItem -name |% {
# old filename is in the form YYYY-MM-DD_NAME.EXT (e.g. 1982-04-26_foobar.txt)
$old_filename = $_;
# extract the date part (e.g., 1982-04-26)
$trailing = $($old_filename.Substring(0, 10));
# extract the suffix part (e.g.. foobar.txt);
$leading = $_.Substring(11);
# build up the new filename (e.g. 1982-04-26_0123_foobar.txt)
$new_filename = "{0}_{1:0000}_{2}" -f $trailing, $id, $leading
# rename the file
move $old_filename $new_filename;
$id += 1;
}
|
PowerShellCorpus/GithubGist/krohrbaugh_6875688_raw_7c9e1e67416817e31200c4cc003f5e6913dfe174_example.ps1
|
krohrbaugh_6875688_raw_7c9e1e67416817e31200c4cc003f5e6913dfe174_example.ps1
|
# Using the Windows Azure Active Directory Module for Windows PowerShell
#
# Connect to the tenant to modify
Connect-MsolService # => login
# Get Service Principal to add the role to
$servicePrincipal = Get-MsolServicePrincipal -ServicePrincipalName Principal.Name
# Get role object ID
# Alternatively, you can list all the roles (in order to get a different role name) using just `Get-MsolRole`
$roleId = (Get-MsolRole -RoleName "Directory Readers").ObjectId
# Add role to service principal
Add-MsolRoleMember -RoleObjectId $roleId -RoleMemberObjectId $servicePrincipal.ObjectId -RoleMemberType servicePrincipal
# Check our work
Get-MsolRoleMember -RoleObjectId $roleId # => should include Principal.Name in list
|
PowerShellCorpus/GithubGist/mvadstrup_4409388_raw_09e0a538319ba676c1895a9bd8e44da3e56f47a5_gistfile1.ps1
|
mvadstrup_4409388_raw_09e0a538319ba676c1895a9bd8e44da3e56f47a5_gistfile1.ps1
|
#
# Powershell script for adding/removing entries to the hosts file.
#
# Known limitations:
# - does not handle entries with comments afterwards ("<ip> <host> # comment")
#
$file = "C:\Windows\System32\drivers\etc\hosts"
function add-host([string]$filename, [string]$ip, [string]$hostname) {
remove-host $filename $hostname
$ip + "`t`t" + $hostname | Out-File -encoding ASCII -append $filename
}
function remove-host([string]$filename, [string]$hostname) {
$c = Get-Content $filename
$newLines = @()
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
if ($bits[1] -ne $hostname) {
$newLines += $line
}
} else {
$newLines += $line
}
}
# Write file
Clear-Content $filename
foreach ($line in $newLines) {
$line | Out-File -encoding ASCII -append $filename
}
}
function print-hosts([string]$filename) {
$c = Get-Content $filename
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
Write-Host $bits[0] `t`t $bits[1]
}
}
}
try {
if ($args[0] -eq "add") {
if ($args.count -lt 3) {
throw "Not enough arguments for add."
} else {
add-host $file $args[1] $args[2]
}
} elseif ($args[0] -eq "remove") {
if ($args.count -lt 2) {
throw "Not enough arguments for remove."
} else {
remove-host $file $args[1]
}
} elseif ($args[0] -eq "show") {
print-hosts $file
} else {
throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove'."
}
} catch {
Write-Host $error[0]
Write-Host "`nUsage: hosts add <ip> <hostname>`n hosts remove <hostname>`n hosts show"
}
|
PowerShellCorpus/GithubGist/wpsmith_a9d1bb00252bac22cadc_raw_7f99b5beece3446e51143135514a05edcfc74de4_flushBLOBCache.ps1
|
wpsmith_a9d1bb00252bac22cadc_raw_7f99b5beece3446e51143135514a05edcfc74de4_flushBLOBCache.ps1
|
Param(
[string]$webAppURL
)
#Loading SharePoint Powershell Snaping
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
if (!$webAppURL) { $webAppURL = Read-Host "What is the web application's URL?" }
Write-Host "Checking:" $webAppURL
$webApp = Get-SPWebApplication $webAppURL
[Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApp)
Write-Host "Flushed the BLOB cache for:" $webApp
|
PowerShellCorpus/GithubGist/JonasGroeger_301db5e64afdcd90e71e_raw_e084376972e4e0bcdc030e9cacec50e85592832a_Clean-Temporary-Files.ps1
|
JonasGroeger_301db5e64afdcd90e71e_raw_e084376972e4e0bcdc030e9cacec50e85592832a_Clean-Temporary-Files.ps1
|
# ------------------------------------------------------------------------------
# Script: Clean-Temporary-Files.ps1
# Author: Jonas Gröger <jonas.groeger@gmail.com>
# Date: 12.04.2014
# Keywords: LaTeX, Clean, Delete, Remove, Temporary, Files
# Comments: Removes temporary files created by LaTeX etc. You can tweak it by
# adding extensions or specific files.
# ------------------------------------------------------------------------------
Param(
[String] $Folder = $PSScriptRoot # By default, remove from current directory
)
$files_to_delete = @(
"*.aux",
"*.bbl",
"*.bcf",
"*.blg",
"*.brf",
"*.idx",
"*.ilg",
"*.ind",
"*.lof",
"*.log",
"*.lol",
"*.lot",
"*.lpr",
"*.nlo",
"*.nls",
"*.out",
"*.pyg",
"*.run.xml",
"*.synctex",
"*.synctex.gz"
"*.tdo",
"*.toc"
)
$n_files_removed = 0
Get-ChildItem $Folder -Recurse -Include $files_to_delete | foreach ($_) {
Write-Host "Removing $($_ | Resolve-Path -Relative)"
Remove-Item $_.FullName
$n_files_removed++
}
if($n_files_removed -eq 0) {
Write-Host "No files removed from: $Folder"
} else {
Write-Host "$n_files_removed files removed from: $Folder"
}
|
PowerShellCorpus/GithubGist/kyle-herzog_9532722_raw_69ab5932a4bcec8a8e009329b6bdc1e37993e945_Get-SolutionProjects.ps1
|
kyle-herzog_9532722_raw_69ab5932a4bcec8a8e009329b6bdc1e37993e945_Get-SolutionProjects.ps1
|
Add-Type -AssemblyName "EnvDTE"
$vsInstance = [System.Runtime.InteropServices.Marshal]::GetActiveObject("VisualStudio.DTE.11.0")
$dte = $vsInstance.DTE
$solution = $dte.Solution
$soltuion.Projects | Format-List
Write-Host "$($solution.Projects)"
$solution.Projects | Foreach-Object `
{
Write-Host "Project - $($_.Name)"
}
|
PowerShellCorpus/GithubGist/eltone_6979834_raw_5cd7cdc8e008d6cd5a95f8d913c6443023b4c06f_DisableNuGetPackageRestore.ps1
|
eltone_6979834_raw_5cd7cdc8e008d6cd5a95f8d913c6443023b4c06f_DisableNuGetPackageRestore.ps1
|
if(!(Test-Path *.sln)) {
echo ($pwd.Path + " is not a vs solution folder")
}
else {
#remove .nuget folder
Remove-Item .nuget -Recurse
#remove .nuget sln folder
Get-Item *.sln | ForEach-Object {
$c = [System.IO.File]::ReadAllText($_.Fullname)
$c -replace '(?s)Project\("\{2150E333-8FDC-42A3-9474-1A3956D46DE8\}"\) = "\.nuget",.*?EndProjectSection.*?EndProject', "" |
Set-Content $_.FullName
}
#remove package restore from .csproj
Get-Item *\*.csproj | ForEach-Object {
$pc = Get-Content $_ | Where-Object {
$_ -notmatch '<RestorePackages>true</RestorePackages>' -AND $_ -notmatch 'nuget.targets'
}
Set-Content ($_.FullName) $pc
}
}
|
PowerShellCorpus/GithubGist/wpsmith_eaae2a6155357107cbe4_raw_e6e7034bbae8b55f5becef27979927181d64c70a_SP.GetRunningWorkflows.ps1
|
wpsmith_eaae2a6155357107cbe4_raw_e6e7034bbae8b55f5becef27979927181d64c70a_SP.GetRunningWorkflows.ps1
|
Clear-Host
#Start, SP Site URL
$web = Get-SPWeb "https://myrndc.rndc-usa.com/";
$web.AllowUnsafeUpdates = $true;
#Pages List Name
$list = $web.Lists["Pages"];
$count = 0
#Loop through all Items in List then loop through all Workflows on each List Items.
foreach ($listItem in $list.Items) {
foreach ($workflow in $listItem.Workflows) {
#Disregard Completed or Cancelled Workflows
if(($listItem.Workflows |
where-object {$_.InternalState -ne "Completed" -and $_.InternalState -ne "Cancelled"}) -ne $null)
{
#Print Items with Workflows in Progress
#Place cancel command here to cancel ALL
write-output "Workflow :
" $workflow;
write-output "in progress for :
" $listItem.Title;
}
}
}
$web.Dispose();
|
PowerShellCorpus/GithubGist/pavelbinar_7397549_raw_fe50bc3b6ebc9dd2897f1ffd214aecaff6a127fc_gistfile1.ps1
|
pavelbinar_7397549_raw_fe50bc3b6ebc9dd2897f1ffd214aecaff6a127fc_gistfile1.ps1
|
# NPM
npm update
# Ruby gems
gem update
# Homebrew
brew upgrade
# yeoman generators
npm update -g generator-_______
|
PowerShellCorpus/GithubGist/dfinke_4161503_raw_98cf6c46de5365afa7a14275836e056c6f796504_ppm.ps1
|
dfinke_4161503_raw_98cf6c46de5365afa7a14275836e056c6f796504_ppm.ps1
|
param ($key)
<#
# sample package.ps1
@{
start = {1..10}
stuff = "this is stuff"
}
#>
$defaultPackageName = ".\package.ps1"
if(Test-Path $defaultPackageName) {
$package = & $defaultPackageName
if(!$key) {$key="start"}
if(!$package.ContainsKey($key)) {
Write-Error "Cannot find $($key)"
Return
}
$value = $package.$key
switch ($value) {
{$_ -is [Scriptblock]} {&$_}
default {$_}
}
}
|
PowerShellCorpus/GithubGist/jstangroome_5437665_raw_03875cb83bf59017a25fd62019042767236714b1_PSISEAliasExpansion.ps1
|
jstangroome_5437665_raw_03875cb83bf59017a25fd62019042767236714b1_PSISEAliasExpansion.ps1
|
function Expand-Alias {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]
$Code
)
[ref]$CodeErrors = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Management.Automation.PSParseError]
$Tokens = [System.Management.Automation.PSParser]::Tokenize($Code, $CodeErrors)
if ($CodeErrors.Value) {
Write-Error "$($MyInvocation.MyCommand): Error parsing code"
return
}
$NewCode = New-Object -TypeName System.Text.StringBuilder -ArgumentList ($Code.Length * 2)
$Offset = 0
$LastType = $null
foreach ($Token in $Tokens) {
if ($Token.Start -gt $Offset) {
$NewCode.Append($Code.Substring($Offset, $Token.Start - $Offset)) | Out-Null
}
$Content = $Code.Substring($Token.Start, $Token.Length)
if ($Token.Type -eq 'Command') {
$LastCommand = Get-Command -Name $Token.Content |
Where-Object { $_.Name -eq $Token.content }
if ($LastCommand.CommandType -eq 'Alias') {
$Content = $LastCommand.Definition
}
} elseif ($Token.Type -eq 'CommandParameter') {
$ParamName = $Token.Content.Substring(1)
$AliasedParam = $LastCommand.Parameters.Values |
Where-Object { $_.Aliases | Where-Object { $_ -eq $ParamName } }
if ($AliasedParam) {
$Content = '-' + $AliasedParam.Name
} else {
$Params = @(
$LastCommand.Parameters.Values |
Where-Object { $_.Name -like "$ParamName*" }
)
if ($Params.Length -eq 1) {
$Content = '-' + $Params[0].Name
}
}
}
$NewCode.Append($Content) | Out-Null
$Offset = $Token.Start + $Token.Length
$LastType = $Token.Type
}
$NewCode.Append($Code.Substring($Offset)) | Out-Null
$ExpandedCode = $NewCode.ToString()
[System.Management.Automation.PSParser]::Tokenize($ExpandedCode, $CodeErrors) | Out-Null
if ($CodeErrors.Value) {
Write-Error "$($MyInvocation.MyCommand): Error after expanding aliases"
return
}
return $ExpandedCode
}
function Expand-ISEAlias {
$Code = $psISE.CurrentFile.Editor.SelectedText
if ($Code.Length) {
$Code = Expand-Alias -Code $Code
$psISE.CurrentFile.Editor.InsertText($Code)
}
}
if (Get-Variable -Name ExpandIseAliasMenu -ErrorAction SilentlyContinue) {
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Remove($ExpandIseAliasMenu) | Out-Null
}
$ExpandIseAliasMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Expand Alias', { Expand-ISEAlias }, 'Ctrl+Shift+E')
|
PowerShellCorpus/GithubGist/l1x_3642024_raw_9f4cacfb6fc5dd6b33380b986fb552b40f1905ad_GitUtils.ps1
|
l1x_3642024_raw_9f4cacfb6fc5dd6b33380b986fb552b40f1905ad_GitUtils.ps1
|
# Add a key to the SSH agent
function Add-SshKey() {
$sshAdd = Get-Command ssh-add -TotalCount 1 -ErrorAction SilentlyContinue
if (!$sshAdd) { Write-Warning 'Could not find ssh-add'; return }
if ($args.Count -eq 0) {
$sshPath = Resolve-Path ~/.ssh/github_rsa
& $sshAdd $sshPath
} else {
foreach ($value in $args) {
& $sshAdd $value
}
}
|
PowerShellCorpus/GithubGist/taddev_3965431_raw_2ab88b19400f4b9de014b3dfede0a13e08fd45a8_SignCode.ps1
|
taddev_3965431_raw_2ab88b19400f4b9de014b3dfede0a13e08fd45a8_SignCode.ps1
|
#
# Author: Tad DeVries
# Email: taddevries@gmail.com
# FileName: SignCode.ps1
#
# Description:
# Uses a codesigning certifcate in your certificate list
# to sign the code. You may need to edit the options below
# to select the correct certificate if you have more than
# one like I do.
#
#
# Copyright (C) 2011 Tad DeVries
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# License Info: http://www.gnu.org/licenses/gpl-2.0.html
#
#
function SignCode
{
param([string] $FilePath=$(throw "Please specify a filename."))
$cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0]
Set-AuthenticodeSignature -FilePath $FilePath -Certificate $cert -TimestampServer "http://timestamp.verisign.com/scripts/timestamp.dll"
<#
.SYNOPSIS
Sign a script using my valid certificate.
.DESCRIPTION
Sign a script using my valid certificate. Takes any file and adds the certificate in the signature block.
.INPUTS
Any test file containing executable code.
.OUTPUTS
The thumbprint, name, and status of the certificate used.
.EXAMPLE
SignCode example.ps1
.EXAMPLE
sign example.ps1
.LINK
http://splunk.net
#>
}
function SignCodeMultiple
{
$count = @($input).Count;
$input.Reset();
if( $count -eq 0 )
{
echo "Incorrect Input"
}
else
{
foreach( $file in $input )
{
SignCode $file
}
}
<#
.SYNOPSIS
Sign multiple scripts using my valid certificate.
.DESCRIPTION
Sign multiple scripts using my valid certificate. Takes any file and adds the certificate in the signature block.
.INPUTS
Any file containing executable code.
.OUTPUTS
The thumbprint, name, and status of the certificate used.
.EXAMPLE
Get-ChildItem *.ps1 -name | SignCodeMultiple
.EXAMPLE
ls *.ps1 -name | signm
.LINK
http://splunk.net
#>
}
##Set an alias to simplifiy typing
Set-Alias sign SignCode
Set-Alias signm SignCodeMultiple
##export module
Export-ModuleMember -Function * -Alias *
# SIG # Begin signature block
# MIIbaQYJKoZIhvcNAQcCoIIbWjCCG1YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU/BwWnd+KweNMof1cBTfgO/QR
# oRugghYbMIIDnzCCAoegAwIBAgIQeaKlhfnRFUIT2bg+9raN7TANBgkqhkiG9w0B
# AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp
# BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMTIw
# NTAxMDAwMDAwWhcNMTIxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xNDAyBgNVBAMTK1N5bWFudGVjIFRpbWUg
# U3RhbXBpbmcgU2VydmljZXMgU2lnbmVyIC0gRzMwgZ8wDQYJKoZIhvcNAQEBBQAD
# gY0AMIGJAoGBAKlZZnTaPYp9etj89YBEe/5HahRVTlBHC+zT7c72OPdPabmx8LZ4
# ggqMdhZn4gKttw2livYD/GbT/AgtzLVzWXuJ3DNuZlpeUje0YtGSWTUUi0WsWbJN
# JKKYlGhCcp86aOJri54iLfSYTprGr7PkoKs8KL8j4ddypPIQU2eud69RAgMBAAGj
# geMwgeAwDAYDVR0TAQH/BAIwADAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js
# LnZlcmlzaWduLmNvbS90c3MtY2EuY3JsMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMI
# MDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AudmVyaXNp
# Z24uY29tMA4GA1UdDwEB/wQEAwIHgDAeBgNVHREEFzAVpBMwETEPMA0GA1UEAxMG
# VFNBMS0zMB0GA1UdDgQWBBS0t/GJSSZg52Xqc67c0zjNv1eSbzANBgkqhkiG9w0B
# AQUFAAOCAQEAHpiqJ7d4tQi1yXJtt9/ADpimNcSIydL2bfFLGvvV+S2ZAJ7R55uL
# 4T+9OYAMZs0HvFyYVKaUuhDRTour9W9lzGcJooB8UugOA9ZresYFGOzIrEJ8Byyn
# PQhm3ADt/ZQdc/JymJOxEdaP747qrPSWUQzQjd8xUk9er32nSnXmTs4rnykr589d
# nwN+bid7I61iKWavkugszr2cf9zNFzxDwgk/dUXHnuTXYH+XxuSqx2n1/M10rCyw
# SMFQTnBWHrU1046+se2svf4M7IV91buFZkQZXZ+T64K6Y57TfGH/yBvZI1h/MKNm
# oTkmXpLDPMs3Mvr1o43c1bCj6SU2VdeB+jCCA8QwggMtoAMCAQICEEe/GZXfjVJG
# Q/fbbUgNMaQwDQYJKoZIhvcNAQEFBQAwgYsxCzAJBgNVBAYTAlpBMRUwEwYDVQQI
# EwxXZXN0ZXJuIENhcGUxFDASBgNVBAcTC0R1cmJhbnZpbGxlMQ8wDQYDVQQKEwZU
# aGF3dGUxHTAbBgNVBAsTFFRoYXd0ZSBDZXJ0aWZpY2F0aW9uMR8wHQYDVQQDExZU
# aGF3dGUgVGltZXN0YW1waW5nIENBMB4XDTAzMTIwNDAwMDAwMFoXDTEzMTIwMzIz
# NTk1OVowUzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMSsw
# KQYDVQQDEyJWZXJpU2lnbiBUaW1lIFN0YW1waW5nIFNlcnZpY2VzIENBMIIBIjAN
# BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqcqypMzNIK8KfYmsh3XwtE7x38EP
# v2dhvaNkHNq7+cozq4QwiVh+jNtr3TaeD7/R7Hjyd6Z+bzy/k68Numj0bJTKvVIt
# q0g99bbVXV8bAp/6L2sepPejmqYayALhf0xS4w5g7EAcfrkN3j/HtN+HvV96ajEu
# A5mBE6hHIM4xcw1XLc14NDOVEpkSud5oL6rm48KKjCrDiyGHZr2DWFdvdb88qiaH
# XcoQFTyfhOpUwQpuxP7FSt25BxGXInzbPifRHnjsnzHJ8eYiGdvEs0dDmhpfoB6Q
# 5F717nzxfatiAY/1TQve0CJWqJXNroh2ru66DfPkTdmg+2igrhQ7s4fBuwIDAQAB
# o4HbMIHYMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3Au
# dmVyaXNpZ24uY29tMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYDVR0fBDowODA2oDSg
# MoYwaHR0cDovL2NybC52ZXJpc2lnbi5jb20vVGhhd3RlVGltZXN0YW1waW5nQ0Eu
# Y3JsMBMGA1UdJQQMMAoGCCsGAQUFBwMIMA4GA1UdDwEB/wQEAwIBBjAkBgNVHREE
# HTAbpBkwFzEVMBMGA1UEAxMMVFNBMjA0OC0xLTUzMA0GCSqGSIb3DQEBBQUAA4GB
# AEpr+epYwkQcMYl5mSuWv4KsAdYcTM2wilhu3wgpo17IypMT5wRSDe9HJy8AOLDk
# yZNOmtQiYhX3PzchT3AxgPGLOIez6OiXAP7PVZZOJNKpJ056rrdhQfMqzufJ2V7d
# uyuFPrWdtdnhV/++tMV+9c8MnvCX/ivTO1IbGzgn9z9KMIIGcDCCBFigAwIBAgIB
# JDANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD
# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln
# bmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkw
# HhcNMDcxMDI0MjIwMTQ2WhcNMTcxMDI0MjIwMTQ2WjCBjDELMAkGA1UEBhMCSUwx
# FjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFs
# IENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIg
# UHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0IENBMIIBIjANBgkqhkiG9w0BAQEF
# AAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J0D8MlzgWKbr4fYlbRVjvhHDtfhFN
# 6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSjId6ZNavcSa6/McVnhDAQm+8H3HWo
# D030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckRZfpJB2Kfk6aHqW3JnSvRe+XVZSuf
# DVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoUTZ65+c0H4paR8c8eK/mC914mBo6N
# 0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sCpttLVlIjnkuY4r9+zvqhToPjxcfD
# YEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbVuUOw7wIDAQABo4IB6TCCAeUwDwYD
# VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFNBOD0CZbLhL
# GW87KLjg44gHNKq3MB8GA1UdIwQYMBaAFE4L7xqkQFulF2mHMMo0aEPQQa7yMD0G
# CCsGAQUFBwEBBDEwLzAtBggrBgEFBQcwAoYhaHR0cDovL3d3dy5zdGFydHNzbC5j
# b20vc2ZzY2EuY3J0MFsGA1UdHwRUMFIwJ6AloCOGIWh0dHA6Ly93d3cuc3RhcnRz
# c2wuY29tL3Nmc2NhLmNybDAnoCWgI4YhaHR0cDovL2NybC5zdGFydHNzbC5jb20v
# c2ZzY2EuY3JsMIGABgNVHSAEeTB3MHUGCysGAQQBgbU3AQIBMGYwLgYIKwYBBQUH
# AgEWImh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwNAYIKwYBBQUH
# AgEWKGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2ludGVybWVkaWF0ZS5wZGYwEQYJ
# YIZIAYb4QgEBBAQDAgABMFAGCWCGSAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAy
# IFByaW1hcnkgSW50ZXJtZWRpYXRlIE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRl
# czANBgkqhkiG9w0BAQUFAAOCAgEAcnMLA3VaN4OIE9l4QT5OEtZy5PByBit3oHiq
# QpgVEQo7DHRsjXD5H/IyTivpMikaaeRxIv95baRd4hoUcMwDj4JIjC3WA9FoNFV3
# 1SMljEZa66G8RQECdMSSufgfDYu1XQ+cUKxhD3EtLGGcFGjjML7EQv2Iol741rEs
# ycXwIXcryxeiMbU2TPi7X3elbwQMc4JFlJ4By9FhBzuZB1DV2sN2irGVbC3G/1+S
# 2doPDjL1CaElwRa/T0qkq2vvPxUgryAoCppUFKViw5yoGYC+z1GaesWWiP1eFKAL
# 0wI7IgSvLzU3y1Vp7vsYaxOVBqZtebFTWRHtXjCsFrrQBngt0d33QbQRI5mwgzEp
# 7XJ9xu5d6RVWM4TPRUsd+DDZpBHm9mszvi9gVFb2ZG7qRRXCSqys4+u/NLBPbXi/
# m/lU00cODQTlC/euwjk9HQtRrXQ/zqsBJS6UJ+eLGw1qOfj+HVBl/ZQpfoLk7IoW
# lRQvRL1s7oirEaqPZUIWY/grXq9r6jDKAp3LZdKQpPOnnogtqlU4f7/kLjEJhrrc
# 98mrOWmVMK/BuFRAfQ5oDUMnVmCzAzLMjKfGcVW/iMew41yfhgKbwpfzm3LBr1Zv
# +pEBgcgW6onRLSAn3XHM0eNtz+AkxH6rRf6B2mYhLEEGLapH8R1AMAo4BbVFOZR5
# kXcMCwowggg4MIIHIKADAgECAgIHqTANBgkqhkiG9w0BAQUFADCBjDELMAkGA1UE
# BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE
# aWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENs
# YXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0IENBMB4XDTEyMTAxMDIz
# MzU0OFoXDTE0MTAxMzAwMjE0MFowgY8xGTAXBgNVBA0TEFMzRUM3Yzh4Y1lOMnBQ
# cXUxCzAJBgNVBAYTAlVTMRUwEwYDVQQIEwxTb3V0aCBEYWtvdGExEzARBgNVBAcT
# ClJhcGlkIENpdHkxFDASBgNVBAMTC1RhZCBEZVZyaWVzMSMwIQYJKoZIhvcNAQkB
# FhR0YWRkZXZyaWVzQGdtYWlsLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC
# AgoCggIBAKb2chsYUh+l9MhIyQc+TczABVRO4rU3YOwu1t0gybek1d0KacGTtD/C
# SFWutUsrfVHWb2ybUiaTN/+P1ChqtnS4Sq/pyZ/UcBzOUoFEFlIOv5NxTjv7gm2M
# pR6LwgYx2AyfdVYpAfcbmAH0wXfgvA3i6y9PEAlVEHq3gf11Hf1qrQKKD+k7ZMHG
# ozQhmtQ9MxfF4VCG9NNSU/j7TXJG+j7sxlG0ADxwjMo+iA7R1ANs6N2seOnvcNvQ
# a3YP4SwHv0hUgz9KBXHXCdA7LG8lGlLp4s0bbyPxagZ1+Of0qnTyG4yq5qij8Wsa
# xAasi1sRYM6rO6Dn5ISaIF1lJmQIOYPezivKenDc3o9yjbb4jPDUjT7M2iK+VRfc
# FPEbcxHJ+FpUAvTYPOEeDO2LkriuRvUkkMTYiXWpqUVojLk3JDlcCRkE5cykIMdX
# irx82lxQpiZGkFrfrGQPMi6DAALX85ZUiDQ10iGyXANtubJkhAnp5hn4Q5JA4tpR
# ty6MlZh94TjeFlbXq9Y2phRi3AWqunOMAxX8gSHfbrmAa7gNkaBoVZd2tlVrV1X+
# lnnnb3yO0SuErx3bfhS++MgrisERscGgcY+vB5trw05FMGfK5YkzWZF2eIE/m70T
# 2rfmH9tUnElgJHTqEu4L8txmnNZ/j8ZzyLNY5+n8XqGghtTqeIxLAgMBAAGjggOd
# MIIDmTAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDAuBgNVHSUBAf8EJDAiBggr
# BgEFBQcDAwYKKwYBBAGCNwIBFQYKKwYBBAGCNwoDDTAdBgNVHQ4EFgQU/zkKtNmi
# KcWBOqQkxr6qsIyjrGUwHwYDVR0jBBgwFoAU0E4PQJlsuEsZbzsouODjiAc0qrcw
# ggIhBgNVHSAEggIYMIICFDCCAhAGCysGAQQBgbU3AQICMIIB/zAuBggrBgEFBQcC
# ARYiaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9saWN5LnBkZjA0BggrBgEFBQcC
# ARYoaHR0cDovL3d3dy5zdGFydHNzbC5jb20vaW50ZXJtZWRpYXRlLnBkZjCB9wYI
# KwYBBQUHAgIwgeowJxYgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkw
# AwIBARqBvlRoaXMgY2VydGlmaWNhdGUgd2FzIGlzc3VlZCBhY2NvcmRpbmcgdG8g
# dGhlIENsYXNzIDIgVmFsaWRhdGlvbiByZXF1aXJlbWVudHMgb2YgdGhlIFN0YXJ0
# Q29tIENBIHBvbGljeSwgcmVsaWFuY2Ugb25seSBmb3IgdGhlIGludGVuZGVkIHB1
# cnBvc2UgaW4gY29tcGxpYW5jZSBvZiB0aGUgcmVseWluZyBwYXJ0eSBvYmxpZ2F0
# aW9ucy4wgZwGCCsGAQUFBwICMIGPMCcWIFN0YXJ0Q29tIENlcnRpZmljYXRpb24g
# QXV0aG9yaXR5MAMCAQIaZExpYWJpbGl0eSBhbmQgd2FycmFudGllcyBhcmUgbGlt
# aXRlZCEgU2VlIHNlY3Rpb24gIkxlZ2FsIGFuZCBMaW1pdGF0aW9ucyIgb2YgdGhl
# IFN0YXJ0Q29tIENBIHBvbGljeS4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2Ny
# bC5zdGFydHNzbC5jb20vY3J0YzItY3JsLmNybDCBiQYIKwYBBQUHAQEEfTB7MDcG
# CCsGAQUFBzABhitodHRwOi8vb2NzcC5zdGFydHNzbC5jb20vc3ViL2NsYXNzMi9j
# b2RlL2NhMEAGCCsGAQUFBzAChjRodHRwOi8vYWlhLnN0YXJ0c3NsLmNvbS9jZXJ0
# cy9zdWIuY2xhc3MyLmNvZGUuY2EuY3J0MCMGA1UdEgQcMBqGGGh0dHA6Ly93d3cu
# c3RhcnRzc2wuY29tLzANBgkqhkiG9w0BAQUFAAOCAQEAMDdkGhWaFooFqzWBaA/R
# rf9KAQOeFSLoJrgZ+Qua9vNHrWq0TGyzH4hCJSY4Owurl2HCI98R/1RNYDWhQ0+1
# dK6HZ/OmKk7gsbQ5rqRnRqMT8b2HW7RVTVrJzOOj/QdI+sNKI5oSmTS4YN4LRmvP
# MWGwbPX7Poo/QtTJAlxXkeEsLN71fabQsavjjJORaDXDqgd6LydG7yJOlLzs2zDr
# dSBOZnP8VD9seRIZtMWqZH2tGZp3YBQSTWq4BySHdsxsIgZVZnWi1HzSjUTMtbcl
# P/CKtZKBCS7FPHJNcACouOQbA81aOjduUtIVsOnulVGT/i72Grs607e5m+Z1f4pU
# FjGCBLgwggS0AgEBMIGTMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD
# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln
# bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk
# aWF0ZSBPYmplY3QgQ0ECAgepMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3AgEMMQow
# CKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisGAQQBgjcC
# AQsxDjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBS3MM5hUfh47C7iwjPF
# S+Wj9EA89DANBgkqhkiG9w0BAQEFAASCAgCF7V0fbPuIVbirzh5Sq/KJpLY516UW
# vjDCqCBe53Mi2NUo754nWRwugOsnwvpYEC750mSYuOhYqsWXyHrBid19TXzG47Dx
# RViiA/X0v3v5KCJ0KKUTZ4Ba/J1whL7Kvm8OE/oXN/DYQU9oFOxIxgWQRd1RzdVL
# BCK7gxlPf2CPOum+vZTbbMshgtBEWV37WBFqsQWi6sOyPQuH4/bdldJEMkGFozRS
# n7gUDLd4jf0kK54urJ11JF1DD2ORjkt2M4hOnw2ySD+DKQJH2uA626dYcR99nR5d
# qv3iL6IVT4Ev1ugWV2qM0Ulmve0zjRvG/3K3s4NJzSz70RYaQX1iStStcyxVbZ/b
# dceJftc6O4anYQOfd0NGXmcNDac2+ELdLw0Hp0RnmThBZ0LG+W7UzzA+synI5PGT
# CMKI56XzPBLd7BCKWuXylqSbgpPBp739Nu6g3pcpZh8yfnFP4QbA7pOypj3j/1Ft
# I0j6fS/Xb7iOCLoaFuBHumFDCehuJDfVbHtoqxvpldcIC27a/f19JsPmht0OSUJR
# TwPeQJO3+T8MbPToMyzn0UHJPAMIDJaOK/MMlhiIvwyNS1/D9nbf2aibvQysX77g
# P/8/2vr8n/QPEmSBuO0WoZWXgcEuf1wpg/7xokzT12k3c0AbwLdn+6pP2BPdENtP
# Xp/B5PKDZDn9AKGCAX8wggF7BgkqhkiG9w0BCQYxggFsMIIBaAIBATBnMFMxCzAJ
# BgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjErMCkGA1UEAxMiVmVy
# aVNpZ24gVGltZSBTdGFtcGluZyBTZXJ2aWNlcyBDQQIQeaKlhfnRFUIT2bg+9raN
# 7TAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG
# 9w0BCQUxDxcNMTIxMDI3MDI0NzIxWjAjBgkqhkiG9w0BCQQxFgQUR+U1tuc1OUPX
# OnzJzCqWXCVFu4UwDQYJKoZIhvcNAQEBBQAEgYB6QVRrZ8ndKa9ZRSV0CDfgTKYH
# 0l6zjHhO6UYNoR5OdhKZcp+uYb9eLmHqOZ6ACwYlai1nWOUC3altS4EnmKMd9Sjy
# ppZPZgrkGIGstCsS9hbiT/6YzVIaDwl7fxf6gclfV3gqh10U4TGOx95IbGBE3epX
# ej4bEW/b3CjWueyGFA==
# SIG # End signature block
|
PowerShellCorpus/GithubGist/tkmtmkt_2490903_raw_a401aae0d6fac1bb951c5304f6a3af46b122ab08_CollectVersionInfo.ps1
|
tkmtmkt_2490903_raw_a401aae0d6fac1bb951c5304f6a3af46b122ab08_CollectVersionInfo.ps1
|
<#
.SYNOPSIS
ソフトウェアのバージョン情報を収集する
#>
$ps1_file = &{$myInvocation.ScriptName}
$base_dir = Split-Path (Split-Path $ps1_file)
$log_dir = "$base_dir\log"
$log_file = "$log_dir\$((Split-Path -Leaf $ps1_file).Replace(".ps1",".log"))"
if (-not (Test-Path "$log_dir")) {New-Item "$log_dir" -Force -ItemType Directory}
<#
.SYNOPSIS
メイン処理
#>
$tmp = $Host.UI.RawUI.WindowSize
$tmp.Width = 120
$Host.UI.RawUI.WindowSize = $tmp
Start-Transcript $log_file -Append
$csv_file = "$base_dir\conf\computers.csv"
$computers = ConvertFrom-Csv (cat $csv_file)
$outdir = "version_$(Get-Date -f "yyyyMMdd")"
if (-not (Test-Path $outdir)) {New-Item $outdir -Force -ItemType Directory}
# ソフトウェアバージョン情報を取得するジョブを発行する
$jobs = $computers | %{
$job = gwmi Win32_Product -AsJob -ComputerName $_.IPAddress
$job.Name = $_.COMPUTERNAME
$job
}
# ジョブの実行結果を受け取る
Wait-Job $jobs | %{
$job = $_
Write-Host "$($job.Name) : $($job.State)"
if ($_.HasMoreData) {
Receive-Job $job |
select IdentifyingNumber,Name,Vendor,Version,Caption |
sort Vender,Name |
Export-CSV "$outdir\$($job.Name).csv" -Encoding OEM -NoTypeInformation
}
}
Remove-Job $jobs
Stop-Transcript
# vim: set ft=ps1 ts=4 sw=4 et:
|
PowerShellCorpus/GithubGist/ao-zkn_0cd187ef790d67321e47_raw_febe76d13c102143fe6e121b1b28783899e1b2a1_Get-URLDecode.ps1
|
ao-zkn_0cd187ef790d67321e47_raw_febe76d13c102143fe6e121b1b28783899e1b2a1_Get-URLDecode.ps1
|
# ------------------------------------------------------------------
# 指定した文字コードより、文字列をURLデコードする
# 関数名:Get-URLDecode
# 引数 :VALUE URLデコードする文字列
# :ENCODING 文字コード
# 戻り値:URLデコードした文字列
# ------------------------------------------------------------------
function Get-URLDecode([String]$VALUE, [String]$ENCODING){
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web")
$enc= [System.Text.Encoding]::GetEncoding($ENCODING)
return [System.Web.HttpUtility]::UrlDecode($VALUE,$enc)
}
|
PowerShellCorpus/GithubGist/heedfull_4bf8e4f1a8328fbe8da8_raw_6c86678dc0f2b542e5bb0e8cadfcaba00d643578_GetLastestLogFile.ps1
|
heedfull_4bf8e4f1a8328fbe8da8_raw_6c86678dc0f2b542e5bb0e8cadfcaba00d643578_GetLastestLogFile.ps1
|
# Set where you want the Logs to be copied to
$to = "D:\Temp\Logs\"
# Create that folder if it doesn't exist
New-Item -Force $to -ItemType directory
# Get rid of all the files in that folder
Remove-Item $to\*
(1..4)| % {"\\Server{0:00}\d$\LogFiles\" -F $_ | %{if(Test-Path $_ ){$_ }else{}} | gci | sort LastWriteTime | select -last 1 | copy -Destination $to }
|
PowerShellCorpus/GithubGist/andyrat33_9019899_raw_4d2db19e378cf9c51008bbfc95922ac22577a843_oclhashcatbenchmark.ps1
|
andyrat33_9019899_raw_4d2db19e378cf9c51008bbfc95922ac22577a843_oclhashcatbenchmark.ps1
|
$allHashTypes = get-content -Path C:\files\oclhashcathashtypes.txt | foreach {"$(($_ -split '=')[0])"} | foreach {$_.trim()}
$exclusions = Get-Content -Path c:\files\exclusions.txt | foreach {$_.trim()}
$exe="C:\Users\Administrator\Downloads\oclhashcat\oclHashcat-1.01\oclhashcat64.exe"
$arg1 = "-m"
$arg3 = "-b"
foreach ($hashType in $(Compare-Object $allHashTypes $exclusions -PassThru))
{
$allArgs = @($arg1,$hashType,$arg3)
$result = iex "&$exe $allArgs"
$test =""
$speed=""
foreach ($line in $result)
{
if ($line.contains("Hashtype"))
{$test = $line.replace("Hashtype: ","").trim()}
if ($line.contains("Speed"))
{
$speed = $line.replace("Speed.GPU.#1.:","").trim()
write-host "$hashType, $test, $speed"
}
}
}
|
PowerShellCorpus/GithubGist/sunnyc7_8694149_raw_420e8f279baee62bb9042eb61ead0e9bb3d72fe3_Invoke-CommandAST.ps1
|
sunnyc7_8694149_raw_420e8f279baee62bb9042eb61ead0e9bb3d72fe3_Invoke-CommandAST.ps1
|
#requires -Version 3
#Usage:
#Invoke-command -computername $server -scriptblock {FunctionName -param1 -param2}
# Author: Matt Graeber
# @mattifestation
# www.exploit-monday.com
function Invoke-Command
{
[CmdletBinding(DefaultParameterSetName='InProcess', HelpUri='http://go.microsoft.com/fwlink/?LinkID=135225', RemotingCapability='OwnedByCommand')]
param(
[Parameter(ParameterSetName='FilePathRunspace', Position=0)]
[Parameter(ParameterSetName='Session', Position=0)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Runspaces.PSSession[]]
${Session},
[Parameter(ParameterSetName='FilePathComputerName', Position=0)]
[Parameter(ParameterSetName='ComputerName', Position=0)]
[Alias('Cn')]
[ValidateNotNullOrEmpty()]
[string[]]
${ComputerName},
[Parameter(ParameterSetName='Uri', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='FilePathUri', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='ComputerName', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='FilePathComputerName', ValueFromPipelineByPropertyName=$true)]
[pscredential]
[System.Management.Automation.CredentialAttribute()]
${Credential},
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='FilePathComputerName')]
[ValidateRange(1, 65535)]
[int]
${Port},
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='FilePathComputerName')]
[switch]
${UseSSL},
[Parameter(ParameterSetName='FilePathComputerName', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='ComputerName', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='FilePathUri', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='Uri', ValueFromPipelineByPropertyName=$true)]
[string]
${ConfigurationName},
[Parameter(ParameterSetName='ComputerName', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='FilePathComputerName', ValueFromPipelineByPropertyName=$true)]
[string]
${ApplicationName},
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='Session')]
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='FilePathRunspace')]
[Parameter(ParameterSetName='FilePathUri')]
[Parameter(ParameterSetName='Uri')]
[int]
${ThrottleLimit},
[Parameter(ParameterSetName='Uri', Position=0)]
[Parameter(ParameterSetName='FilePathUri', Position=0)]
[Alias('URI','CU')]
[ValidateNotNullOrEmpty()]
[uri[]]
${ConnectionUri},
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='Uri')]
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='FilePathRunspace')]
[Parameter(ParameterSetName='FilePathUri')]
[Parameter(ParameterSetName='Session')]
[switch]
${AsJob},
[Parameter(ParameterSetName='Uri')]
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='FilePathUri')]
[Parameter(ParameterSetName='ComputerName')]
[Alias('Disconnected')]
[switch]
${InDisconnectedSession},
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='ComputerName')]
[ValidateNotNullOrEmpty()]
[string[]]
${SessionName},
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='Session')]
[Parameter(ParameterSetName='FilePathRunspace')]
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='FilePathUri')]
[Parameter(ParameterSetName='Uri')]
[Alias('HCN')]
[switch]
${HideComputerName},
[Parameter(ParameterSetName='Session')]
[Parameter(ParameterSetName='FilePathRunspace')]
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='FilePathUri')]
[Parameter(ParameterSetName='Uri')]
[string]
${JobName},
[Parameter(ParameterSetName='Session', Mandatory=$true, Position=1)]
[Parameter(ParameterSetName='Uri', Mandatory=$true, Position=1)]
[Parameter(ParameterSetName='InProcess', Mandatory=$true, Position=0)]
[Parameter(ParameterSetName='ComputerName', Mandatory=$true, Position=1)]
[Alias('Command')]
[ValidateNotNull()]
[scriptblock]
${ScriptBlock},
[Parameter(ParameterSetName='InProcess')]
[switch]
${NoNewScope},
[Parameter(ParameterSetName='FilePathUri', Mandatory=$true, Position=1)]
[Parameter(ParameterSetName='FilePathComputerName', Mandatory=$true, Position=1)]
[Parameter(ParameterSetName='FilePathRunspace', Mandatory=$true, Position=1)]
[Alias('PSPath')]
[ValidateNotNull()]
[string]
${FilePath},
[Parameter(ParameterSetName='Uri')]
[Parameter(ParameterSetName='FilePathUri')]
[switch]
${AllowRedirection},
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='Uri')]
[Parameter(ParameterSetName='FilePathUri')]
[System.Management.Automation.Remoting.PSSessionOption]
${SessionOption},
[Parameter(ParameterSetName='Uri')]
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='FilePathUri')]
[System.Management.Automation.Runspaces.AuthenticationMechanism]
${Authentication},
[Parameter(ParameterSetName='FilePathComputerName')]
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='Uri')]
[Parameter(ParameterSetName='FilePathUri')]
[switch]
${EnableNetworkAccess},
[Parameter(ValueFromPipeline=$true)]
[psobject]
${InputObject},
[Alias('Args')]
[System.Object[]]
${ArgumentList},
[Parameter(ParameterSetName='ComputerName')]
[Parameter(ParameterSetName='Uri')]
[string]
${CertificateThumbprint})
begin
{
function Get-ScriptblockFunctions
{
Param (
[Parameter(Mandatory=$True)]
[ValidateNotNull()]
[Scriptblock]
$Scriptblock
)
# Return all user-defined function names contained within the supplied scriptblock
$Scriptblock.Ast.FindAll({$args[0] -is [Management.Automation.Language.CommandAst]}, $True) |
% { $_.CommandElements[0] } | Sort-Object Value -Unique | ForEach-Object { $_.Value } |
? { ls Function:\$_ -ErrorAction Ignore }
}
function Get-FunctionDefinition
{
Param (
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String[]]
[ValidateScript({Get-Command $_})]
$FunctionName
)
BEGIN
{
# We want to output a single string versus an array of strings
$FunctionCollection = ''
}
PROCESS
{
foreach ($Function in $FunctionName)
{
$FunctionInfo = Get-Command $Function
$FunctionCollection += "function $($FunctionInfo.Name) {`n$($FunctionInfo.Definition)`n}`n"
}
}
END
{
$FunctionCollection
}
}
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Invoke-Command', [System.Management.Automation.CommandTypes]::Cmdlet)
if($PSBoundParameters['ScriptBlock'])
{
$FunctionDefinitions = Get-ScriptblockFunctions $ScriptBlock | Get-FunctionDefinition
$PSBoundParameters['ScriptBlock'] = [ScriptBlock]::Create($FunctionDefinitions + $ScriptBlock.ToString())
}
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Invoke-Command
.ForwardHelpCategory Cmdlet
#>
}
|
PowerShellCorpus/GithubGist/mehmetkut_4f60d16568b54a9442b6_raw_5d0e7a36102c43c7d58dece494fbee69a5e8516e_ResetAzureVMCredentials.ps1
|
mehmetkut_4f60d16568b54a9442b6_raw_5d0e7a36102c43c7d58dece494fbee69a5e8516e_ResetAzureVMCredentials.ps1
|
<# --------------------------
Azure VM şifresini sıfırlamak için
Mehmet Kut
mail@mehmetkut.com
---------------------------- #>
Import-AzurePublishSettingsFile C:\AzureScripts\30-1-2015-credentials.publishsettings
Get-AzureSubscription
$adminCredentials = Get-Credential -Message "Yeni Giriş Bilgileri"
(Get-AzureVM) |
Where-Object -Property Status -EQ "ReadyRole" |
Select-Object -Property Name, ServiceName |
Out-GridView -Title "VM Seçiniz…" -PassThru |
ForEach-Object {
$VM = Get-AzureVM -Name $_.Name -ServiceName $_.ServiceName
If ($VM.VM.ProvisionGuestAgent) {
Set-AzureVMAccessExtension -VM $VM `
-UserName $adminCredentials.UserName `
-Password $adminCredentials.GetNetworkCredential().Password `
-ReferenceName "VMAccessAgent" |
Update-AzureVM
Restart-AzureVM -ServiceName $VM.ServiceName -Name $VM.Name
} else {
Write-Output "$($VM.Name): VM Agent kurulu değil"
}
}
|
PowerShellCorpus/GithubGist/pkirch_678cdf7b596f1f8c9bb0_raw_5231ac3e8b977f2ae886f95c34af1d896bd1e97f_Get-AzureVM-Sample.ps1
|
pkirch_678cdf7b596f1f8c9bb0_raw_5231ac3e8b977f2ae886f95c34af1d896bd1e97f_Get-AzureVM-Sample.ps1
|
Get-AzureVM
<# Output
ServiceName Name Status
----------- ---- ------
leasetest host1 ReadyRole
leasetest2 host2 RoleStateUnknown
leasetest3 host3 StoppedDeallocated
leasetest4 host4 StoppedDeallocated
leasetest5 host5 StoppedDeallocated
#>
|
PowerShellCorpus/GithubGist/wiliammbr_88718fc7de3ab76f8d0b_raw_675dd1c0717632fed0b8a6837d2d1c91feb23300_GetErrorByCorrelationID.ps1
|
wiliammbr_88718fc7de3ab76f8d0b_raw_675dd1c0717632fed0b8a6837d2d1c91feb23300_GetErrorByCorrelationID.ps1
|
# Comando para visualizar erros
get-splogevent | ?{$_.Correlation -eq "{CorrelationId}"} | select Area, Category, Level, EventID, Message | Format-List > C:\filename.log
# Exemplo real
get-splogevent | ?{$_.Correlation -eq "bf16df13-48c8-4c45-8fc7-1c855599c7a3"} | select Area, Category, Level, EventID, Message | Format-List > C:\log_today.log
|
PowerShellCorpus/GithubGist/josheinstein_2586345_raw_0d2258a8351f4830626e6fec72f3fd1796d77c3b_Enable-AppearOffline.ps1
|
josheinstein_2586345_raw_0d2258a8351f4830626e6fec72f3fd1796d77c3b_Enable-AppearOffline.ps1
|
$ErrorActionPreference = 'Stop'
try {
$LyncPolicyKey = 'HKLM:\Software\Policies\Microsoft\Communicator'
if (!(Test-Path $LyncPolicyKey)) {
New-Item $LyncPolicyKey
}
Set-ItemProperty $LyncPolicyKey EnableAppearOffline -Value 1
}
catch {
Write-Warning "Could not set the appropriate registry keys. Be sure PowerShell is running as an administrator."
}
|
PowerShellCorpus/GithubGist/rchaganti_68a2bb55ed015d19385e_raw_fc0c10a3d66f2690207c1910c669cd441105de05_Get-AzurePowerShellMSI.ps1
|
rchaganti_68a2bb55ed015d19385e_raw_fc0c10a3d66f2690207c1910c669cd441105de05_Get-AzurePowerShellMSI.ps1
|
Function Test-Url {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[String] $Url
)
Process {
if ([system.uri]::IsWellFormedUriString($Url,[System.UriKind]::Absolute)) {
$true
} else {
$false
}
}
}
Function Get-AzurePowerShellMSI {
[CmdletBinding()]
param (
[String]$Url = 'https://github.com/Azure/azure-powershell/releases',
[Switch]$DownloadLatest,
[String]$DownloadPath = "$env:USERPROFILE\Downloads",
[Switch]$Passthru
)
Process {
$Msi = @()
$doc = Invoke-WebRequest -Uri $Url
foreach ($href in ($doc.links.href -ne '')) {
if ((Test-Url -Url $href) -and $href.EndsWith('.msi')) {
$Msi += New-Object -TypeName PSObject -Property @{
"Url" = $href
"Version" = ([Regex]::Match($href,'\bv?[0-9]+\.[0-9]+\.[0-9]+(?:\.[0-9]+)?\b')).Value
}
}
}
if ($DownloadLatest) {
if (-not (Test-Path $DownloadPath -PathType Container)) {
Write-Warning "${DownloadPath} does not exist. Creating it ..."
New-Item -Path $DownloadPath -ItemType Directory -ErrorAction Stop | Out-Null
}
$MsiFullPath = "${DownloadPath}\$(Split-Path -Path $Msi[0].Url -Leaf)"
if (-not (Test-Path -Path $MsiFullPath)) {
Write-Verbose "Starting MSI download from $($Msi[0].Url)"
Start-BitsTransfer -Source $Msi[0].Url -Destination $MsiFullPath -ErrorAction Stop
} else {
Write-Warning ("{0} already exists at {1}. No action needed." -f $MsiFullPath, $DownloadPath)
}
if ($Passthru) {
return $MsiFullPath
}
} else {
$Msi
}
}
}
|
PowerShellCorpus/GithubGist/babadofar_11193668_raw_0885a1585676955807db1fd6ba83a9ca40ca3840_gistfile1.ps1
|
babadofar_11193668_raw_0885a1585676955807db1fd6ba83a9ca40ca3840_gistfile1.ps1
|
param ([Parameter(Mandatory=$true)][string]$query)
$con = New-Object -TypeName System.Data.OleDb.OleDbConnection
$con.ConnectionString = "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"
$con.Open()
$cmd = $con.CreateCommand()
$query = "SELECT Top 5 System.ItemPathDisplay FROM SYSTEMINDEX WHERE contains(*, '$($query)*') AND System.Kind = 'email'"
$cmd.CommandText = $query
$rdr = $cmd.ExecuteReader()
while ($rdr.Read()) {
Write-Host $rdr[0]
}
$rdr.Close()
$con.Close()
|
PowerShellCorpus/GithubGist/jonsagara_992625_raw_e48e42129e720199c1f774f57f41dd2ab3063759_Pinger.ps1
|
jonsagara_992625_raw_e48e42129e720199c1f774f57f41dd2ab3063759_Pinger.ps1
|
# -------------------------------------------------------------------------------------------------
# Pinger.ps1
#
# Repeatedly pings the specified server until the ping is successful.
# -------------------------------------------------------------------------------------------------
# Script params
param([String]$server)
# Script param validation
if ([String]::IsNullOrEmpty($server)) {
throw "You must specify a `$server to ping"
}
$pingOutput = @()
while ($pingOutput.Length -eq 0) {
Write-Host "Pinging $server..."
$pingOutput = @((ping $server -n 2) | where { $_ -match "TTL=[\d]{1,}" })
}
Write-Host "$server pinged successfully."
# Send an email notifying that the server is back online
$smtpClient = New-Object Net.Mail.SmtpClient
$smtpClient.Host = "smtp.example.com"
$currentUser = $env:UserName
$from = "$currentUser@example.com"
$to = "$currentUser@example.com"
$title = "$server was pinged successfully, and appears to be back up"
$body = "$server was pinged successfully, and appears to be back up"
$smtpClient.Send($from, $to, $title, $body)
|
PowerShellCorpus/GithubGist/kurukurupapa_5635973_raw_897a2fb0ece6dfa7e64e7b14178ccabbe2f41299_EchoFunc.ps1
|
kurukurupapa_5635973_raw_897a2fb0ece6dfa7e64e7b14178ccabbe2f41299_EchoFunc.ps1
|
# Windows PowerShell
# 引数またはパイプライン入力を受け付けるスクリプトの練習です。
function U-Echo() {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true, Mandatory=$true)] #パイプライン入力を受け取る。必須。
[ValidateNotNull()] #NULL不可
[string[]]$InputString
)
process {
$InputString | %{
"Echo:[$_]"
}
}
}
|
PowerShellCorpus/GithubGist/pipin68k_7916984b1cbb880c2e70_raw_83ead8ee0c1defb509b987712754437ab5e42f0d_Timetaken.ps1
|
pipin68k_7916984b1cbb880c2e70_raw_83ead8ee0c1defb509b987712754437ab5e42f0d_Timetaken.ps1
|
Read-ApacheLog *.log|
?{($_.Status -eq 200) -and ($_.Path -like "*.php")}|
Group-Object Date|
%{
$m = $_ | select -ExpandProperty Group | measure -Property TimeTaken -Average -Maximum -Minimum
$_ | Add-Member Average $m.Average
$_ | Add-Member Max $m.Maximum
$_ | Add-Member Min $m.Minimum
$_
}|
select Name, Count, Average, Max, Min|
ft -AutoSize
|
PowerShellCorpus/GithubGist/wendelb_1c364bb1a36ca5916ca4_raw_5f650adae09dfb1468fa0a0a410bac98c1816eab_logoff.ps1
|
wendelb_1c364bb1a36ca5916ca4_raw_5f650adae09dfb1468fa0a0a410bac98c1816eab_logoff.ps1
|
#
# This background job automatically locks your Workstation after a specified amount of
# time. It will come in handy if you cannot access the screensaver settings due to policy
# restriction but want to lock your screen after a idle timeout. Or you could just
# press [Win]+[L] everytime you leave your desk ;) .
#
# start with
# powershell.exe -windowstyle hidden -executionpolicy Unrestricted P:\ATH\TO\logoff.ps1
#
# `-windowstyle hidden` will make your PowerShell disappear/run in background
# `-executionpolicy Unrestricted` will enable this PowerShell process to allow non-signed scripts
#
# This is the only setting: How long before locking?
# Alternative Options:
# * -Seconds 10 ( = 10 Seconds)
# * -Minutes 10 ( = 10 Minutes)
# * -Hours 10 ( = 10 Hours)
#
$idle_timeout = New-TimeSpan -Minutes 10
# DO NOT CHANGE ANYTHING BELOW THIS LINE
####################################################################################################################################################################
# This snippet is from http://stackoverflow.com/a/15846912
Add-Type @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PInvoke.Win32 {
public static class UserInput {
[DllImport("user32.dll", SetLastError=false)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO {
public uint cbSize;
public int dwTime;
}
public static DateTime LastInput {
get {
DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
return lastInput;
}
}
public static TimeSpan IdleTime {
get {
return DateTime.UtcNow.Subtract(LastInput);
}
}
public static int LastInputTicks {
get {
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
GetLastInputInfo(ref lii);
return lii.dwTime;
}
}
}
}
'@
#End snippet
# Helper: Is currently locked?
$locked = 0;
do {
# 1st: How long is your computer currently idle?
$idle_time = [PInvoke.Win32.UserInput]::IdleTime;
#Write-Host ("Idle for " + $idle_time);
# Your computer is not locked, but idle time is longer than allowed? -> Lock it!
if (($locked -eq 0) -And ($idle_time -gt $idle_timeout)) {
# Lock it
rundll32.exe user32.dll,LockWorkStation
# Setting $locked to 1 will prevent it from relocking every 10 seconds
$locked = 1;
#Write-Host ("Locking");
}
# Your computer is idle for less than the allowed time -> in most cases this means it is unlocked and
# therefore ready to be locked again!
if ($idle_time -lt $idle_timeout) {
$locked = 0;
}
# Save the environment. Don't use 100% of a single CPU just for idle checking :)
Start-Sleep -Seconds 10
}
while (1 -eq 1)
|
PowerShellCorpus/GithubGist/pkirch_7e6049c61e18672ee52b_raw_cf67b16c746685a5c1db438794b2dd31ea77bf78_Upload-VHD.ps1
|
pkirch_7e6049c61e18672ee52b_raw_cf67b16c746685a5c1db438794b2dd31ea77bf78_Upload-VHD.ps1
|
# Get administration certificate.
# Get-AzurePublishSettingsFile
# Import-AzurePublishSettingsFile -PublishSettingsFile "C:\Users\pkirch\Downloads\Azure MSDN - pkirchner-9-11-2014-credentials.publishsettings"
# Settings
$SubscriptionName = "Azure MSDN - pkirchner"
$StorageAccountName = "pkmsft"
$Container = "vhds"
$LocalVhd = "C:\Users\pkirch\fixedvhd20mb.vhd"
# Select my Microsoft Azure Subscription.
Select-AzureSubscription -SubscriptionName $SubscriptionName
# Get locations. Need to know one for storage account creation.
# Get-AzureLocation | Select -Property DisplayName
# Create new storage account.
New-AzureStorageAccount -Location "West Europe" -StorageAccountName $StorageAccountName -Type Standard_LRS
# Create container for VHDs.
$StorageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName
New-AzureStorageContext -StorageAccountKey $StorageAccountKey.Primary -StorageAccountName $StorageAccountName | `
New-AzureStorageContainer -Name $Container -Permission Off
# Add-AzureVhd needs the CurrentStorageAccountName to be set.
Set-AzureSubscription -SubscriptionName $SubscriptionName -CurrentStorageAccountName $StorageAccountName
# Build destination path automatically.
$NewContainer = Get-AzureStorageContainer -Name $Container
$VhdFile = Split-Path -Path $LocalVhd -Leaf
$Destination = $NewContainer.CloudBlobContainer.Uri.AbsoluteUri + "/" + $VhdFile
$Destination
# Upload VHD
Add-AzureVhd -Destination $Destination -LocalFilePath $LocalVhd
## Clean Up ##
# Delete storage account.
# Remove-AzureStorageAccount -StorageAccountName $StorageAccountName
########################################################################
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF #
# ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO #
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A #
# PARTICULAR PURPOSE. #
########################################################################
|
PowerShellCorpus/GithubGist/rposbo_2859e10bbf24ea2b689d_raw_26619b5e59e482b3307220e1f449440b6b391f17_upload-to-blob-storage.ps1
|
rposbo_2859e10bbf24ea2b689d_raw_26619b5e59e482b3307220e1f449440b6b391f17_upload-to-blob-storage.ps1
|
Param(
[string]$rootDir,
[string]$storage,
[string]$key,
[string]$container
)
try {
$context = New-AzureStorageContext -StorageAccountName $storage -StorageAccountKey $key
foreach ($file in Get-ChildItem -Path $rootDir)
{
$prop = @{"ContentType"="application/octetstream"}
if ($file.Extension.ToLowerInvariant() -eq ".png")
{
$prop = @{"ContentType"="image/png"}
}
if ($file.Extension.ToLowerInvariant() -eq ".jpg")
{
$prop = @{"ContentType"="image/jpeg"}
}
Set-AzureStorageBlobContent -Blob $file.Name -Container $container -File $file.FullName -Context $context -Properties $prop -Force
}
}
catch [System.Exception] {
Write-Host $_.Exception.ToString()
exit 1
}
|
PowerShellCorpus/GithubGist/tigerswithguitars_472f54c9c994b1bcdb8b_raw_fb07ec440070c2e0bc9fca05c3879da58af7b5f4_sexy_profile.ps1
|
tigerswithguitars_472f54c9c994b1bcdb8b_raw_fb07ec440070c2e0bc9fca05c3879da58af7b5f4_sexy_profile.ps1
|
# Load posh-git example profile
. '{PATH TO POWERSHELL STUFF}\WindowsPowerShell\Modules\posh-git\profile.example.ps1'
#First in your powershell profile in
#C:\Users\<<username>>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
#Then in:
#C:\Users\<<username>>\Documents\WindowsPowerShell\Get-ChildItemColor.ps1
# function prompt {
# "$(split-path "$pwd" -leaf -resolve) $lastexitcode $Global:GitStatus #>"
# }
Import-Module posh-git
# Set up a simple prompt, adding the git prompt parts inside git repos
function global:prompt {
$realLASTEXITCODE = $LASTEXITCODE
# Reset color, which can be messed up by Enable-GitColors
$Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor
Write-Host($(split-path "$pwd" -leaf -resolve)) -nonewline
$fore = $Host.UI.RawUI.ForegroundColor
if (get-job){
$Host.UI.RawUI.ForegroundColor = 'Green'
Write-Host " (⌐■_■)" -nonewline
} else {
$Host.UI.RawUI.ForegroundColor = 'Cyan'
Write-Host " ( •_•)" -nonewline
}
$Host.UI.RawUI.ForegroundColor = $fore
Write-VcsStatus
$global:LASTEXITCODE = $realLASTEXITCODE
return " #> "
}
Enable-GitColors
Pop-Location
function Get-ChildItemColor {
<#
.Synopsis
Returns childitems with colors by type.
From http://poshcode.org/?show=878
.Description
This function wraps Get-ChildItem and tries to output the results
color-coded by type:
Compressed - Yellow
Directories - Dark Cyan
Executables - Green
Text Files - Cyan
Others - Default
.ReturnValue
All objects returned by Get-ChildItem are passed down the pipeline
unmodified.
.Notes
NAME: Get-ChildItemColor
AUTHOR: Tojo2000 <tojo2000@tojo2000.com>
#>
$regex_opts = ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase `
-bor [System.Text.RegularExpressions.RegexOptions]::Compiled)
$fore = $Host.UI.RawUI.ForegroundColor
$compressed = New-Object System.Text.RegularExpressions.Regex('\.(zip|tar|gz|rar)$', $regex_opts)
$executable = New-Object System.Text.RegularExpressions.Regex('\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg|fsx)$', $regex_opts)
$dll_pdb = New-Object System.Text.RegularExpressions.Regex('\.(dll|pdb)$', $regex_opts)
$configs = New-Object System.Text.RegularExpressions.Regex('\.(config|conf|ini)$', $regex_opts)
$text_files = New-Object System.Text.RegularExpressions.Regex('\.(txt|cfg|conf|ini|csv|log)$', $regex_opts)
Invoke-Expression ("Get-ChildItem $args") |
%{
$c = $fore
if ($_.GetType().Name -eq 'DirectoryInfo') {
$c = 'DarkCyan'
} elseif ($compressed.IsMatch($_.Name)) {
$c = 'Yellow'
} elseif ($executable.IsMatch($_.Name)) {
$c = 'Green'
} elseif ($text_files.IsMatch($_.Name)) {
$c = 'Cyan'
} elseif ($dll_pdb.IsMatch($_.Name)) {
$c = 'DarkGreen'
} elseif ($configs.IsMatch($_.Name)) {
$c = 'Yellow'
}
$Host.UI.RawUI.ForegroundColor = $c
echo $_
$Host.UI.RawUI.ForegroundColor = $fore
}
}
# set-location D:\code
# . "C:\Users\<<username>>\Documents\WindowsPowerShell\Get-ChildItemColor.ps1" # read the colourized ls
set-alias ls Get-ChildItemColor -force -option allscope
function Get-ChildItem-Force { ls -Force }
set-alias la Get-ChildItem-Force -option allscope
|
PowerShellCorpus/GithubGist/bmccormack_2586415_raw_4797a793c640cf45946cb865381bf11b1e564051_Select-WindowStarted.ps1
|
bmccormack_2586415_raw_4797a793c640cf45946cb865381bf11b1e564051_Select-WindowStarted.ps1
|
# Uses WASP from http://wasp.codeplex.com for automating the control of Windows in Powershell.
# The purpose of this function is to start a new process and then return the window
# that was opened by the started process. This can be difficult because if you already have
# multiple windows open for that process; there may be a delay in the window being returned
# after the process is started; and the process that is started is not always the same as the
# window that's created (Chrome).
#
# This function will grab a list of current windows matching the processName, start a new instance,
# and will then loop until the new window is opened or the function times out. example:
#
# Select-WindowStarted notepad.exe -processName
#
function Select-WindowStarted($process, [string]$processName = "", $msTimeout = 1000){
$startTime = get-date
$endTime = $startTime.addMilliseconds($msTimeout)
if ($processName -eq ""){
$processName = $process
}
$currentWindows = Select-Window $processName
$processID = Start-Process $process -passThru
do {
if((get-date) -gt $endTime){
throw "Timeout while trying to Select window by process"
}
}
while ((Select-Window $processName | where {!($currentWindows -contains $_)} | measure).count -eq 0)
Select-Window $processName | where {!($currentWindows -contains $_)}
}
|
PowerShellCorpus/GithubGist/chrisobriensp_7814727_raw_ef525be14448bd842651b35bfa030b1c08d44404_PS_SPO_RecreateSiteCollection.ps1
|
chrisobriensp_7814727_raw_ef525be14448bd842651b35bfa030b1c08d44404_PS_SPO_RecreateSiteCollection.ps1
|
. .\PS_SPO_TopOfScript.ps1
# replace these details - parameters for new site collection..
$siteCollectionUrl = "Your site URL here.."
$owner = $username
$storageQuota = 100
$resourceQuota = 30
$localeID = 1033
$timeZoneID = 2 # (GMT London)
if ($connected)
{
Write-Host "Removing site collection $siteCollectionUrl - please wait.."
Remove-SPOSite $siteCollectionUrl -Confirm:$false
Write-Host "Now deleting from recycle bin.."
Remove-SPODeletedSite $siteCollectionUrl -Confirm:$false
Write-Host "Creating new site collection (no template) at $siteCollectionUrl - please wait.."
New-SPOSite -Url $siteCollectionUrl -Owner $owner -StorageQuota $storageQuota -LocaleId $localeID -ResourceQuota $resourceQuota -TimeZoneId $timeZoneID
Disconnect-SPOService
Write-Host "Completed" -ForegroundColor Green
}
|
PowerShellCorpus/GithubGist/gugi9000_6612271_raw_aab589128c519e1d107964f1d4b0934c8ea9498d_MailboxSizes.ps1
|
gugi9000_6612271_raw_aab589128c519e1d107964f1d4b0934c8ea9498d_MailboxSizes.ps1
|
# HINT: MailboxSizes.ps1 > mailboxes.txt
# Is how I find this the most useful
Get-MailboxDatabase | Get-MailboxStatistics | Sort totalitemsize -desc | ft displayname, totalitemsize,itemcount
|
PowerShellCorpus/GithubGist/jonforums_4771531_raw_40d9bcbc939f213e9ef4e4fe5e3a30ed5dab9e6f_build_openssl.ps1
|
jonforums_4771531_raw_40d9bcbc939f213e9ef4e4fe5e3a30ed5dab9e6f_build_openssl.ps1
|
#requires -version 2.0
# Author: Jon Maken
# License: 3-clause BSD
# Revision: 2013-03-11 01:24:20 -0600
#
# TODO:
# - extract generics into a downloadable utils helper module
# - add try-catch-finally error handling
# - add checkpoint support
# - support x86 and x64 builds
param(
[parameter(Mandatory=$true,
Position=0,
HelpMessage='OpenSSL version to build (eg - 1.0.1e).')]
[alias('v')]
[validateset('1.0.0k','1.0.1e')]
[string] $version,
[parameter(HelpMessage='mingw toolchain flavor to use (eg - mingw, mingw64)')]
[validateset('mingw','mingw64')]
[string] $toolchain = 'mingw',
[parameter(HelpMessage='Path to 7-Zip command line tool')]
[string] $7ZA = 'C:/tools/7za.exe',
[parameter(HelpMessage='Path to DevKit root directory')]
[string] $DEVKIT = 'C:/Devkit',
[parameter(HelpMessage='Path to zlib dev libraries root directory')]
[alias('with-zlib-dir')]
[string] $ZLIBDIR = 'C:/devlibs/zlib-1.2.7'
)
$msg_color = 'Yellow'
$root = Split-Path -parent $script:MyInvocation.MyCommand.Path
$libname = 'openssl'
$source = "${libname}-${version}.tar.gz"
$source_dir = "${libname}-${version}"
$repo_root = 'http://www.openssl.org/source/'
$archive = "${repo_root}${source}"
$archive_hash = "${repo_root}${source}.sha1"
# download and verify
# TODO implement progress bar when extracted to util helper module
if(-not (Test-Path $source)) {
Import-Module BitsTransfer
Write-Host "[INFO] downloading $archive" -foregroundcolor $msg_color
Start-BitsTransfer $archive "$PWD\$source"
}
# download hash data and validate source archive
Write-Host "[INFO] validating $source" -foregroundcolor $msg_color
$client = New-Object System.Net.WebClient
$hash = $client.DownloadString($archive_hash).Trim(" ","`r","`n").ToLower()
try {
$hasher = New-Object System.Security.Cryptography.SHA1Cng
$fs = New-Object System.IO.FileStream "$PWD\$source", 'Open', 'Read'
$test_hash = [BitConverter]::ToString($hasher.ComputeHash($fs)).Replace('-','').ToLower()
} finally {
$fs.Close()
}
if ($test_hash -ne $hash) {
Write-Host "[ERROR] $source validation failed, exiting" -foregroundcolor red
break
}
# extract
Write-Host "[INFO] extracting $source" -foregroundcolor $msg_color
$tar_file = $source.Substring(0, $source.LastIndexOf('.'))
(& "$7ZA" "x" $source) -and (& "$7ZA" "x" $tar_file) -and (rm $tar_file) | Out-Null
# patch, configure, build, archive
Push-Location "${source_dir}"
# patch
Write-Host "[INFO] patching ${source_dir}" -foregroundcolor $msg_color
Push-Location test
rm md2test.c,rc5test.c,jpaketest.c
Pop-Location
# activate toolchain
Write-Host "[INFO] activating toolchain" -foregroundcolor $msg_color
. "$DEVKIT/devkitvars.ps1" | Out-Null
$env:CPATH = "$ZLIBDIR/include"
# configure
Write-Host "[INFO] configuring ${source_dir}" -foregroundcolor $msg_color
$install_dir = "$($PWD.ToString().Replace('\','/'))/my_install"
perl Configure $toolchain zlib-dynamic shared --prefix="$install_dir" | Out-Null
# build
Write-Host "[INFO] building ${source_dir}" -foregroundcolor $msg_color
sh -c "make" | Out-Null
# install
sh -c "make install_sw" | Out-Null
# archive
Push-Location "$install_dir"
Write-Host "[INFO] creating binary archive for ${source_dir}" -foregroundcolor $msg_color
$bin_archive = "${source_dir}-x86-windows-bin.7z"
& "$7ZA" "a" "-mx=9" "-r" $bin_archive "*" | Out-Null
Pop-Location
Pop-Location
# hoist binary archive and cleanup
Write-Host "[INFO] cleaning up" -foregroundcolor $msg_color
mv "$install_dir/$bin_archive" "$PWD"
rm -recurse -force "${source_dir}"
|
PowerShellCorpus/GithubGist/gravejester_54ec8204ab008700f6a6_raw_67795615dfafd6569dc4a4c62929b80aeb0c51af_Get-TrimmedMean.ps1
|
gravejester_54ec8204ab008700f6a6_raw_67795615dfafd6569dc4a4c62929b80aeb0c51af_Get-TrimmedMean.ps1
|
function Get-TrimmedMean {
<#
.SYNOPSIS
Function to calculate the trimmed mean of a set of numbers.
.DESCRIPTION
Function to calculate the trimmed mean of a set of numbers.
The default trim percent is 25, which when used will calculate the Interquartile Mean of the number set.
Use the TrimPercent parameter to set the trim percent as needed.
.EXAMPLE
[double[]]$dataSet = 8, 3, 7, 1, 3, 9
Get-TrimmedMean -NumberSet $dataSet
Calculate the trimmed mean of the number set, using the default trim percent of 25.
.NOTES
Author: Øyvind Kallstad
Date: 29.10.2014
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[double[]] $NumberSet,
[Parameter()]
[ValidateRange(1,100)]
[int] $TrimPercent = 25
)
try {
# collect the number set into an arraylist and sort it
$orderedSet = New-Object System.Collections.ArrayList
$orderedSet.AddRange($NumberSet)
$orderedSet.Sort()
# calculate the trim count
$numberSetLength = $orderedSet.Count
$trimmedMean = $TrimPercent/100
$trimmedCount = [Math]::Floor($trimmedMean * $numberSetLength)
# subtract trim count from top and bottom of the number set
[double[]]$trimmedSet = $orderedSet[$trimmedCount..($numberSetLength - ($trimmedCount+1))]
# calculate the mean of the trimmed set
Write-Output ($trimmedSet | Measure-Object -Average | Select-Object -ExpandProperty Average)
}
catch {
Write-Warning $_.Exception.Message
}
}
|
PowerShellCorpus/GithubGist/colinbowern_1225231_raw_dcb84d9cf4fc604e61005c826cdacf936d89a53c_Get-Build2011Sessions.ps1
|
colinbowern_1225231_raw_dcb84d9cf4fc604e61005c826cdacf936d89a53c_Get-Build2011Sessions.ps1
|
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
$a = ([xml](new-object net.webclient).downloadstring("http://channel9.msdn.com/Events/BUILD/BUILD2011/RSS/wmv"))
$a.rss.channel.item | foreach{
$url = New-Object System.Uri($_.enclosure.url)
$sessionUrl = New-Object System.Uri($_.link)
$file = $sessionUrl.segments[-1] + " - " + $_.title.Replace("""", "'").Replace(":", "-") + ".wmv"
if (!(test-path $file))
{
Write-Host "Downloading $file"
(New-Object System.Net.WebClient).DownloadFile($url, $file)
}
}
|
PowerShellCorpus/GithubGist/GuruAnt_7216135_raw_5dd0f89b7e39be82288a82169f0e5bb3376e6481_AddHashTableOfVirtualPortGroupsTovSphereHosts.ps1
|
GuruAnt_7216135_raw_5dd0f89b7e39be82288a82169f0e5bb3376e6481_AddHashTableOfVirtualPortGroupsTovSphereHosts.ps1
|
# Sets up virtual port groups on all hosts connected to a specific vCenter Server
# Name of vCenter Server
$strVCenterServer = "your.vCenter.Server"
# VLANs and associated VPGs
$ArrVLANs = @{
"123" = "vlanA";
"456" = "vlanB";
"789" = "vlanC";
}
# Connect to the vCenter Server
Connect-VIserver -Server $strVCenterServer
# Loop through the VLAN/VPG pairs
ForEach($objVLAN in ($ArrVLANs.Keys | Sort-Object)){
# Loop through the hosts
ForEach ($objHost in (Get-VMHost | Sort-Object)){
# Create the VPG with the VLAN as specified in the array above, on the switch called "VMSwitch" on the current host
# Remove the "-WhatIf" tag from the end of the following line to "arm" the script
New-VirtualPortGroup -Name $strNewVPG -VirtualSwitch (Get-Virtualswitch -VMHost $objHost | Where-Object { $_.Name -match "VMswitch" }) -VLanId $strNewVlanTag
# Write what we've just done to screen
Write-Host ("Adding Virtual Port Group $($ArrVLANs[$objVLAN]) with VLAN Tag $objVLAN to $objHost")
}
}
# Disconnect the session from the host
Disconnect-VIServer -Confirm:$False
|
PowerShellCorpus/GithubGist/kujotx_4566177_raw_49d61dd813897496a3ba58bb1c949786e1d5e8bc_deleteold.ps1
|
kujotx_4566177_raw_49d61dd813897496a3ba58bb1c949786e1d5e8bc_deleteold.ps1
|
<#
.SYNOPSIS
Script to delete or list old files in a folder
.DESCRIPTION
Script to delete files older than x-days. The script is built to be used as a scheduled task, it automatically generates a logfile name based on the copy location and the current date/time. There are various levels of logging available and the script can also run in -listonly mode in which it only lists the files it would otherwise delete. There are two main routines, one to delete the files and a second routine that checks if there are any empty folders left that could be deleted.
.PARAMETER FolderPath
The path that will be recusively scanned for old files.
.PARAMETER Fileage
Filter for age of file, entered in days. Use -1 for all files to be removed.
.PARAMETER LogFile
Specifies the full path and filename of the logfile. When the LogFile parameter is used in combination with -autolog only the path is required.
.PARAMETER AutoLog
Automatically generates filename at path specified in -logfile. If a filename is specified in the LogFile parameter and the AutoLog parameter is used only the path specified in LogFile is used. The file name is created with the following naming convention:
"Autolog_<FolderPath><dd-MM-yyyy_HHmm.ss>.log"
.PARAMETER ExcludePath
Specifies a path or multiple paths in quotes separated by commas. The Exclude parameter only accepts full paths, relative paths should not be used.
.PARAMETER IncludePath
Specifies a path or multiple paths in quotes separated by commas. The Exclude parameter only accepts full paths, relative paths should not be used. IncludePath is processed before Exclude path, using both parameter
.PARAMETER ExcludeFileExtension
Specifies an extension or multiple extensions in quotes, separated by commas. The extensions will be excluded from deletion. Asterisk can be used as a wildcard.
.PARAMETER IncludeFileExtension
Specifies an extension or multiple extensions in quotes, separated by commas. The extensions will be included in the deletion, all other extensions will implicitly be excluded. Asterisk can be used as a wildcard.
.PARAMETER ExcludeDate
If the ExcludeDate parameter is specified the query is converted by the ConvertFrom-Query function. The output of that table is a hashtable that is splatted to the ConvertTo-DateObject function which returns an array of dates. All files that match a date in the returned array will be excluded from deletion.
Query examples:
Week:
'Week,sat,-1'
Will list all saturday until the LimitYear maximum is reached
'Week,wed,5'
Will list the last 5 wednesdays
Month:
'Month,first,4'
Will list the first day of the last four months
'Month,last,-1'
Will list the last day of until the LimitYear maximum is reached. If the current date is the last day of the month the current day is also listed.
'Month,30,3'
Will list the 30th of the last three months, if february is in the results it will be ignored because it does not have 30 days.
'Month,31,-1'
Will only list the 31st of the month, all months that have less than 31 days are excluded. Will list untli the LimitYear maximum has been reached.
Quarter:
'Quarter,first,-1'
Will list the first day of a quarter until the LimitYear maximum is reached
'Quarter,last,6'
Will list the last day of the past six quarters. If the current date is the last day of the quarter the current day is also listed.
'Quarter,91,5'
Will only list the 91st day of each quarter, in non-leap years this will be the last three quarters. In leap years the first quarter also has 91 days and will therefore be included in the results
'Quarter,92,-1'
Will only list the 92nd day of each quarter, so only display the 30th of september and 31st of december. The first two quarters of a year have less days and will not be listed. Will run until limityear maximum is reached
Year:
'Year,last,4'
Will list the 31st of december for the last 4 years
'Year,first,-1'
Will list the 1st of january until the Limityear maximum has been reached
'Year,15,-1'
Will list the 15 of january until the LimitYear maximum has been reached
'Year,366,5'
Will list only the 366st day, only the last day of the last 5 leap years
Specific Date:
'Date,2010-05-15'
Will list 15th of may 2010
'Date,2012/12/12
Will list 12th of december 2012
'LimitYear,2008'
Will place the limit of LimitYear to 2008, the default is 2010.
Any combination or queries is allowed by comma-separating the queries for example. Query elements Week/Month/Quarter/Year can not be used twice when combining queries. The Date value can be used multiple times:
'Week,Fri,10','Year,last,-1','LimitYear,1950'
Will list the last 10 fridays and the 31st of december for all years until the LimitYear is reached
'Week,Thu,4','Month,last,-1','Quarter,first,6','Year,last,10','LimitYear,2012','Date,1990-12-31','Date,1995-5-31'
Will list the last four Thursdays, the last day of the month until LimitYear maximum has been reached, the first day of the first 6 quarters and the 31st of december for the last 10 years and the two specific dates 1990-12-31 & 1995-5-31.
.PARAMETER ListOnly
Only lists, does not remove or modify files. This parameter can be used to establish which files would be deleted if the script is executed.
.PARAMETER VerboseLog
Logs all delete operations to log, default behaviour of the script is to log failed only.
.PARAMETER CreateTime
Deletes files based on CreationTime, the default behaviour of the script is to delete based on lastwritetime.
.PARAMETER CleanFolders
If this switch is specified any empty folder will be removed. Default behaviour of this script is to only delete folders that contained old files.
.PARAMETER NoFolders
If this switch is specified only files will be deleted and the existing folder will be retained.
.NOTES
Name: deleteold.ps1
Author: Jaap Brasser
Version: 1.6.1
DateUpdated: 2012-11-20
.LINK
http://www.jaapbrasser.com
.EXAMPLE
.\deleteold.ps1 -FolderPath H:\scripts -FileAge 100 -ListOnly -LogFile H:\log.log
Description:
Searches through the H:\scripts folder and writes a logfile containing files that were last modified 100 days ago and older.
.EXAMPLE
.\deleteold.ps1 -FolderPath H:\scripts -FileAge 30 -LogFile H:\log.log -VerboseLog
Description:
Searches through the H:\scripts folder and deletes files that were modified 30 days ago or before, writes all operations, success and failed, to a logfile on the H: drive.
.EXAMPLE
.\deleteold.ps1 -FolderPath C:\docs -FileAge 30 -LogFile H:\log.log -ExcludePath "C:\docs\finance\","C:\docs\hr\"
Description:
Searches through the C:\docs folder and deletes files, exluding the finance and hr folders in C:\docs.
.EXAMPLE
.\deleteold.ps1 -FolderPath C:\Folder -FileAge 30 -LogFile H:\log.log -IncludePath "C:\Folder\Docs\","C:\Folder\Users\" -ExcludePath "C:\docs\finance\","C:\docs\hr\"
Description:
Only check files in the C:\Folder\Docs\ and C:\Folder\Users\ Folders not any other folders in C:\Folders and explicitly exclude the Finance an HR folders in C:\Folder\Docs.
.EXAMPLE
.\deleteold.ps1 -FolderPath C:\Folder -FileAge 30 -LogFile H:\log.log -IncludePath "C:\Folder\Docs\","C:\Folder\Users\" -ExcludePath "C:\docs\finance\","C:\docs\hr\" -ExcludeDate 'Week,Fri,10','Year,last,-1','LimitYear,1950'
Description:
Only check files in the C:\Folder\Docs\ and C:\Folder\Users\ Folders not any other folders in C:\Folders and explicitly exclude the Finance an HR folders in C:\Folder\Docs. Also excludes files based on Date, excluding the last 10 fridays and the 31st of December for all years back until 1950
.EXAMPLE
PowerShell.exe deleteold.ps1 -FolderPath 'H:\admin_jaap' -FileAge 10 -LogFile C:\log -AutoLog
Description:
Launches the script from batchfile or command prompt a filename is automatically generated since the -AutoLog parameter is used. Note the quotes '' that are used for the FolderPath parameter.
.EXAMPLE
.\deleteold.ps1 -FolderPath C:\docs -FileAge 30 -logfile h:\log.log -CreationDate -NoFolder
Description:
Deletes all files that were created 30 days ago or before in the C:\docs folder. No folders are deleted.
.EXAMPLE
.\deleteold.ps1 -FolderPath C:\docs -FileAge 30 -logfile h:\log.log -CreationDate -CleanFolders
Description:
Deletes all files that were created 30 days ago or before in the C:\docs folder. Only folders that contained old files and are empty after the deletion of those files will be deleted.
.EXAMPLE
.\deleteold.ps1 -folderpath c:\users\jaapbrasser\desktop -fileage 10 -log c:\log.txt -autolog -verboselog -IncludeFileExtension '.xls*','.doc*'
Description:
Deletes files older than 10 days, only deletes files matching the .xls* and .doc* patterns eg: .doc and .docx files. Log file is stored in the root of the C-drive with an automatically generated name.
.EXAMPLE
.\deleteold.ps1 -folderpath c:\users\jaapbrasser\desktop -fileage 10 -log c:\log.txt -autolog -verboselog -ExcludeFileExtension .xls
Description:
Deletes files older than 10 days, excluding xls files. Log file is stored in the root of the C-drive with an automatically generated name.
.EXAMPLE
.\deleteold.ps1 -FolderPath C:\docs -FileAge 30 -LogFile h:\log.log -ExcludeDate 'Week,Thu,4','Month,last,-1','Quarter,first,6','Year,last,10','LimitYear,2012','Date,1990-12-31','Date,1995-5-31'
Description:
Deletes all files that were created 30 days ago or before in the C:\docs folder. With the exclusion of files last modified/created specified in the -ExcludeDate query.
#>
param(
[string]$FolderPath,
[string]$FileAge,
[string]$LogFile,
[string[]]$ExcludePath,
[string[]]$IncludePath,
[string[]]$ExcludeFileExtension,
[string[]]$IncludeFileExtension,
[string[]]$ExcludeDate,
[switch]$ListOnly,
[switch]$VerboseLog,
[switch]$AutoLog,
[switch]$CreateTime,
[switch]$CleanFolders,
[switch]$NoFolder
)
# Function to convert the query provided in -ExcludeDate to a format that can be parsed by the ConvertTo-DateObject function
function ConvertFrom-DateQuery {
param (
$Query
)
try {
$CsvQuery = Convertfrom-Csv -InputObject $Query -Delimiter ',' -Header "Type","Day","Repeat"
$ConvertCsvSuccess = $true
} catch {
Write-Warning "Query is in incorrect format, please supply query in proper format"
$ConvertCsvSuccess = $false
}
if ($ConvertCsvSuccess) {
$Check=$HashOutput = @{}
foreach ($Entry in $CsvQuery) {
switch ($Entry.Type) {
'week' {
# Convert named dates to correct format
switch ($Entry.Day)
{
# DayOfWeek starts count at 0, referring to the [datetime] property DayOfWeek
'sun' {
$HashOutput.DayOfWeek = 0
$HashOutput.WeekRepeat = $Entry.Repeat
}
'mon' {
$HashOutput.DayOfWeek = 1
$HashOutput.WeekRepeat = $Entry.Repeat
}
'tue' {
$HashOutput.DayOfWeek = 2
$HashOutput.WeekRepeat = $Entry.Repeat
}
'wed' {
$HashOutput.DayOfWeek = 3
$HashOutput.WeekRepeat = $Entry.Repeat
}
'thu' {
$HashOutput.DayOfWeek = 4
$HashOutput.WeekRepeat = $Entry.Repeat
}
'fri' {
$HashOutput.DayOfWeek = 5
$HashOutput.WeekRepeat = $Entry.Repeat
}
'sat' {
$HashOutput.DayOfWeek = 6
$HashOutput.WeekRepeat = $Entry.Repeat
}
Default {$Check.WeekSuccess = $false}
}
}
'month' {
# Convert named dates to correct format
switch ($Entry.Day)
{
# DayOfMonth starts count at 0, referring to the last day of the month with zero
'first' {
$HashOutput.DayOfMonth = 1
$HashOutput.MonthRepeat = $Entry.Repeat
}
'last' {
$HashOutput.DayOfMonth = 0
$HashOutput.MonthRepeat = $Entry.Repeat
}
{(1..31) -contains $_} {
$HashOutput.DayOfMonth = $Entry.Day
$HashOutput.MonthRepeat = $Entry.Repeat
}
Default {$Check.MonthSuccess = $false}
}
}
'quarter' {
# Count the number of times the quarter argument is used, used in final check of values
$QuarterCount++
# Convert named dates to correct format
switch ($Entry.Day)
{
# DayOfMonth starts count at 0, referring to the last day of the month with zero
'first' {
$HashOutput.DayOfQuarter = 1
$HashOutput.QuarterRepeat = $Entry.Repeat
}
'last' {
$HashOutput.DayOfQuarter = 0
$HashOutput.QuarterRepeat = $Entry.Repeat
}
{(1..92) -contains $_} {
$HashOutput.DayOfQuarter = $Entry.Day
$HashOutput.QuarterRepeat = $Entry.Repeat
}
Default {$Check.QuarterSuccess = $false}
}
}
'year' {
# Convert named dates to correct format
switch ($Entry.Day)
{
# DayOfMonth starts count at 0, referring to the last day of the month with zero
'first' {
$HashOutput.DayOfYear = 1
$HashOutput.DayOfYearRepeat = $Entry.Repeat
}
'last' {
$HashOutput.DayOfYear = 0
$HashOutput.DayOfYearRepeat = $Entry.Repeat
}
{(1..366) -contains $_} {
$HashOutput.DayOfYear = $Entry.Day
$HashOutput.DayOfYearRepeat = $Entry.Repeat
}
Default {$Check.YearSuccess = $false}
}
}
'date' {
# Verify if the date is in the correct format
switch ($Entry.Day)
{
{try {[DateTime]"$($Entry.Day)"} catch{}} {
[array]$HashOutput.DateDay += $Entry.Day
}
Default {$Check.DateSuccess = $false}
}
}
'limityear' {
switch ($Entry.Day)
{
{(1000..2100) -contains $_} {
$HashOutput.LimitYear = $Entry.Day
}
Default {$Check.LimitYearSuccess = $false}
}
}
Default {
$QueryContentCorrect = $false
}
}
}
$HashOutput
}
}
# Function that outputs an array of date objects that can be used to exclude certain files from deletion
function ConvertTo-DateObject {
param(
[validaterange(0,6)]
$DayOfWeek,
[int]$WeekRepeat=1,
[validaterange(0,31)]
$DayOfMonth,
[int]$MonthRepeat=1,
[validaterange(0,92)]
$DayOfQuarter,
[int]$QuarterRepeat=1,
[validaterange(0,366)]
$DayOfYear,
[int]$DayOfYearRepeat=1,
$DateDay,
[validaterange(1000,2100)]
[int]$LimitYear = 2010
)
# Define variable
$CurrentDate = Get-Date
if ($DayOfWeek -ne $null) {
$CurrentWeekDayInt = $CurrentDate.DayOfWeek.value__
# Loop runs for number of times specified in the WeekRepeat parameter
for ($j = 0; $j -lt $WeekRepeat; $j++)
{
$CheckDate = $CurrentDate.Date.AddDays(-((7*$j)+$CurrentWeekDayInt-$DayOfWeek))
# Only display date if date is larger than current date, this is to exclude dates in the current week
if ($CheckDate -le $CurrentDate) {
$CheckDate
} else {
# Increase weekrepeat, to ensure the correct amount of repeats are executed when date returned is
# higher than current date
$WeekRepeat++
}
}
# Loop runs until $LimitYear parameter is exceeded
if ($WeekRepeat -eq -1) {
$j=0
do {
$CheckDate = $CurrentDate.AddDays(-((7*$j)+$CurrentWeekDayInt-$DayOfWeek))
$j++
# Only display date if date is larger than current date, this is to exclude dates in the current week
if ($CheckDate -le $CurrentDate) {
$CheckDate
}
} while ($LimitYear -le $CheckDate.Adddays(-7).Year)
}
}
if ($DayOfMonth -ne $null) {
# Loop runs for number of times specified in the MonthRepeat parameter
for ($j = 0; $j -lt $MonthRepeat; $j++)
{
$CheckDate = $CurrentDate.Date.AddMonths(-$j).AddDays($DayOfMonth-$CurrentDate.Day)
# Only display date if date is larger than current date, this is to exclude dates ahead of the current date and
# to list only output the possible dates. If a value of 29 or higher is specified as a DayOfMonth value
# only possible dates are listed.
if ($CheckDate -le $CurrentDate -and $(if ($DayOfMonth -ne 0) {$CheckDate.Day -eq $DayOfMonth} else {$true})) {
$CheckDate
} else {
# Increase MonthRepeat integer, to ensure the correct amount of repeats are executed when date returned is
# higher than current date
$MonthRepeat++
}
}
# Loop runs until $LimitYear parameter is exceeded
if ($MonthRepeat -eq -1) {
$j=0
do {
$CheckDate = $CurrentDate.Date.AddMonths(-$j).AddDays($DayOfMonth-$CurrentDate.Day)
$j++
# Only display date if date is larger than current date, this is to exclude dates ahead of the current date and
# to list only output the possible dates. For example if a value of 29 or higher is specified as a DayOfMonth value
# only possible dates are listed.
if ($CheckDate -le $CurrentDate -and $(if ($DayOfMonth -ne 0) {$CheckDate.Day -eq $DayOfMonth} else {$true})) {
$CheckDate
}
} while ($LimitYear -le $CheckDate.Adddays(-31).Year)
}
}
if ($DayOfQuarter -ne $null) {
# Set quarter int to current quarter value $QuarterInt
$QuarterInt = [int](($CurrentDate.Month+1)/3)
$QuarterYearInt = $CurrentDate.Year
$QuarterLoopCount = $QuarterRepeat
$j = 0
do {
switch ($QuarterInt) {
1 {
$CheckDate = ([DateTime]::ParseExact("$($QuarterYearInt)0101",'yyyyMMdd',$null)).AddDays($DayOfQuarter-1)
# Check for number of days in the 1st quarter, this depends on leap years
$DaysInFeb = ([DateTime]::ParseExact("$($QuarterYearInt)0301",'yyyyMMdd',$null)).AddDays(-1).Day
$DaysInCurrentQuarter = 31+$DaysInFeb+31
# If the number of days is larger that the total number of days in this quarter the quarter will be excluded
if ($DayOfQuarter -gt $DaysInCurrentQuarter) {
$CheckDate = $null
}
# This check is built-in to return the date last date of the current quarter, to ensure consistent results
# in case the command is executed on the last day of a quarter
if ($DayOfQuarter -eq 0) {
$CheckDate = [DateTime]::ParseExact("$($QuarterYearInt)0331",'yyyyMMdd',$null)
}
$QuarterInt = 4
$QuarterYearInt--
}
2 {
$CheckDate = ([DateTime]::ParseExact("$($QuarterYearInt)0401",'yyyyMMdd',$null)).AddDays($DayOfQuarter-1)
# Check for number of days in the 2nd quarter
$DaysInCurrentQuarter = 30+31+30
# If the number of days is larger that the total number of days in this quarter the quarter will be excluded
if ($DayOfQuarter -gt $DaysInCurrentQuarter) {
$CheckDate = $null
}
# This check is built-in to return the date last date of the current quarter, to ensure consistent results
# in case the command is executed on the last day of a quarter
if ($DayOfQuarter -eq 0) {
$CheckDate = [DateTime]::ParseExact("$($QuarterYearInt)0630",'yyyyMMdd',$null)
}
$QuarterInt = 1
}
3 {
$CheckDate = ([DateTime]::ParseExact("$($QuarterYearInt)0701",'yyyyMMdd',$null)).AddDays($DayOfQuarter-1)
# Check for number of days in the 3rd quarter
$DaysInCurrentQuarter = 31+31+30
# If the number of days is larger that the total number of days in this quarter the quarter will be excluded
if ($DayOfQuarter -gt $DaysInCurrentQuarter) {
$CheckDate = $null
}
# This check is built-in to return the date last date of the current quarter, to ensure consistent results
# in case the command is executed on the last day of a quarter
if ($DayOfQuarter -eq 0) {
$CheckDate = [DateTime]::ParseExact("$($QuarterYearInt)0930",'yyyyMMdd',$null)
}
$QuarterInt = 2
}
4 {
$CheckDate = ([DateTime]::ParseExact("$($QuarterYearInt)1001",'yyyyMMdd',$null)).AddDays($DayOfQuarter-1)
# Check for number of days in the 4th quarter
$DaysInCurrentQuarter = 31+30+31
# If the number of days is larger that the total number of days in this quarter the quarter will be excluded
if ($DayOfQuarter -gt $DaysInCurrentQuarter) {
$CheckDate = $null
}
# This check is built-in to return the date last date of the current quarter, to ensure consistent results
# in case the command is executed on the last day of a quarter
if ($DayOfQuarter -eq 0) {
$CheckDate = [DateTime]::ParseExact("$($QuarterYearInt)1231",'yyyyMMdd',$null)
}
$QuarterInt = 3
}
}
# Only display date if date is larger than current date, and only execute check if $CheckDate is not equal to $null
if ($CheckDate -le $CurrentDate -and $CheckDate -ne $null) {
# Only display the date if it is not further in the past than the limit year
if ($CheckDate.Year -ge $LimitYear -and $QuarterRepeat -eq -1) {
$CheckDate
}
# If the repeat parameter is not set to -1 display results regardless of limit year
if ($QuarterRepeat -ne -1) {
$CheckDate
$j++
} else {
$QuarterLoopCount++
}
}
# Added if statement to catch errors regarding
} while ($(if ($QuarterRepeat -eq -1) {$LimitYear -le $(if ($CheckDate) {$CheckDate.Year} else {9999})}
else {$j -lt $QuarterLoopCount}))
}
if ($DayOfYear -ne $null) {
$YearLoopCount = $DayOfYearRepeat
$YearInt = $CurrentDate.Year
$j = 0
# Mainloop containing the loop for selecting a day of a year
do {
$CheckDate = ([DateTime]::ParseExact("$($YearInt)0101",'yyyyMMdd',$null)).AddDays($DayOfYear-1)
# If the last day of the year is specified, a year is added to get consistent results when the query is executed on last day of the year
if ($DayOfYear -eq 0) {
$CheckDate = $CheckDate.AddYears(1)
}
# Set checkdate to null to allow for selection of last day of leap year
if (($DayOfYear -eq 366) -and !([DateTime]::IsLeapYear($YearInt))) {
$CheckDate = $null
}
# Only display date if date is larger than current date, and only execute check if $CheckDate is not equal to $null
if ($CheckDate -le $CurrentDate -and $CheckDate -ne $null) {
# Only display the date if it is not further in the past than the limit year
if ($CheckDate.Year -ge $LimitYear -and $DayOfYearRepeat -eq -1) {
$CheckDate
}
# If the repeat parameter is not set to -1 display results regardless of limit year
if ($DayOfYearRepeat -ne -1) {
$CheckDate
$j++
} else {
$YearLoopCount++
}
}
$YearInt--
} while ($(if ($DayOfYearRepeat -eq -1) {$LimitYear -le $(if ($CheckDate) {$CheckDate.Year} else {9999})}
else {$j -lt $YearLoopCount}))
}
if ($DateDay -ne $null) {
foreach ($Date in $DateDay) {
try {
$CheckDate = [DateTime]::ParseExact($Date,'yyyy-MM-dd',$null)
} catch {
try {
$CheckDate = [DateTime]::ParseExact($Date,'yyyy\/MM\/dd',$null)
} catch {}
}
if ($CheckDate -le $CurrentDate) {
$CheckDate
}
$CheckDate=$null
}
}
}
# Function that is triggered when the -autolog switch is active
function F_Autolog {
# Gets date and reformats to be used in log filename
$TempDate = (get-date).tostring("dd-MM-yyyy_HHmm.ss")
# Reformats $FolderPath so it can be used in the log filename
$TempFolderPath = $FolderPath -replace '\\','_'
$TempFolderPath = $TempFolderPath -replace ':',''
$TempFolderPath = $TempFolderPath -replace ' ',''
# Checks if the logfile is either pointing at a folder or a logfile and removes
# Any trailing backslashes
$TestLogPath = Test-Path $LogFile -PathType Container
if (-not $TestLogPath) {$LogFile = Split-Path $LogFile -Erroraction SilentlyContinue}
if ($LogFile.SubString($LogFile.Length-1,1) -eq "\") {$LogFile = $LogFile.SubString(0,$LogFile.Length-1)}
# Combines the date and the path scanned into the log filename
$script:LogFile = "$LogFile\Autolog_$TempFolderPath$TempDate.log"
}
# Function which contains the loop in which files are deleted. If a file fails to be deleted
# an error is logged and the error message is written to the log
# $count is used to speed up the delete fileloop and will also be used for other large loops in the script
function F_Deleteoldfiles {
$Count = $FileList.Count
for ($j=0;$j -lt $Count;$j++) {
$TempFile = $FileList[$j].FullName
$TempSize = $FileList[$j].Length
if(-not $ListOnly) {Remove-Item -LiteralPath $Tempfile -Force -ErrorAction SilentlyContinue}
if (-not $?) {
$TempErrorVar = "$($Error[0].tostring()) ::: $($Error[0].targetobject)"
"`tFAILED FILE`t`t$TempErrorVar" >> $LogFile
$script:FilesFailed++
$script:FailedSize+=$TempSize
}
else {
if (-not $ListOnly) {$script:FilesNumber++;$script:FilesSize+=$TempSize
if ($VerboseLog) {"`tDELETED FILE`t$tempfile" >> $LogFile}}
}
if($ListOnly) {"`tLISTONLY`t`t$TempFile" >> $LogFile
$script:FilesNumber++
$script:FilesSize+=$TempSize
}
}
}
# Checks whether folder is empty and uses temporary variables
# Main loop goes through list of folders, only deleting the empty folders
# The if(-not $tempfolder) is the verification whether the folder is empty
function F_Checkforemptyfolder {
$FolderList = @($FolderList | sort-object @{Expression={$_.FullName.Length}; Ascending=$false})
$Count = $FolderList.Count
for ($j=0;$j -lt $Count;$j++) {
$TempFolder = get-childitem $FolderList[$j].FullName -ErrorAction SilentlyContinue
if (-not $TempFolder) {
$TempName = $FolderList[$j].FullName
Remove-Item -LiteralPath $TempName -Force -Recurse -ErrorAction SilentlyContinue
if(-not $?) {
$TempErrorVar = "$($Error[0].tostring()) ::: $($Error[0].targetobject)"
"`tFAILED FOLDER`t$TempErrorVar" >> $LogFile
$script:FoldersFailed++
} else {
if ($VerboseLog) {"`tDELETED FOLDER`t$TempName" >> $LogFile}
$script:FoldersNumber++
}
}
}
}
# Check if correct parameters are used
if (-not $FolderPath) {Write-Warning 'Please specify the -FolderPath variable, this parameter is required. Use Get-Help .\deleteold.ps1 to display help.';exit}
if (-not $FileAge) {Write-Warning 'Please specify the -FileAge variable, this parameter is required. Use Get-Help .\deleteold.ps1 to display help.';exit}
if (-not $LogFile) {Write-Warning 'Please specify the -LogFile variable, this parameter is required. Use Get-Help .\deleteold.ps1 to display help.';exit}
if ($Autolog) {F_Autolog}
# Sets up the variables
$Startdate = Get-Date
$LastWrite = $Startdate.AddDays(-$FileAge)
$StartTime = $Startdate.toshortdatestring()+", "+$Startdate.tolongtimestring()
$Switches = "-FolderPath`r`n`t`t`t$FolderPath`r`n`t`t-FileAge $FileAge`r`n`t`t-LogFile`r`n`t`t`t$LogFile"
# Populate the switches string with the switches and parameters that are set
if ($IncludePath) {
$Switches += "`r`n`t`t-IncludePath"
for ($j=0;$j -lt $IncludePath.Count;$j++) {$Switches+= "`r`n`t`t`t";$Switches+= $IncludePath[$j]}
}
if ($ExcludePath) {
$Switches += "`r`n`t`t-ExcludePath"
for ($j=0;$j -lt $ExcludePath.Count;$j++) {$Switches+= "`r`n`t`t`t";$Switches+= $ExcludePath[$j]}
}
if ($IncludeFileExtension) {
$Switches += "`r`n`t`t-IncludeFileExtension"
for ($j=0;$j -lt $IncludeFileExtension.Count;$j++) {$Switches+= "`r`n`t`t`t";$Switches+= $IncludeFileExtension[$j]}
}
if ($ExcludeFileExtension) {
$Switches += "`r`n`t`t-ExcludeFileExtension"
for ($j=0;$j -lt $ExcludeFileExtension.Count;$j++) {$Switches+= "`r`n`t`t`t";$Switches+= $ExcludeFileExtension[$j]}
}
if ($ExcludeDate) {
$Switches+= "`r`n`t`t-ExcludeDate"
$ExcludeDate | ConvertFrom-Csv -Header:'Item1','Item2','Item3' -ErrorAction SilentlyContinue | ForEach-Object {
$Switches += "`r`n`t`t`t"
$Switches += ($_.Item1,$_.Item2,$_.Item3 -join ',').Trim(',')
}
}
if ($ListOnly) {$Switches+="`r`n`t`t-ListOnly"}
if ($VerboseLog) {$Switches+="`r`n`t`t-VerboseLog"}
if ($autolog) {$Switches+="`r`n`t`t-AutoLog"}
if ($CreateTime) {$Switches+="`r`n`t`t-CreateTime"}
if ($cleanfolders) {$Switches+="`r`n`t`t-CleanFolders"}
if ($nofolder) {$Switches+="`r`n`t`t-NoFolder"}
[long]$FilesSize = 0
[long]$FailedSize = 0
[int]$FilesNumber = 0
[int]$FilesFailed = 0
[int]$FoldersNumber = 0
[int]$FoldersFailed = 0
# Output text to console and write log header
Write-Host ("-"*79)
Write-Host " Deleteold`t::`tScript to delete old files from folders"
Write-Host ("-"*79)
Write-Host "`n Started : $StartTime`n Folder :`t$FolderPath`n Switches :`t$Switches`n"
if ($ListOnly){Write-Host "`t*** Running in Listonly mode, no files will be modified ***`n"}
Write-Host ("-"*79)
("-"*79) > $LogFile
" Deleteold`t::`tScript to delete old files from folders" >> $LogFile
("-"*79) >> $LogFile
" " >> $LogFile
" Started : $StartTime" >> $LogFile
" " >> $LogFile
" Folder : $FolderPath" >> $LogFile
" " >> $LogFile
" Switches : $Switches" >> $LogFile
" " >> $LogFile
("-"*79) >> $LogFile
" " >> $LogFile
# Define the properties to be selected for the array, if createtime switch is specified
# CreationTime is added to the list of properties, this is to conserve memory space
$SelectProperty = @{'Property'='Fullname','Length','PSIsContainer'}
if ($CreateTime) {
$SelectProperty.Property += 'CreationTime'
}
else {
$SelectProperty.Property += 'LastWriteTime'
}
if ($ExcludeFileExtension -or $IncludeFileExtension) {
$SelectProperty.Property += 'Extension'
}
# Get the complete list of files and save to array
Write-Host "`n Retrieving list of files and folders from: $FolderPath"
$CheckError = $Error.Count
$FullArray = @(Get-ChildItem $FolderPath -Recurse -ErrorAction SilentlyContinue -Force | select-object @SelectProperty)
# Catches errors during read stage and writes to log, mostly catches permissions errors
$CheckError = $Error.Count - $CheckError
if ($CheckError -gt 0) {
for ($j=0;$j -lt $CheckError;$j++) {
$TempErrorVar = "$($Error[0].tostring()) ::: $($Error[0].targetobject)"
"`tFAILED ACCESS`t$TempErrorVar" >> $LogFile
}
}
# Split the complete list of items into a separate list containing only the files
$FileList = @($FullArray | Where-Object {$_.PSIsContainer -eq $False})
# If the exclusion parameter is included then this loop will run. This will clear out any path not specified in the
# include parameter. If the ExcludePath parameter is also specified
if ($IncludePath) {
# Checks if all values in $ExcludePath end with \, if not present it will add it
# Reformats the $ExcludePath so the -notmatch command works, all slashes are repeat twice
# eg: c:\temp\ becomes c:\\temp\\
for ($j=0;$j -lt $IncludePath.Count;$j++) {
if ($IncludePath[$j].substring($IncludePath[$j].Length-1,1) -ne "\") {$IncludePath[$j] = $IncludePath[$j] + "\"}
}
$IncludePath = $IncludePath -replace '\\','\\'
$IncludePath = $IncludePath -replace '\$','\$'
for ($j=0;$j -lt $IncludePath.Count;$j++) {
[array]$NewFileList += @($FileList | Where-Object {$_.FullName -match $IncludePath[$j]})
}
$FileList = $NewFileList
$NewFileList=$null
}
# If the exclusion parameter is included then this loop will run. This will clear out the
# excluded paths for both the filelist.
if ($ExcludePath) {
# Checks if all values in $ExcludePath end with \, if not present it will add it
# Reformats the $ExcludePath so the -notmatch command works, all slashes are repeat twice
# eg: c:\temp\ becomes c:\\temp\\
for ($j=0;$j -lt $ExcludePath.Count;$j++) {
if ($ExcludePath[$j].substring($ExcludePath[$j].Length-1,1) -ne "\") {$ExcludePath[$j] = $ExcludePath[$j] + "\"}
}
$ExcludePath = $ExcludePath -replace '\\','\\'
$ExcludePath = $ExcludePath -replace '\$','\$'
for ($j=0;$j -lt $ExcludePath.Count;$j++) {
$FileList = @($FileList | Where-Object {$_.FullName -notmatch $ExcludePath[$j]})
}
}
# If the -IncludeFileExtension is specified all filenames matching the criteria specified
if ($IncludeFileExtension) {
for ($j=0;$j -lt $IncludeFileExtension.Count;$j++) {
# If no dot is present the dot will be added to the front of the string
if ($IncludeFileExtension[$j].Substring(0,1) -ne '.') {$IncludeFileExtension[$j] = ".$($IncludeFileExtension[$j])"}
[array]$NewFileList += @($FileList | Where-Object {$_.Extension -like $IncludeFileExtension[$j]})
}
$FileList = $NewFileList
$NewFileList=$null
}
# If the -ExcludeFileExtension is specified all filenames matching the criteria specified
if ($ExcludeFileExtension) {
for ($j=0;$j -lt $ExcludeFileExtension.Count;$j++) {
# If no dot is present the dot will be added to the front of the string
if ($ExcludeFileExtension[$j].Substring(0,1) -ne '.') {$ExcludeFileExtension[$j] = ".$($ExcludeFileExtension[$j])"}
$FileList = @($FileList | Where-Object {$_.Extension -notlike $ExcludeFileExtension[$j]})
}
}
# Counter for prompt output
$AllFileCount = $FileList.Count
# If the -CreateTime switch has been used the script looks for file creation time rather than
# file modified/lastwrite time
if ($CreateTime) {
$FileList = @($FileList | Where-Object {$_.CreationTime -le $LastWrite})
} else {
$FileList = @($FileList | Where-Object {$_.LastWriteTime -le $LastWrite})
}
# If the ExcludeDate parameter is specified the query is converted by the ConvertFrom-Query function. The
# output of that table is a hashtable that is splatted to the ConvertTo-DateObject function which returns
# an array of dates. All files that match a date in the returned array will be excluded from deletion which
# allows for more specific exclusions.
if ($ExcludeDate) {
$SplatDate = ConvertFrom-DateQuery $ExcludeDate
$ExcludedDates = ConvertTo-DateObject @SplatDate | Select-Object -Unique | Sort-Object -Descending
if ($CreateTime) {
for ($j=0;$j -lt $ExcludedDates.Count;$j++) {
$FileList = @($FileList | Where-Object {$_.CreationTime.Date -ne $ExcludedDates[$j]})
}
} else {
for ($j=0;$j -lt $ExcludedDates.Count;$j++) {
$FileList = @($FileList | Where-Object {$_.LastWriteTime.Date -ne $ExcludedDates[$j]})
}
}
[string]$DisplayExcludedDates = for ($j=0;$j -lt $ExcludedDates.Count;$j++) {
if ($j -eq 0) {
"`n ExcludedDates: $($ExcludedDates[$j].tostring('yyyy-MM-dd'))"
} else {
$ExcludedDates[$j].tostring('yyyy-MM-dd')
}
# After every fifth date start on the next line
if ((($j+1) % 6) -eq 0) {"`n`t`t "}
}
$DisplayExcludedDates
}
# Defines the list of folders, either a complete list of all folders if -EmptyFolder
# was specified or just the folders containing old files. The -NoFolder switch will ensure
# the folder structure is not modified and only files are deleted.
if ($CleanFolders) {
$FolderList = @($FullArray | Where-Object {$_.PSIsContainer -eq $True})
} elseif ($NoFolder) {
$FolderList = @()
} else {
$FolderList = @($FileList | ForEach-Object {
Split-Path -Path $_.FullName} |
Select-Object -Unique | ForEach-Object {
Get-Item -LiteralPath $_ -ErrorAction SilentlyContinue | Select-Object @SelectProperty})
}
# Clear original array containing files and folders and create array with list of older files
$FullArray = ""
# Write totals to console
Write-Host "`n Files`t: $AllFileCount`n Folders`t:"$FolderList.Count"`n Old files`t:"$FileList.Count
# Execute main functions of script
if (-not $ListOnly) {
Write-Host "`n Starting with removal of old files..."
} else {
Write-Host "`n Listing files..."
}
F_Deleteoldfiles
if (-not $ListOnly) {
Write-Host " Finished deleting files`n"
} else {
Write-Host " Finished listing files`n"
}
if (-not $ListOnly) {
Write-Host " Check/remove empty folders started..."
F_Checkforemptyfolder
Write-Host " Empty folders deleted`n"
}
# Pre-format values for footer
$EndDate = Get-Date
$TimeTaken = $Enddate - $StartDate
$TimeTaken = $TimeTaken.ToString().SubString(0,8)
$FilesSize = $FilesSize/1MB
[string]$FilesSize = $FilesSize.ToString()
$FailedSize = $FailedSize/1MB
[string]$FailedSize = $FailedSize.ToString()
$EndDate = "$($EndDate.toshortdatestring()), $($EndDate.tolongtimestring())"
# Output results to console
Write-Host ("-"*79)
Write-Host " "
Write-Host " Files : $FilesNumber"
Write-Host " Filesize(MB) : $FilesSize"
Write-Host " Files Failed : $FilesFailed"
Write-Host " Failedfile Size(MB) : $FailedSize"
Write-Host " Folders : $FoldersNumber"
Write-Host " Folders Failed : $FoldersFailed`n"
Write-Host " Finished Time : $EndDate"
Write-Host " Total Time : $TimeTaken`n"
Write-Host ("-"*79)
# Write footer to logfile
" " >> $LogFile
("-"*79) >> $LogFile
" " >> $LogFile
" Files : $FilesNumber" >> $LogFile
" Filesize(MB) : $FilesSize" >> $LogFile
" Files Failed : $FilesFailed" >> $LogFile
" Failedfile Size(MB) : $FailedSize" >> $LogFile
" Folders : $FoldersNumber" >> $LogFile
" Folders Failed : $FoldersFailed" >> $LogFile
" " >> $LogFile
" Finished Time : $EndDate" >> $LogFile
" Time Taken : $TimeTaken" >> $LogFile
" " >> $LogFile
("-"*79) >> $LogFile
# Clean up variables at end of script
$FileList=$FolderList = $null
|
PowerShellCorpus/GithubGist/goyuix_fd68db59a4f6355ee0f6_raw_a440851951fa6a8787eed0b0c853ab4b03d970e6_Modify-DefaultHive.ps1
|
goyuix_fd68db59a4f6355ee0f6_raw_a440851951fa6a8787eed0b0c853ab4b03d970e6_Modify-DefaultHive.ps1
|
Write-Host "Attempting to mount default registry hive"
& REG LOAD HKLM\DEFAULT C:\Users\Default\NTUSER.DAT
Push-Location 'HKLM:\DEFAULT\Software\Microsoft\Internet Explorer'
if (!(Test-Path Main)) {
Write-Warning "Adding missing default keys for IE"
New-Item Main
}
$sp = Get-ItemProperty -Path .\Main
Write-Host "Replacing $_ : $($sp.'Start Page')"
Set-ItemProperty -Path .\Main -Name "Start Page" -Value $site
Pop-Location
$unloaded = $false
$attempts = 0
while (!$unloaded -and ($attempts -le 5)) {
[gc]::Collect() # necessary call to be able to unload registry hive
& REG UNLOAD HKLM\DEFAULT
$unloaded = $?
$attempts += 1
}
if (!$unloaded) {
Write-Warning "Unable to dismount default user registry hive at HKLM\DEFAULT - manual dismount required"
}
|
PowerShellCorpus/GithubGist/rbenigno_6193856_raw_e2f21e9d90c9bb3481905cdd9306e294fff12baa_Test-DiskAccess-v2.ps1
|
rbenigno_6193856_raw_e2f21e9d90c9bb3481905cdd9306e294fff12baa_Test-DiskAccess-v2.ps1
|
Function Test-DiskAccess {
$filesize = 10MB #rough
$tempfolder = (Convert-Path (Get-Location -PSProvider FileSystem)) + "\NetAppTestTemp\"
If (!(Test-Path $tempfolder)){ New-Item -Path "$tempfolder" -ItemType Directory | Out-Null}
$MD5 = New-Object System.Security.Cryptography.MD5CryptoServiceProvider
while (1)
{
$testfilepath = "$tempFolder" + (Get-Random) + ".tmp"
$stream = New-Object System.IO.StreamWriter $testfilepath
write-host " Writing:" $testfilepath
$stream.WriteLine([string]([char](33..127|get-random)) * ($filesize))
$stream.close()
Start-Sleep -Second 1
$stream = New-Object System.IO.FileStream($testfilepath,`
[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,`
[System.IO.FileShare]::ReadWrite)
[byte[]]$ByteSum = $MD5.ComputeHash($stream)
$stream.Close()
Write-Host "Checksum:" $ByteSum
Start-Sleep -Second 1
Remove-Item $testfilepath
}
}
Test-DiskAccess
|
PowerShellCorpus/GithubGist/alvaroarias_4713812_raw_d94fe04f00d284b24f380edb39460fad3acb8d6c_UpdateUserProfilePictures.ps1
|
alvaroarias_4713812_raw_d94fe04f00d284b24f380edb39460fad3acb8d6c_UpdateUserProfilePictures.ps1
|
## Updates User Profile Pictures
## -----------------------------
## After backup-restore process the images still contain link to the original location
## this script replaces that links to point to the current location
## .\UpdateUserProfilePictures.ps1 "<CurrentSiteUrl>"
## Remember to update the $prodUrlWildcard variable
param([string]$mySiteUrl)
$prodUrlWildcard = "https://yourProductionMySiteUrl*"
$mySiteHostSite = Get-SPSite $MySiteUrl
$mySiteHostWeb = $mySiteHostSite.OpenWeb()
$context = Get-SPServiceContext $mySiteHostSite
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$userProfiles = $profileManager.GetEnumerator();
Write-Host "Start processing profiles"
foreach($profile in $userProfiles)
{
Write-Host "Start processing " $profile.DisplayName
if($profile["PictureURL"].Value -ne $null -and $profile["PictureURL"].Value -ne "" )
{
Write-Host "Start processing " $profile.DisplayName
$picture = $profile["PictureURL"].Value
if ($picture -like $prodUrlWildcard)
{
$profile["PictureURL"].Value = $picture -replace $prodUrlWildcard, $mySiteUrl
$profile.Commit()
Write-Host "Modified " $profile.DisplayName -Foregroundcolor green
}
}
}
|
PowerShellCorpus/GithubGist/HowardvanRooijen_5498260_raw_c9290d37f35b582d0686e3aa4754b594498a168e_gistfile1.ps1
|
HowardvanRooijen_5498260_raw_c9290d37f35b582d0686e3aa4754b594498a168e_gistfile1.ps1
|
# This is the public script we call as an entry point into the deployment / configuration process
Function Invoke-Deployment
{
Param
(
$ApplicationPool,
$WebSite
)
Invoke-AppPoolTasks @PSBoundParameters
Invoke-WebSiteTasks @PSBoundParameters
}
# The main script for managing ApplicationPools
Function Invoke-AppPoolTasks
{
Param
(
# this is essentially a hashtable that contains all the properties we need
# we can then use PS dot notation to step into the property we want to access
# as if we had a fully fledged object model
$ApplicationPool
)
Write-Host $ApplicationPool.Name
}
# The main script for managing WebSites
Function Invoke-WebSiteTasks
{
Param
(
$WebSite
)
Write-Host $Website.Name
Write-Host $Website.ApplicationPoolName
# we can access each property manually, for example $Website.Bindings[0].Ip or by looping
foreach($binding in $Website.Bindings)
{
Write-Host ("{0}:{1}:{2}" -f $binding.Ip, $binding.Port, $binding.HostName)
}
}
# We can define a stronger object model, which is essentially dynamic and easy to extend
$parameters = @{
ApplicationPool = @{
Name = "Endjin_Web_App_Pool"
}
WebSite = @{
Name = "Endjin_Web"
ApplicationPoolName = "Endjin_Web_App_Pool"
Bindings = @(
@{
Ip = "192.168.100.10"
Port = "80"
HostName = "endjin.com"
},
@{
Ip = "192.168.100.10"
Port = "443"
HostName = "endjin.com"
}
)
}
}
Clear-Host
Invoke-Deployment @parameters
|
PowerShellCorpus/GithubGist/CombustibleLemon_ca9f31ad9f41fa05a576_raw_d0bf7cc56afc36aa14ee6681e8616114b2dd519d_git-merge.ps1
|
CombustibleLemon_ca9f31ad9f41fa05a576_raw_d0bf7cc56afc36aa14ee6681e8616114b2dd519d_git-merge.ps1
|
# Pull from PWNAGERobotics/PWNAGE
git fetch upstream
# Checkout user master
git checkout master
# Merge PWNAGERobotics/PWNAGE:master into local user/PWNAGE:master
git merge upstream/master
# Push to user/PWNAGE:master origin
git push
|
PowerShellCorpus/GithubGist/Thermionix_0b6382b5a121942000e4_raw_c124277858afe170997fca106bd7cb24c3848d43_svn-to-git.ps1
|
Thermionix_0b6382b5a121942000e4_raw_c124277858afe170997fca106bd7cb24c3848d43_svn-to-git.ps1
|
$rev=40469 ; $url="svn://svn/test/branches/1.0.3" ; $clonedir="C:\source\test" ; $gitbin="${env:ProgramFiles(x86)}\Git\bin" ; cmd /c "svn diff --force --patch-compatible --diff-cmd `"$gitbin\diff.exe`" -x `"--text --unified`" -c $rev $url | git apply --directory=`"$clonedir`" -p0 --reject --verbose -"
|
PowerShellCorpus/GithubGist/wiliammbr_947bf9b5d5299fd3a117_raw_69bd05c41083b44bdcda2a0355a68a1a34284dfd_RecoverLookup.ps1
|
wiliammbr_947bf9b5d5299fd3a117_raw_69bd05c41083b44bdcda2a0355a68a1a34284dfd_RecoverLookup.ps1
|
$webURL = "http://localhost"
$listName = "ListName"
$columnName = "LookupColumn"
$lookupWebURL = "http://localhost"
$lookupListName = "LookupListName"
# Código do Powershell
function RepairLookup($webURL, $listName, $columnName, $lookupListName, $lookupWebURL)
{
# Obtem a Web, a Lista e a Coluna
$web = Get-SPWeb $webURL
$list = $web.Lists[$listName]
$column = $list.Fields[$columnName]
# Obtem a Web e a Lista do tipo Lookup
$lookupWeb = Get-SPWeb $lookupWebURL
$lookupList = $lookupWeb.Lists[$lookupListName]
# Separa os IDs que atualizarão a Coluna quebrada
$newLookupListID = $lookupList.ID.ToString()
$newLookupWebID = $lookupWeb.ID.ToString()
# Realiza um 'Replace' no XML que define a Coluna quebrada
$column.SchemaXml = $column.SchemaXml.Replace($column.LookupWebId.ToString(), $newLookupWebID)
$column.SchemaXml = $column.SchemaXml.Replace($column.LookupList.ToString(), $newLookupListID)
$column.Update()
# Escreve uma mensagem no final, informando que deu tudo certo
write-host "No site " $web.Url " a coluna " $column.Title " da lista " $list.Title " foi conectada com a lista " $lookupList.Title " do site " $lookupWeb.Url
# Libera a memoria
$web.Dispose()
$lookupWeb.Dispose()
}
# Faz a chamada do metodo
RepairLookup -webURL $webURL -listName $listName -columnName $columnName -lookupListName $lookupListName -lookupWeb $lookupWebURL
|
PowerShellCorpus/GithubGist/grenade_8459746_raw_b9789e64152bc5eba673bceea4300aa92f14bfed_set-connection-string.ps1
|
grenade_8459746_raw_b9789e64152bc5eba673bceea4300aa92f14bfed_set-connection-string.ps1
|
$connectionString = "Data Source=localhost;Initial Catalog=SomeDatabase;Integrated Security=True"
$config = "path\to\app.config"
$xml = (Get-Content $config) -as [xml]
$xml.SelectSingleNode('/configuration/connectionStrings/add[@name="ConnectionString.Key"]/@connectionString').set_InnerXML($connectionString)
$xml.Save($config)
|
PowerShellCorpus/GithubGist/philbritton_7427115_raw_602b585a6592329fbe0c68826b5af5a3f6103ebb_killerwindowsconfig.ps1
|
philbritton_7427115_raw_602b585a6592329fbe0c68826b5af5a3f6103ebb_killerwindowsconfig.ps1
|
#########################
# Autoinstall script using chocolatey
#########################
# Note: Net 4.0 must be installed prior to running this script
#
#Modify this line to change packages
$items = @("git-credential-winstore", "console-devel", "sublimetext3", "poshgit", "driverbooster", "revouninstallerpro", "malwarebytes", "powerquery", "TimRayburn.GitAliases", "sudo", "Evernote5", "javaruntime", "DotNet4.5.1", "NSSM", "ConsoleZ", "git.install")
#################
# Create packages.config based on passed arguments
#################
$xml = '<?xml version="1.0" encoding="utf-8"?>'+ "`n" +'<packages>' + "`n"
foreach ($item in $items)
{
$xml += "`t" +'<package id="' + $item + '"/>' + "`n"
}
$xml += '</packages>'
$file = ([system.environment]::getenvironmentvariable("userprofile") + "\packages.config")
$xml | out-File $file
####
# Install chocolatey
####
# iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
######
# Install packages with cinst
######
cinst $file
########
# Delete packages.config
Remove-Item $file
|
PowerShellCorpus/GithubGist/hachibeeDI_4351161_raw_4578fb32701eb3b514ca7af102be1303e7876918_generate_csv.ps1
|
hachibeeDI_4351161_raw_4578fb32701eb3b514ca7af102be1303e7876918_generate_csv.ps1
|
$key_codefile = $args[0]
$random = new-Object random
function get_random_word {
$li = 'abcdefghijklmnopqrstuvwxyz'
return $li[$random.next(0, 26)]
}
function get_random_words([Int]$limit) {
return { (1..$limit | %{ get_random_word }) -join "" }.GetNewClosure()
}
#9以上だとintからあふれるので9まで
function get_random_numbers([int]$limit) {
return { $random.next('0' * $limit, '9' * $limit) }.GetNewClosure()
}
function get_random_bylist {
$limit = $args.Length
$valuelist = $args #scriptblock内でargsへの上書きが起きるので
return { $valuelist[$random.next(0, $limit)] }.GetNewClosure()
}
function get_random_numbers_byrange([int]$limit) {
return { $random.next(0, $limit) }.GetNewClosure()
}
function get_datetime() {
return { Get-Date -format "yyyy-MM-dd hh:mm:ss" }
}
$wor = get_random_words(13)
$num = get_random_numbers(9)
$lis = get_random_bylist '01' '02' '03' '04' '05' '06' '99'
$dat = get_datetime
$each_line = @($wor, $num, $lis, $dat)
# 遅延評価の連鎖
$csv_line = { $($each_line | %{ "`"$(&$_)`"" } ) -join "," }
$content = 0..100 | % { "$(& $csv_line)" }
$content | %{ echo $_ }
|
PowerShellCorpus/GithubGist/abombss_1129655_raw_d7149834d492c58e25e08934387815b6120878eb_toggle-list-sep.ps1
|
abombss_1129655_raw_d7149834d492c58e25e08934387815b6120878eb_toggle-list-sep.ps1
|
function toggle-list-sep
{
$path = "hkcu:\Control Panel\International"
$key = "sList"
$cur_sep = (Get-ItemProperty -path $path -name $key).$key
if ($args.Length -gt 0) { $value = $args[0] }
elseif ($cur_sep -eq ",") { $value = "|" }
else { $value = "," }
Set-ItemProperty -path $path -name $key -Value $value -type string
$new_sep = (Get-ItemProperty -path $path -name $key).$key
Write-Output "Changed $path.$key from '$cur_sep' to '$new_sep'"
}
|
PowerShellCorpus/GithubGist/dklevakin_8056743_raw_4588dae8f3bb5cd6da6b19d756dbcf48ebdf0882_hosts.ps1
|
dklevakin_8056743_raw_4588dae8f3bb5cd6da6b19d756dbcf48ebdf0882_hosts.ps1
|
#
# Powershell script for adding/removing/showing entries to the hosts file.
#
# Known limitations:
# - does not handle entries with comments afterwards ("<ip> <host> # comment")
#
$file = "C:\Windows\System32\drivers\etc\hosts"
function add-host([string]$filename, [string]$ip, [string]$hostname) {
remove-host $filename $hostname
$ip + "`t`t" + $hostname | Out-File -encoding ASCII -append $filename
}
function remove-host([string]$filename, [string]$hostname) {
$c = Get-Content $filename
$newLines = @()
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
if ($bits[1] -ne $hostname) {
$newLines += $line
}
} else {
$newLines += $line
}
}
# Write file
Clear-Content $filename
foreach ($line in $newLines) {
$line | Out-File -encoding ASCII -append $filename
}
}
function print-hosts([string]$filename) {
$c = Get-Content $filename
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
Write-Host $bits[0] `t`t $bits[1]
}
}
}
try {
if ($args[0] -eq "add") {
if ($args.count -lt 3) {
throw "Not enough arguments for add."
} else {
add-host $file $args[1] $args[2]
}
} elseif ($args[0] -eq "remove") {
if ($args.count -lt 2) {
throw "Not enough arguments for remove."
} else {
remove-host $file $args[1]
}
} elseif ($args[0] -eq "show") {
print-hosts $file
} else {
throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove', 'show'."
}
} catch {
Write-Host $error[0]
Write-Host "`nUsage: hosts add <ip> <hostname>`n hosts remove <hostname>`n hosts show"
}
|
PowerShellCorpus/GithubGist/tmichel_4986618_raw_605f8bb297cd3dc07273fee2aa01f97b7c3fcea9_gistfile1.ps1
|
tmichel_4986618_raw_605f8bb297cd3dc07273fee2aa01f97b7c3fcea9_gistfile1.ps1
|
ls -Recurse | ? { $_ -match "^(bin|obj)$" }
|
PowerShellCorpus/GithubGist/ao-zkn_9b5b0a1e4c8d9ac259a0_raw_3e9f423ed28ffaa13dae2ae5d09ff8523d5e5fe2_Convert-SnakeToCamel.ps1
|
ao-zkn_9b5b0a1e4c8d9ac259a0_raw_3e9f423ed28ffaa13dae2ae5d09ff8523d5e5fe2_Convert-SnakeToCamel.ps1
|
# ------------------------------------------------------------------
# スネークケースをキャメルケースに変換する
# 関数名:Convert-SnakeToCamel
# 引数 :Snake スネークケース文字列
# 戻り値:キャメルケース文字列
# ------------------------------------------------------------------
function Convert-SnakeToCamel([String]$Snake){
$regex=[regex]"_[a-zA-Z]{1}"
$regex.Matches($Snake)|ForEach{
$Snake = $Snake -replace $_.value, ($_.value).SubString(1,1).toUpper()
}
return $Snake
}
|
PowerShellCorpus/GithubGist/simplement-e_5382683_raw_775dfca9eba06a5945cc4dfbe585f91142a55748_get-mediation-etat.ps1
|
simplement-e_5382683_raw_775dfca9eba06a5945cc4dfbe585f91142a55748_get-mediation-etat.ps1
|
# la recherche à effectuer :
$recherche = '*sip*'
# si vous êtes sur un poste avec vos identifiants sauvegardés
Connect-e_session
# dans le cas contraire, vous devrez préciser les paramètres
# ServerUrl : l'url racine de votre gestion commerciale
# Username : l'adresse e-mail de connexion à utiliser
# Password : le mot de passe associé
# Connect-e_session -serverurl 'http://e-gestcom' -Username test@test.com -password test123#
Get-e_mediationtype $recherche
|
PowerShellCorpus/GithubGist/ab9rf_5586006_raw_f593cf00cb8b13f3d80e86bab4977f67f2de5c18_uninstall-ie10.ps1
|
ab9rf_5586006_raw_f593cf00cb8b13f3d80e86bab4977f67f2de5c18_uninstall-ie10.ps1
|
$Updates = "50ff45dd-fc70-4e32-8698-a3d112e59ef1", "c0b3230a-bb79-4e44-b771-177bc224fcbf", "5f84379f-7c14-472f-b560-62a0cdec6f31", "ca2a186f-626f-401f-9cb1-68f859acbbf7"
$updatefilter = ($Updates | % { "UpdateID = '$_'" } ) -join " or "
$us = New-Object -ComObject "Microsoft.Update.Session"
$ss = $us.createupdateSearcher()
Write-Host "Scanning for IE10 updates..."
$sr = $ss.search($updatefilter)
$uninst = $False
foreach ($upd in $sr.updates) {
if ($upd.IsInstalled) { $uninst = $True }
if ($upd.IsHidden) { $status = "already hidden" }
else { $upd.IsHidden = $True; $status = "now hidden" }
Write-Host $upd.Identity.UpdateID $upd.Title $status
}
if ($uninst) {
Write-Host "Uninstalling IE10..."
wusa.exe /uninstall /quiet /norestart /KB:2718695
}
|
PowerShellCorpus/GithubGist/rdsimes_6190832_raw_26ba0b57cce78133784c8ad24de74aea25c3b061_restart-visual-studio.ps1
|
rdsimes_6190832_raw_26ba0b57cce78133784c8ad24de74aea25c3b061_restart-visual-studio.ps1
|
function Stop-Vs {
$currentApp = Split-Path $pwd -leaf
Get-Process -Name devenv | where {$_.mainWindowTitle -like "*$currentApp*"} | Stop-Process
}
function Start-Vs {
$currentApp = Split-Path $pwd -leaf
& .\$currentApp.sln
}
|
PowerShellCorpus/GithubGist/rodolfofadino_10173639_raw_0ed2a73ef413cdc5623805c8224c0715409ac365_deployiisnlb.ps1
|
rodolfofadino_10173639_raw_0ed2a73ef413cdc5623805c8224c0715409ac365_deployiisnlb.ps1
|
Import-Module NetworkLoadBalancingClusters
$CopyOrigin="C:\inetpub\wwwroot\xxxx"
$TimeOut=5
$Servers = New-Object System.Collections.ArrayList
$Servers.Add(@{Ip="xxx.xxx.xxx";Path="E:\xxxx";Urls=("/","/appx")})
$Servers.Add(@{Ip="xxx.xxx.xxx";Path="F:\xxxx";Urls=("/","/appx")})
$Servers.Add(@{Ip="xxx.xxx.xxx";Path="G:\xxxx";Urls=("/","/appx")})
$Servers.Add(@{Ip="xxx.xxx.xxx";Path="H:\xxxx";Urls=("/","/appx")})
foreach($Server in $Servers)
{
Write-Host "Starting deploy on $Server.Ip"
Write-Host "Stopping NLB cluster..."
Stop-NlbClusterNode -Hostname $Server.Ip
Start-Sleep -Second $TimeOut
Write-Host "Copying files..."
robocopy $CopyOrigin $Server.Path /S /E
Start-Sleep -Second $TimeOut
foreach($Url in $Server.Urls){
$s=$Server.Ip
Write-Host "Warming up (http://$s$Url)..."
Write-Host http://$s$Url
$request = [System.Net.WebRequest]::Create("http://$s$Url")
$response=$request.GetResponse()
$response.Close()
}
Start-Sleep -Second $TimeOut
Write-Host "Starting NLB cluster..."
Start-NlbClusterNode -Hostname $Server.Ip
Write-Host $Server.Ip
Write-Host "Done!"
}
|
PowerShellCorpus/GithubGist/monahancj_7fbca58bc80443dffd38_raw_8a2ce9d108d7a0882787ed16e0008f3328ab558e_vCheckUpgradeUtils.ps1
|
monahancj_7fbca58bc80443dffd38_raw_8a2ce9d108d7a0882787ed16e0008f3328ab558e_vCheckUpgradeUtils.ps1
|
<#
.SYNOPSIS
Lists the variables in vCheck plugin files.
.DESCRIPTION
Plugin file will be scanned as a text file and any variables in between the "Start of Settings"
and "End of Settings" section markers will be sent out the pipeline. Files can be sent in
via the pipeline or individually with a loop. If using the "-Verbose" option for troubleshooting
then using a loop is recommended.
.PARAMETER PluginFile
The file to be processed. Can be passed as text, a file object, or a set of files, such as
"Get-ChildItem *.ps1".
.EXAMPLE
Simple
Get-vCheckVariablesSettings -PluginFile "c:\scripts\vcheck6\vcenter\Plugins\20 Cluster\75 DRS Rules.ps1"
Recursed
Get-ChildItem -Path E:\vCheckLatestTesting -File -Filter *.ps1 -Recurse | % { Get-vCheckVariablesSettings -PluginFile $_.FullName }
.INPUTS
System.IO.FileInfo
.OUTPUTS
File Selected.System.Management.Automation.PSCustomObject The 'Fullname' property from the plugin file.
Variable Selected.System.Management.Automation.PSCustomObject The text of the variable assignment from the plugin file.
.NOTES
With multiple vCheck directories to upgrade I needed an easy to pull the variables used
in the old vCheck installation to go into the new version.
.LINK
https://github.com/alanrenouf/vCheck-vSphere
Recent Comment History
20150127 cmonahan Initial release.
#>
Function Get-vCheckVariablesSettings {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)] $PluginFile
)
#begin {
Write-Verbose "Started $PluginFile"
if (Test-Path $PluginFile) {
$PluginFile = Get-ChildItem $PluginFile
$contents = Get-Content $PluginFile
$end = $contents.length }
else { throw "Value passed to File parameter is not a file." }
$i=0
#} # end begin block
#process {
while ( ($i -lt $end) -and ($contents[$i] -notmatch "Start of Settings") ) { $i++ }
while ( ($i -lt $end) -and ($contents[$i] -notmatch "End of Settings") ) {
if ($contents[$i] -match "`=") { "" | select @{n='File';e={$PluginFile.fullname}},@{n='Variable';e={$contents[$i]}}; $i++ }
else { $i++ }
}
#} #end process block
#end {
Write-Verbose "Ended $PluginFile"
#} #end end block
<#
Recent Comment History
20150127 cmonahan Initial release.
#>
} # end function
<#
.SYNOPSIS
Matches the disabled plugins in a target directory with those in a source directory.
.DESCRIPTION
I wrote it for when I'm upgrading vCheck. This will go through the old directory and
any plugin marked as disabled there will be marked as disabled in the new directory.
.PARAMETER OldVcheckDir
What you you think it is.
.PARAMETER NewVcheckDir
No tricks here.
.EXAMPLE
Sync-vCheckDisabledPlugins -OldVcheckDir c:\scripts\vcheck6\vccenter_old_20150218_163057 -NewVcheckDir c:\scripts\vcheck6\vcenter
.LINK
https://github.com/alanrenouf/vCheck-vSphere
Recent Comment History
20150128 cmonahan Initial release.
#>
function Sync-vCheckDisabledPlugins {
[cmdletbinding(SupportsShouldProcess=$True)]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] $OldVcheckDir,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] $NewVcheckDir
)
# $WhatIfPreference
$OldVcheckPluginsDir = (Get-ChildItem "$($OldVcheckDir)\Plugins").PsParentPath
$NewVcheckPluginsDir = (Get-ChildItem "$($NewVcheckDir)\Plugins").PsParentPath
$OldDisabled = Get-ChildItem $OldVcheckDir -Recurse | ? { $_ -like "*.disabled" } #| select -First 1
$OldDisabled
foreach ($file in $OldDisabled) {
Get-ChildItem $NewVcheckDir -Recurse | Where-Object { $_ -match $file.Name } | Select-Object FullName
Get-ChildItem $NewVcheckDir -Recurse -Filter $file.BaseName | ForEach-Object { Move-Item -Path $_.FullName -Destination ($_.FullName -replace("ps1","ps1.disabled")) }
}
<# Comment History
20150128 cmonahan Initial release.
#>
} # end function
<#
.SYNOPSIS
Lists the disabled plugins in a target directory.
.DESCRIPTION
Essentially a stripped down version of Sync-vCheckDisabledPlugins I threw it in
in case someone found it useful.
.PARAMETER VcheckDir
What you you think it is.
.EXAMPLE
Get-vCheckDisabledPlugins -VcheckDir c:\scripts\vcheck6\vcenter
.LINK
https://github.com/alanrenouf/vCheck-vSphere
Recent Comment History
20150128 cmonahan Initial release.
#>
function Get-vCheckDisabledPlugins {
param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)] $vCheckDir )
Get-ChildItem (Get-ChildItem "$($vCheckDir)\Plugins").PsParentPath -Recurse | ? { $_ -like "*.disabled" } #| select -First 1
<# Comment History
20150128 cmonahan Initial release.
#>
} # end function
<#
.SYNOPSIS
Does most of the work upgrading to a new version of vCheck.
.DESCRIPTION
This function will:
-Backup the current directory by renaming it with the current date
-Copy in the new version from a directory you've specified
-Save all the variable settings to a text file
-Set the same disabled plugins in the new version
-Opens the saved variable settings in Notepad
Then run vCheck.ps1 for the first time to configure it using the
variables listing open in Notepad as a reference.
.PARAMETER CurrentvCheckPath
Directory to be upgraded.
.PARAMETER NewvCheckSource
Location of the new version downloaded from GitHub.
.EXAMPLE
Upgrade-vCheckDirectory -CurrentvCheckPath c:\scripts\vcheck6\vcenter -NewvCheckSource c:\scripts\vcheck6\vcenter\vCheck-vSphere-master
.NOTES
If you have multiple directories and some settings like smtp server
are the same for them all you could upgrade the file(s) in the new
vCheck version directory and they'll be copied out with each upgrade.
.LINK
https://github.com/alanrenouf/vCheck-vSphere
Recent Comment History
20150127 cmonahan Initial release.
#>
Function Upgrade-vCheckDirectory {
param (
[Parameter(Position=0,Mandatory=$true)] $CurrentvCheckPath,
[Parameter(Position=1,Mandatory=$true)] $NewvCheckSource
)
function Get-Now { (get-date -uformat %Y%m%d) + "_" + (get-date -uformat %H%M%S) }
$TS = Get-Now # TS means time stamp
# Test that directories exist
if ( !(Test-Path -Path $CurrentvCheckPath) ) { break }
if ( !(Test-Path -Path $NewvCheckSource) ) { break }
$OldvCheckPath = "$($CurrentvCheckPath)_old_$($TS)"
$OldvCheckVariables = "$($OldvCheckPath)\vCheckVariables_$($TS).txt"
# Backup current directory and setup new directory
Move-Item -Path $CurrentvCheckPath -Destination $OldvCheckPath
mkdir $CurrentvCheckPath
robocopy $NewvCheckSource $CurrentvCheckPath /s /e /z /xj /r:2 /w:5 /np
# Save variable settings
Get-ChildItem -Path $OldvCheckPath -Filter *.ps1 -Recurse | % { Get-vCheckVariablesSettings -PluginFile $_.FullName } | Format-Table -AutoSize | Out-File -FilePath $OldvCheckVariables
# Make the disabled plugins match
Sync-vCheckDisabledPlugins -OldVcheckDir $OldvCheckPath -NewVcheckDir $CurrentvCheckPath
# Configure it
notepad $OldvCheckVariables
Write-Output "Locally on the server hosting the vCheck script run vCheck.ps1"
<# Comment History
20150128 cmonahan Initial release.
#>
} # end function
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.