full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/wurmr_9843120_raw_b3043cf86ab1a6d63c9b92cb49758836dec39d66_sqlDeploy.ps1
wurmr_9843120_raw_b3043cf86ab1a6d63c9b92cb49758836dec39d66_sqlDeploy.ps1
function Get-MSWebDeployInstallPath() { return (get-childitem "HKLM:\SOFTWARE\Microsoft\IIS Extensions\MSDeploy" | Select -last 1).GetValue("InstallPath") } function Load-Configuration { $webDeploy = Get-MSWebDeployInstallPath $env:Path += (";" + $webDeploy) } try { Load-Configuration $Depacs = (Get-ChildItem *.dacpac | Select BaseName, FullName) foreach ($depac in $Depacs) { $destinationDatabase = $OctopusParameters["DbServer"]; $depacFile = ($depac | Select -ExpandProperty FullName) $databaseName = ($depac | Select -ExpandProperty BaseName) $Args = @('-Verb:Sync', "-Source:dbDacFx='$depacFile'", "-Dest:dbDacFx='Server=$destinationDatabase;Database=$databaseName;Trusted_Connection=True'") Write-Host $Args; & 'msdeploy.exe' $Args } } catch { Write-Host $_.Exception throw $_.Exception }
PowerShellCorpus/GithubGist/NotMyself_b184fa4e9ac010b26302_raw_0aea1a4f22fdf8191a56c3b567d47a2833f2b071_gistfile1.ps1
NotMyself_b184fa4e9ac010b26302_raw_0aea1a4f22fdf8191a56c3b567d47a2833f2b071_gistfile1.ps1
$dir = 'c:\exports\' $years = @{ 2013=18 } #;2014=19;2012=17; 2011=16; 2010=15; 2009=14; 2008=13; 2007=12; 2006=11 $domains = @("MSPHSPE", "EOC", "WAAS", "WELPA") #"MSPHSPE", "EOC", "WAAS", "WELPA", "AYP" $years.Keys | % { $path = "$dir$_\" if((Test-Path -Path $path)) { Remove-Item -Recurse -Force $path } New-Item -ItemType directory -Path $path $year = $years[$_] $domains | ForEach-Object { Invoke-Expression ".\GenerateDownloadFiles.exe -o $path -y $year -d $_" } }
PowerShellCorpus/GithubGist/chgeuer-duplicate_1054674_raw_5e8fc7b4ff6e0430175ca74ff36577a18d0a0b76_Download-SysInternals.ps1
chgeuer-duplicate_1054674_raw_5e8fc7b4ff6e0430175ca74ff36577a18d0a0b76_Download-SysInternals.ps1
$currentDir = (Get-Location -PSProvider FileSystem).ProviderPath function InstallSysInternalsComponent([System.String] $filename, [System.String] $RegistryName) { $binaryDir = (Get-Location -PSProvider FileSystem).ProviderPath + [System.IO.Path]::DirectorySeparatorChar # [HKEY_CURRENT_USER\Software\Sysinternals\PsExec] # "EulaAccepted"=dword:00000001 $f = Test-Path -Path "HKCU:\Software\SysInternals" if (!$f) { Write-Host "Create main key" $ignore = New-Item -Path "HKCU:\Software\SysInternals" -type Directory } $f = Test-Path -Path "HKCU:\Software\SysInternals\$RegistryName" if (!$f) { Write-Host "Create sub key" $ignore = New-Item -Path "HKCU:\Software\SysInternals\$RegistryName" -type Directory } $ignore = New-ItemProperty -Path "HKCU:\Software\SysInternals\$RegistryName" -Name "EulaAccepted" -PropertyType DWord -Value 1 -Force $f = Test-Path $filename if (!$f) { $url = [System.String]::Format("http://live.sysinternals.com/{0}", $filename) $wc = (New-Object System.Net.WebClient) $path = [System.IO.Path]::Combine($binaryDir, $filename) Write-Host "Downloading application '$RegistryName' from $url to $path" $wc.DownloadFile($url, $path) Write-Host "Done..." } } InstallSysInternalsComponent "accesschk.exe" "AccessChk" InstallSysInternalsComponent "accessenum.exe" "AccessEnum" InstallSysInternalsComponent "psexec.exe" "PsExec" InstallSysInternalsComponent "procexp.exe" "Process Explorer" InstallSysInternalsComponent "procmon.exe" "Process Monitor" InstallSysInternalsComponent "Dbgview.exe" "DbgView"
PowerShellCorpus/GithubGist/hapylestat_9b1fc3947e717701454d_raw_ef0db275b69e844fe766c7987c81737ab345913a_mount_drive.ps1
hapylestat_9b1fc3947e717701454d_raw_ef0db275b69e844fe766c7987c81737ab345913a_mount_drive.ps1
################################################ # Map shares # # Author: H.L. # # Version: 0.3 # # Description: map shares to the system # ################################################ #############################what's new #--v0.3-- #- Mount fix, while described multiple shares #- Possibility to skip asking credentials #--v0.2-- #- fix small error's in code #- fix values moved to system settings #- if credentials was not set script will ask for that using password form #- template for domain like accounts #--v0.1-- #- Basic functionality #- Try to mount drive 3 times(fixed) #- timeout to mount operation, max 8 sec, fixed #- password can be set inside script only ######################################## #vars--system settings [int]$global:_mnt_max_trys = 3; [int]$global:_mnt_min_waittime= 8; [bool]$global:_mnt_increase_waittime= $False; [int]$global:_mnt_increase_step= 3; #--vars-global $global:version="v0.3"; $global:_share=""; #!!! type here ip address of host $global:_domain=""; #used only in case of blank username and password #!!credentials - leave blank to show "ask user name" every time before launch $global:_usepass=$False; $global:_user=""; $global:_pass=""; $global:_drives=( ("O:","SomeShare") #!!!!describe here list of shares ); #functions function startApp([string]$name,[string]$prms,[int]$wait){ $si=new-object System.Diagnostics.ProcessStartInfo; $si.UseShellExecute = $False; $si.RedirectStandardError=$True; $si.RedirectStandardOutput=$True; $si.FileName = $name; $si.Arguments = $prms; try{ $process=[System.Diagnostics.Process]::Start($si); $spend_time=0; while ( $spend_time -lt ($wait*1000)){ if ($process.HasExited -eq $True) { if ($process.ExitCode -gt 0){ return $False; } else { return $True; } } Start-Sleep -m 200; $spend_time+=200; } $process.Kill; #workaround =( Stop-Process $process.Id; return $False; } catch { return $False; } } function callMounter($event, [int]$wtime, [string]$mntpoint="",[string]$share=""){ switch ($event){ "mount"{ if ($global:_usepass -eq $True){ return (startApp "net.exe" "use $mntpoint \\$global:_share\$share $global:_pass /USER:$global:_user /persistent:no" $wtime); } else { return (startApp "net.exe" "use $mntpoint \\$global:_share\$share /persistent:no" $wtime); } } "unmount"{ return (startApp "net.exe" "use /delete $mntpoint" $wtime); } } return $False; } function unmountDrive([string]$drive){ #return startApp "net.exe" "use /delete $drive" 3; return callMounter "unmount" 3 $drive; } function mountDrive{ Param([string]$share,[string]$mntpoint,[int]$tTry) ; $waittime=$global:_mnt_min_waittime; $canExit=0; $curr_pos=$host.ui.rawui.CursorPosition; #unmount previous drive Write-Host "Try to unmount $mntpoint..." -noNewLine; unmountDrive $mntpoint; $host.ui.rawui.CursorPosition=$curr_pos; Write-Host " " -noNewLine; $host.ui.rawui.CursorPosition=$curr_pos; #try to mount new drive Write-Host "Mounting $share at $mntpoint...." -noNewLine; $curr_pos=$host.ui.rawui.CursorPosition; while ($canExit -lt $tTry){ # if ( (startApp "net.exe" "use $mntpoint \\$global:_share\$share $global:_pass /USER:$global:_user /persistent:no" $waittime) -eq $True){ if ( (callMounter "mount" $waittime $mntpoint $share) -eq $True){ if ($canExit -gt 0){ Write-Host "] " -noNewLine; } Write-Host "ok"; $canExit=$tTry; return $True; } else { if ($canExit -eq 0){ # first time showed Write-Host "[" -noNewLine; } Write-Host "." -noNewLine; if ($canExit -eq ($tTry-1)){ Write-Host "] fail"; } } #wait time handling if ($global:_mnt_increase_waittime -eq $True){ $waittime+=$global:_mnt_increase_step; } $canExit++; } return $False; } #===========================================main() Write-Host "Network Share mounter $global:version" -foregroundcolor Cyan; if ($global:_user -eq "" -and $global:_pass -eq "" -and $global:_usepass -eq $True){ Write-Host "Username and Password is required...."; try{ $credential= Get-Credential ""; $global:_user=$credential.GetNetworkCredential().username; $global:_pass=$credential.GetNetworkCredential().password; if ($global:_domain -ne ""){ $global:_user=$global:_domain+"\"+$global:_user; } } catch { Write-Host "Login is invalid or operation canceled." -foregroundcolor "Red"; Start-Sleep -s 2; exit; } } if ($global:_drives[0].GetType().BaseType.Name -ne "Array"){ #array contain only one element mountDrive $global:_drives[1] $global:_drives[0] $global:_mnt_max_trys|out-null; } else { foreach ( $map in $global:_drives ) { mountDrive $map[1] $map[0] $global:_mnt_max_trys|out-null; } } exit; #======conditions #-eq Equal to #-lt Less than #-gt Greater than #-ge Greater than or Eqaul to #-le Less than or equal to #-ne Not equal to #====logic operators # -not Not # ! Not # -and And # -or Or
PowerShellCorpus/GithubGist/chrisfrancis27_5151297_raw_58e1015b92523f2632328ebbbb72fe2fd65e1484_profile.ps1
chrisfrancis27_5151297_raw_58e1015b92523f2632328ebbbb72fe2fd65e1484_profile.ps1
# '##::::'##::::'###::::'########::'####::::'###::::'########::'##:::::::'########::'######:: # ##:::: ##:::'## ##::: ##.... ##:. ##::::'## ##::: ##.... ##: ##::::::: ##.....::'##... ##: # ##:::: ##::'##:. ##:: ##:::: ##:: ##:::'##:. ##:: ##:::: ##: ##::::::: ##::::::: ##:::..:: # ##:::: ##:'##:::. ##: ########::: ##::'##:::. ##: ########:: ##::::::: ######:::. ######:: # . ##:: ##:: #########: ##.. ##:::: ##:: #########: ##.... ##: ##::::::: ##...:::::..... ##: # :. ## ##::: ##.... ##: ##::. ##::: ##:: ##.... ##: ##:::: ##: ##::::::: ##:::::::'##::: ##: # ::. ###:::: ##:::: ##: ##:::. ##:'####: ##:::: ##: ########:: ########: ########:. ######:: # :::...:::::..:::::..::..:::::..::....::..:::::..::........:::........::........:::......::: $ProjectsDir = "D:\Projects" # :'######::'########::::'###::::'########::'########:'##::::'##:'########:: # '##... ##:... ##..::::'## ##::: ##.... ##:... ##..:: ##:::: ##: ##.... ##: # ##:::..::::: ##:::::'##:. ##:: ##:::: ##:::: ##:::: ##:::: ##: ##:::: ##: # . ######::::: ##::::'##:::. ##: ########::::: ##:::: ##:::: ##: ########:: # :..... ##:::: ##:::: #########: ##.. ##:::::: ##:::: ##:::: ##: ##.....::: # '##::: ##:::: ##:::: ##.... ##: ##::. ##::::: ##:::: ##:::: ##: ##:::::::: # . ######::::: ##:::: ##:::: ##: ##:::. ##:::: ##::::. #######:: ##:::::::: # :......::::::..:::::..:::::..::..:::::..:::::..::::::.......:::..::::::::: Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) # Load posh-git module Import-Module posh-git # Set up a simple prompt, adding the git prompt parts inside git repos function prompt { # Reset color before each prompt to prevent nasties [Console]::ResetColor() $realLASTEXITCODE = $LASTEXITCODE # Reset color, which can be messed up by Enable-GitColors $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor Write-Host($pwd) -nonewline Write-VcsStatus $LASTEXITCODE = $realLASTEXITCODE return "> " } Enable-GitColors Pop-Location Start-SshAgent -Quiet # '########::'########:::'#######:::'######:::'########:::::'###::::'##::::'##::'######:: # ##.... ##: ##.... ##:'##.... ##:'##... ##:: ##.... ##:::'## ##::: ###::'###:'##... ##: # ##:::: ##: ##:::: ##: ##:::: ##: ##:::..::: ##:::: ##::'##:. ##:: ####'####: ##:::..:: # ########:: ########:: ##:::: ##: ##::'####: ########::'##:::. ##: ## ### ##:. ######:: # ##.....::: ##.. ##::: ##:::: ##: ##::: ##:: ##.. ##::: #########: ##. #: ##::..... ##: # ##:::::::: ##::. ##:: ##:::: ##: ##::: ##:: ##::. ##:: ##.... ##: ##:.:: ##:'##::: ##: # ##:::::::: ##:::. ##:. #######::. ######::: ##:::. ##: ##:::: ##: ##:::: ##:. ######:: # ..:::::::::..:::::..:::.......::::......::::..:::::..::..:::::..::..:::::..:::......::: # Alias Notepad++ Set-Alias npp notepad++.exe # Open cwd in sublime text function sub { sublime_text.exe . } # Open cwd in Windows Explorer function e { explorer.exe . } # Add string to path function path($path) { [Environment]::SetEnvironmentVariable('Path', "$env:Path;$path",'Process'); [Environment]::SetEnvironmentVariable('Path', "$env:Path",'Machine'); } # :'######:::'####:'########: # '##... ##::. ##::... ##..:: # ##:::..:::: ##::::: ##:::: # ##::'####:: ##::::: ##:::: # ##::: ##::: ##::::: ##:::: # ##::: ##::: ##::::: ##:::: # . ######:::'####:::: ##:::: # :......::::....:::::..::::: function gs { git status } function gpu { git push } function gpl { git pull } function gco($message) { git add . | Out-Host git commit -am $message | Out-Host } function gr { git reset head --hard } function gclone($user, $repo) { # shortcut to meeee if ($user -eq "cf") { $user = "chrisfrancis27" } git clone [email protected]:$user/$repo.git | Out-Host cd ./$repo } # :'######::'##:::::'##:'########:: # '##... ##: ##:'##: ##: ##.... ##: # ##:::..:: ##: ##: ##: ##:::: ##: # ##::::::: ##: ##: ##: ##:::: ##: # ##::::::: ##: ##: ##: ##:::: ##: # ##::: ##: ##: ##: ##: ##:::: ##: # . ######::. ###. ###:: ########:: # :......::::...::...:::........::: Set-Location $script:ProjectsDir
PowerShellCorpus/GithubGist/rheid_ac43862993666947a008_raw_bfb12b4cba5a26d0edde0a863d43cb0d2ecf4d5a_unpublischoct.ps1
rheid_ac43862993666947a008_raw_bfb12b4cba5a26d0edde0a863d43cb0d2ecf4d5a_unpublischoct.ps1
Add-PSSnapIn Microsoft.SharePoint.PowerShell if ($args.Count -ne 3) { Write-Host "UnpublishContentTypes.ps1 <web url> <content type hub url> <unpublish>" exit } $webUrl = $args[0] $ctUrl = $args[1] $unpublish = $args[2] $web = Get-SPWeb $webUrl $ctsite = Get-SPSite $ctUrl $ctPublisher = New-Object Microsoft.SharePoint.Taxonomy.ContentTypeSync.ContentTypePublisher($ctsite) foreach($ct in $web.ContentTypes) { if ( $ct.XmlDocuments -like "*SharedContentType*") { try { if (-not $ctsite.RootWeb.ContentTypes[$ct.Name]) { Write-Host "Found orphan Shared ContentType $($ct.Name) - ($($ct.ID))" if($unpublish) { $ctPublisher.UnPublish($ct) Write-Host "$($ct.Name) - ($($ct.ID)) UnPublished successfully" } } } catch { Write-Host "Error unpublishing ContentType $($ct.Name) - ($($ct.ID)): $error[0]" } } } if($unpublish) { Start-SPTimerJob MetadataSubscriberTimerJob }
PowerShellCorpus/GithubGist/giseongeom_5432994_raw_bdc56b34e7b5ce66c0067cec007d876d51ebc183_payA.ps1
giseongeom_5432994_raw_bdc56b34e7b5ce66c0067cec007d876d51ebc183_payA.ps1
[CmdletBinding()] Param( [Parameter(Mandatory=$True,Position=1)] [int]$A ) [int]$C1 = 0 [int]$C5 = 0 [int]$C10 = 0 [int]$C50 = 0 [int]$C100 = 0 [int]$C500 = 0 [int]$CAll = 0 [int]$tmp = 0 $C500 = ( $A / 500 ) ; $tmp = ( $A % 500 ) if ( $tmp -ne 0 ) { $C100 = ( $tmp / 100 ) ; $tmp %= 100 } if ( $tmp -ne 0 ) { $C50 = ( $tmp / 50 ) ; $tmp %= 50 } if ( $tmp -ne 0 ) { $C10 = ( $tmp / 10 ) ; $tmp %= 10 } if ( $tmp -ne 0 ) { $C5 = ( $tmp / 5 ) ; $tmp %= 5 } if ( $tmp -ne 0 ) { $C1 = ( $tmp / 1 ) ; $tmp %= 1 } $CAll = $C500 + $C100 + $C50 + $C10 + $C5 + $C1 Write-Output "$`A $A needs $CAll coins 500: $C500 coin(s) 100: $C100 coin(s) 50: $C50 coin(s) 10: $C10 coin(s) 5: $C5 coin(s) 1: $C1 coin(s)"
PowerShellCorpus/GithubGist/onyxhat_2c02749d4891c303506e_raw_8277a3f3f5e8ffd7ed6cc83ae3fcf4466130b295_Mirror-DB.ps1
onyxhat_2c02749d4891c303506e_raw_8277a3f3f5e8ffd7ed6cc83ae3fcf4466130b295_Mirror-DB.ps1
param ([string]$SrcDBInstance, [string]$DestDBInstance, [string]$DBName) #Functions function Exec-Query ([string]$DBServer,[string]$DBName,[string]$Query) { $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=$DBServer;Database=$DBName;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandTimeout = 0 $SqlCmd.CommandText = $Query $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet) | Out-Null $SqlConnection.Close() $DataSet.Tables[0] } function Backup-FullBackup ([string]$DBServer, [string]$DBName, [string]$BakLoc) { if (Test-Path $BakLoc) {Remove-Item $BakLoc -Force | Out-Null} $script = ("BACKUP DATABASE [" + $DBName + "] TO DISK = N'" + $BakLoc + "' WITH NOFORMAT, NOINIT, NAME = N'" + $DBName + "_" + $(Get-Date -UFormat %Y%m%d) + "-Full', SKIP, NOREWIND, NOUNLOAD, STATS = 10") Set-RecoveryModel $DBServer $DBName "FULL" Exec-Query $DBServer "master" $script } function Backup-TranLog ([string]$DBServer, [string]$DBName, [string]$BakLoc) { if (Test-Path $BakLoc) {Remove-Item $BakLoc -Force | Out-Null} $script = ("BACKUP LOG [" + $DBName + "] TO DISK = N'" + $BakLoc + "' WITH NOFORMAT, NOINIT, NAME = N'" + $DBName + "_" + $(Get-Date -UFormat %Y%m%d) + "-Trans', SKIP, NOREWIND, NOUNLOAD, STATS = 10") Exec-Query $DBServer "master" $script } function Restore-FullBackup ([string]$DBServer, [string]$DBName, [string]$BakLoc) { $RestoreTo = Get-DfltLoc $DBServer foreach ($NameSpace in $Global:NameSpace) { switch ($NameSpace.file_type) { "mdf" {[string]$files += (", MOVE N'" + $NameSpace.name + "' TO N'" + ($RestoreTo.DefaultFile + "\" + $DBName) + ".mdf'")} "ndf" {[string]$files += (", MOVE N'" + $NameSpace.name + "' TO N'" + ($RestoreTo.DefaultFile + "\" + $DBName) + ".ndf'")} "ldf" {[string]$files += (", MOVE N'" + $NameSpace.name + "' TO N'" + ($RestoreTo.DefaultLog + "\" + $DBName) + ".ldf'")} } } $script = ("RESTORE DATABASE [" + $DBName + "] FROM DISK = N'" + $BakLoc + "' WITH FILE = 1" + $files +", NORECOVERY, NOUNLOAD, STATS = 10") Exec-Query $DBServer "master" $script } function Restore-TranLog ([string]$DBServer, [string]$DBName, [string]$BakLoc) { $script = ("RESTORE LOG [" + $DBName + "] FROM DISK = N'" + $BakLoc + "' WITH FILE = 1, NORECOVERY, NOUNLOAD, STATS = 10") Exec-Query $DBServer "master" $script } function Get-DfltLoc ([string]$DBServer) { $script = "declare @SmoDefaultFile nvarchar(512) exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @SmoDefaultFile OUTPUT declare @SmoDefaultLog nvarchar(512) exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', @SmoDefaultLog OUTPUT SELECT ISNULL(@SmoDefaultFile,N'') AS [DefaultFile], ISNULL(@SmoDefaultLog,N'') AS [DefaultLog]" Exec-Query $DBServer "master" $script } function Get-FileNamespace ([string]$DBServer, [string]$DBName) { $script = "SELECT LOWER(RIGHT(physical_name, 3)) AS file_type, name FROM SYS.DATABASE_FILES" Exec-Query $DBServer $DBName $script } function Set-RecoveryModel ([string]$DBServer, [string]$DBName, [string]$model) { $script = ("ALTER DATABASE " + $DBName + " SET RECOVERY " + $model) Exec-Query $DBServer "master" $script } function Check-Endpoint ([string]$DBServer) { $script = "SELECT * FROM SYS.DATABASE_MIRRORING_ENDPOINTS WITH (NOLOCK) WHERE NAME = 'HADR_ENDPOINT'" Exec-Query $DBServer "master" $script } function Create-Endpoint ([string]$DBServer) { $script = "CREATE ENDPOINT [HADR_ENDPOINT] STATE = STARTED AS TCP (LISTENER_PORT = 5022, LISTENER_IP = ALL) FOR DATA_MIRRORING (ROLE = ALL, AUTHENTICATION = WINDOWS NEGOTIATE, ENCRYPTION = REQUIRED ALGORITHM AES)" if (!(Check-Endpoint $DBServer)) {Exec-Query $DBServer "master" $script} } function Get-DBSvcUser ([string]$DBName) { $script = "DECLARE @SrvAccount varchar(100) set @SrvAccount ='' EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\Services\MSSQLSERVER', N'ObjectName', @SrvAccount OUTPUT, N'no_output' SELECT @SrvAccount as SQLAgent_ServiceAccount" Exec-Query $DBName "master" $script } function Check-DBUser ([string]$DBName, [string]$UserName) { $script = ("SELECT * FROM sys.server_principals WHERE name = '" + $UserName + "'") Exec-Query $DBName "master" $script } function Create-DBUser ([string]$DBName, [string]$UserName) { $script = ("CREATE LOGIN [" + $UserName + "] FROM WINDOWS") if (!(Check-DBUser $DBName $UserName)) {Exec-Query $DBName "master" $script} } function Grant-EndpointACL ([string]$DBName, [string]$UserName) { $script = ("GRANT CONNECT ON ENDPOINT::HADR_ENDPOINT TO [" + $UserName + "]") Exec-Query $DBName "master" $script } function Get-InstanceFQDN([string]$DBName) { $script = "DECLARE @Domain NVARCHAR(100) EXEC master.dbo.xp_regread 'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\services\Tcpip\Parameters', N'Domain',@Domain OUTPUT SELECT Cast(SERVERPROPERTY('MachineName') as nvarchar) + '.' + @Domain AS FQDN" Exec-Query $DBName "master" $script } function Create-Mirror ([string]$SrcDBInstance, [string]$DestDBInstance, [string]$DBName) { try { Write-Host -NoNewline "Attempting to Create Mirror..." Exec-Query $DestDBInstance "master" ("ALTER DATABASE [" + $DBName + "] SET PARTNER = 'TCP://" + $(Get-InstanceFQDN $SrcDBInstance).FQDN + ":5022'") Exec-Query $SrcDBInstance "master" ("ALTER DATABASE [" + $DBName + "] SET PARTNER = 'TCP://" + $(Get-InstanceFQDN $DestDBInstance).FQDN + ":5022'") Write-Host "DONE!" return $true } catch { Write-Host "FAILED!" return $false } } #Runtime if (!$SrcDBInstance) {$SrcDBInstance = Read-Host "Source Instance"} if (!$DestDBInstance) {$DestDBInstance = Read-host "Destination Instance"} if (!$DBName) {$DBName = Read-Host "Database Name"} $BackupTo = ("\\" + $DestDBInstance + "\Database\Backups\") $Global:NameSpace = Get-FileNamespace $SrcDBInstance $DBName Write-Host -NoNewline "Creating Endpoints..." Create-Endpoint $SrcDBInstance Create-Endpoint $DestDBInstance Write-Host "DONE!" Write-Host -NoNewline "Creating Users and ACLs..." Create-DBUser $SrcDBInstance $(Get-DBSvcUser $DestDBInstance).SQLAgent_ServiceAccount Create-DBUser $DestDBInstance $(Get-DBSvcUser $SrcDBInstance).SQLAgent_ServiceAccount Grant-EndpointACL $SrcDBInstance $(Get-DBSvcUser $DestDBInstance).SQLAgent_ServiceAccount Grant-EndpointACL $DestDBInstance $(Get-DBSvcUser $SrcDBInstance).SQLAgent_ServiceAccount Write-Host "DONE!" Write-Host -NoNewline "Performing Full Backup..." Backup-FullBackup $SrcDBInstance $DBName ($BackupTo + $DBName + ".bak") Restore-FullBackup $DestDBInstance $DBName ($BackupTo + $DBName + ".bak") Write-Host "DONE!" do { Write-Host -NoNewline "Performing Transactional Backup..." Backup-TranLog $SrcDBInstance $DBName ($BackupTo + $DBName + ".trn") Restore-TranLog $DestDBInstance $DBName ($BackupTo + $DBName + ".trn") Write-Host "DONE!" } until (Create-Mirror $SrcDBInstance $DestDBInstance $DBName) Get-ChildItem $BackupTo | Where {$_.Name -like ($DBName + ".*")} | Remove-Item -Force
PowerShellCorpus/GithubGist/grenade_7749144_raw_a7e7fe242cfeacfb4d5d3ac59b149cd086f5759d_wmi-firewall-exceptions.ps1
grenade_7749144_raw_a7e7fe242cfeacfb4d5d3ac59b149cd086f5759d_wmi-firewall-exceptions.ps1
# http://msdn.microsoft.com/en-us/library/jj980508(v=winembedded.81).aspx # http://wiki.splunk.com/Deploy:HOWTO_Enable_WMI_Access_for_Non-Admin_Domain_Users # http://blogs.technet.com/b/ashleymcglone/archive/2011/04/18/powershell-remoting-exposed-how-to-command-your-minions.aspx # disable Remote UAC: reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f # enable the Remote Administration exception: netsh advfirewall set service RemoteAdmin enable # enable WMI traffic at a command prompt by using a WMI rule: netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes # establish a firewall exception for DCOM port 135: netsh advfirewall firewall add rule dir=in name="DCOM" program=%systemroot%\system32\svchost.exe service=rpcss action=allow protocol=TCP localport=135 # establish a firewall exception for the WMI service: netsh advfirewall firewall add rule dir=in name ="WMI" program=%systemroot%\system32\svchost.exe service=winmgmt action = allow protocol=TCP localport=any # establish a firewall exception for the sink that receives callbacks from a remote device: netsh advfirewall firewall add rule dir=in name ="UnsecApp" program=%systemroot%\system32\wbem\unsecapp.exe action=allow # establish a firewall exception for outgoing connections to a remote device that the local computer is communicating with asynchronously: netsh advfirewall firewall add rule dir=out name ="WMI_OUT" program=%systemroot%\system32\svchost.exe service=winmgmt action=allow protocol=TCP localport=any
PowerShellCorpus/GithubGist/johnsocp_6127196_raw_8a05cddbb3df221c410185fd79a36f9f329fb5bc_gistfile1.ps1
johnsocp_6127196_raw_8a05cddbb3df221c410185fd79a36f9f329fb5bc_gistfile1.ps1
Import-Module SPModule.misc Import-Module SPModule.setup Install-SharePoint -SetupExePath "c:\SP210" -ServerRole "SINGLESERVER"
PowerShellCorpus/GithubGist/HarmJ0y_4c37e43ba4865bdef2a8_raw_b916a8a85488ea85a0021b43aa58698e8ad15324_psremoting.ps1
HarmJ0y_4c37e43ba4865bdef2a8_raw_b916a8a85488ea85a0021b43aa58698e8ad15324_psremoting.ps1
#Run winrm quickconfig defaults echo Y | winrm quickconfig #Run enable psremoting command with defaults Enable-PSRemoting -force # adjust local token filter policy Set-ItemProperty –Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System –Name LocalAccountTokenFilterPolicy –Value 1 -Type DWord #Enabled Trusted Hosts for Universial Access Set-Item WSMan:\localhost\Client\TrustedHosts –Value * -Force restart-Service winrm echo "Complete"
PowerShellCorpus/GithubGist/nims_4263820_raw_031b81ae6cdd2c1b1b9cf571fa1a5983f0e6ddd5_readSite.ps1
nims_4263820_raw_031b81ae6cdd2c1b1b9cf571fa1a5983f0e6ddd5_readSite.ps1
$result = (new-object System.IO.StreamReader ([System.Net.WebRequest]::Create("URL_of_Site").GetResponse().GetResponseStream())).ReadToEnd()
PowerShellCorpus/GithubGist/trondhindenes_087a706421ffa6c945d5_raw_87100221b82008818bee2b03f5d63f6d3c55e774_win_restart.ps1
trondhindenes_087a706421ffa6c945d5_raw_87100221b82008818bee2b03f5d63f6d3c55e774_win_restart.ps1
#!powershell # This file is part of Ansible. # # Copyright 2014, Trond Hindenes <[email protected]> and others # # 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; If ($params.force) { $force = $params.force | ConvertTo-Bool } $result = New-Object psobject @{ changed = $true } if (Get-ScheduledJob -Name "Ansible: Restart computer") { Unregister-ScheduledJob -Name "Ansible: Restart computer" -Force } $immediate = (get-date).AddSeconds(5) $trigger = New-JobTrigger -Once -At $immediate $sjo = New-ScheduledJobOption -RunElevated Register-ScheduledJob -Name "Ansible: Restart computer" -ScriptBlock {Restart-Computer -Force} -Trigger $trigger -ScheduledJobOption $sjo Exit-Json $result;
PowerShellCorpus/GithubGist/PaulStovell_9c4c72602ebe1b76942e_raw_3730914d329958a9163eab41a6fd53bd4ee569ac_gistfile1.ps1
PaulStovell_9c4c72602ebe1b76942e_raw_3730914d329958a9163eab41a6fd53bd4ee569ac_gistfile1.ps1
# Create arguments as an array $args = @("create-release", "--project", "My Project") # Dynamically add arguments $environments = @("My Environment", "Production") foreach ($environment in $environments) { $args += "--environment" $args += $environment.Trim() } & .\Octo.exe ($args)
PowerShellCorpus/GithubGist/sjwaight_f81771e365877ee1dc39_raw_3e9c0cefa9b3ea4c782544ecf49dbcfc479206e1_04-Setup-TrafficManager.ps1
sjwaight_f81771e365877ee1dc39_raw_3e9c0cefa9b3ea4c782544ecf49dbcfc479206e1_04-Setup-TrafficManager.ps1
# You can download this file as part of this repository: https://github.com/sjwaight/uha-azure-sample/ if($args.Count -eq 0) { Write-Host "ERROR: you must supply a unique traffic manager DNS prefix" Exit 1 } $tmDomain = "{0}.trafficmanager.net" -f $args[0] $trafficManProfile = New-AzureTrafficManagerProfile -Name "MusicStoreFoProfile" -DomainName $tmDomain -LoadBalancingMethod Failover -Ttl 300 -MonitorProtocol Http -MonitorPort 80 -MonitorRelativePath "/" # these hostnames will need to be updated to match your actual ones. $trafficManProfile = Add-AzureTrafficManagerEndpoint -TrafficManagerProfile $trafficManProfile -DomainName "dmmswaustraliaeast.cloudapp.net" -Status Enabled -Type CloudService $trafficManProfile = Add-AzureTrafficManagerEndpoint -TrafficManagerProfile $trafficManProfile -DomainName "dmmswaustraliasoutheast.cloudapp.net" -Status Enabled -Type CloudService Set-AzureTrafficManagerProfile –TrafficManagerProfile $trafficManProfile
PowerShellCorpus/GithubGist/mdumrauf_7593409_raw_db02ddb3a391ef51748c53ab9631c640e2ca16cb_db_multiverse_downloader.ps1
mdumrauf_7593409_raw_db02ddb3a391ef51748c53ab9631c640e2ca16cb_db_multiverse_downloader.ps1
echo "Downlading.." $file = "" $client = new-object System.Net.WebClient for($i = 1; $i -le 797; $i++) { if ($i -lt 10) { $file = "000$($i)" } elseif (($i / 10) -lt 10) { $file = "00$($i)" } elseif (($i / 100) -lt 100) { $file = "0$($i)" } Try { $client.DownloadFile("http://www.dragonball-multiverse.com/es/pages/final/$($file).jpg", "C:\Users\mdumrauf\Desktop\dbz-multiverse\$($file).jpg") echo "INFO :: File $($file) download completed" } Catch { [System.Net.WebException] echo "WARN :: File $($file) is not a jpg! Downloading png instead.." Try { $client.DownloadFile("http://www.dragonball-multiverse.com/es/pages/final/$($file).png", "C:\Users\mdumrauf\Desktop\dbz-multiverse\$($file).png") echo "INFO :: File $($file) download completed" } Catch { [System.Net.WebException] echo "ERROR :: File $($file) is not a valid image! Ignoring." } } }
PowerShellCorpus/GithubGist/tiernano_3798509_raw_12eaefa066f55af1b8c750ef516dc79b88ab4f63_convert-to-AppleTV.ps1
tiernano_3798509_raw_12eaefa066f55af1b8c750ef516dc79b88ab4f63_convert-to-AppleTV.ps1
$files = gci "path to your file location" $handbrake = "C:\Program Files\HandBrake\HandBrakeCLI.exe" foreach($file in $files) { $newFileName = "path to where you want the files to be set to..." + [System.IO.Path]::GetFileNameWithoutExtension($file) + ".m4v" & $handbrake -i $file.FullName -o $newFileName --preset "AppleTV 2" if ($LastExitCode -ne 0) { Write-Warning "Error converting $($file.FullName)" } }
PowerShellCorpus/GithubGist/RhysC_840623_raw_84a07b78be89af7e1d485fce30b521d8d51d7ae5_cleanSvn.ps1
RhysC_840623_raw_84a07b78be89af7e1d485fce30b521d8d51d7ae5_cleanSvn.ps1
function cleanSvn { param ([string]$path) write-host "Cleaning svn from: $path" get-childitem $path -include .svn -recurse -force | remove-item -force -confirm:$false -recurse }
PowerShellCorpus/GithubGist/Touichirou_a8fe9b9bec77892c13de_raw_3b5562b1e5da3e1eab14252a23df06c78b2f8f7b_change-windows-password-policy.ps1
Touichirou_a8fe9b9bec77892c13de_raw_3b5562b1e5da3e1eab14252a23df06c78b2f8f7b_change-windows-password-policy.ps1
# Export LocalSecurityPolicy.cfg & SecEdit.exe /export /cfg .\LocalSecurityPolicy.cfg Get-Item -Path ".\LocalSecurityPolicy.cfg" & notepad.exe .\LocalSecurityPolicy.cfg # Import LocalSecurityPolicy.cfg after changing & SecEdit.exe /configure /db .\LocalSecurityPolicy.db /cfg .\LocalSecurityPolicy.cfg Get-Item -Path ".\LocalSecurityPolicy.db"
PowerShellCorpus/GithubGist/Kruzen_9143261_raw_f7b10a12e363971a94c35f203d01d66f61801f76_Generate-GUID.ps1
Kruzen_9143261_raw_f7b10a12e363971a94c35f203d01d66f61801f76_Generate-GUID.ps1
$Members = @("PC1","PC2","PC3","PC4","PC5") $CostCenter = "50" Function GenerateID($Members,$CostCenter){ $IDPool = (20..(20+$Members.count - 1) | %{$_.ToString("$($CostCenter)0000")}) foreach($member in $Members){ $Object = New-Object PSObject -Property @{ PCID = $Members[(0..($Members.Count - 1) | Where { $Members[$_] -eq "$member" })] UID = $IDPool[(0..($Members.Count - 1) | Where { $Members[$_] -eq "$member" })] } Write-Output $Object } } GenerateID($Members, $CostCenter) # This Works when removed from the Function $IDPool = (20..(20+$Members.count - 1) | %{$_.ToString("$($CostCenter)0000")}) foreach($member in $Members){ $Object = New-Object PSObject -Property @{ PCID = $Members[(0..($Members.Count - 1) | Where { $Members[$_] -eq "$member" })] UID = $IDPool[(0..($Members.Count - 1) | Where { $Members[$_] -eq "$member" })] } #Write-Output $Object }
PowerShellCorpus/GithubGist/venetianthief_7d9af24d76810f301b7a_raw_d99c14878535bdc8d07109cc24ff330ebbab1cff_mongodb-install.ps1
venetianthief_7d9af24d76810f301b7a_raw_d99c14878535bdc8d07109cc24ff330ebbab1cff_mongodb-install.ps1
# Borrowed from: http://blogs.msdn.com/b/jasonn/archive/2013/06/11/8594493.aspx function downloadFile($url, $targetFile) { $uri = New-Object "System.Uri" "$url" $request = [System.Net.HttpWebRequest]::Create($uri) $request.set_Timeout(15000) #15 second timeout $response = $request.GetResponse() $totalLength = [System.Math]::Floor($response.get_ContentLength()/1024) $responseStream = $response.GetResponseStream() $targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $targetFile, Create $buffer = new-object byte[] 10KB $count = $responseStream.Read($buffer,0,$buffer.length) $downloadedBytes = $count while ($count -gt 0) { $targetStream.Write($buffer, 0, $count) $count = $responseStream.Read($buffer,0,$buffer.length) $downloadedBytes = $downloadedBytes + $count Write-Progress -activity "Downloading file '$($url.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength) * 100) } Write-Progress -activity "Finished downloading file '$($url.split('/') | Select -Last 1)'" $targetStream.Flush() $targetStream.Close() $targetStream.Dispose() $responseStream.Dispose() } # Welcome message & clear Write-Host "`n`n`n`n`n`n`n`n`n`n" Write-Host "`n=============================================" -foregroundcolor white Write-Host " Mongo" -foregroundcolor green -nonewline Write-Host "DB" -foregroundcolor white -nonewline Write-Host " Powershell Install Script" -foregroundcolor yellow -nonewline Write-Host " ver " -foregroundcolor red -nonewline Write-Host "2.6.7" -foregroundcolor white Write-Host "=============================================`n" -foregroundcolor white #Check to see if running as Admin if (!(new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)){ Write-Host "`nERROR! " -foregroundcolor red -nonewline Write-Host "Please run this script with " -foregroundcolor white -nonewline Write-Host "Elevated/Admin" -foregroundcolor yellow -nonewline Write-Host " access.`n" -foregroundcolor white exit } Set-ExecutionPolicy RemoteSigned $mongoDbPath = $env:SystemDrive + "\tools\mongodb" $mongoDbConfigPath = "$mongoDbPath\mongod.cfg" $mongoDbConfigPathLog = "$mongoDbPath\log" $mongoDbConfigPathData = "$mongoDbPath\data" $mongoDbSysPath = ";$mongoDbPath\bin" $url = "https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-2.6.7.zip" $zipFile = "$mongoDbPath\mongo.zip" $unzippedFolderContent ="$mongoDbPath\mongodb-win32-x86_64-2008plus-2.6.7" # Check if MongoDB bin directory exists if ((Test-Path -path $mongoDbPath\bin\mongod.exe) -eq $True){ Write-Host "`nERROR! " -foregroundcolor red -nonewline Write-Host "MongoDB is already installed at: " -foregroundcolor white -nonewline Write-Host "$mongoDbPath`n" -foregroundcolor yellow exit } Write-Host "`nCreating MongoDB Directory Structure... `n" -foregroundcolor white Write-Host "Creating " -foregroundcolor yellow -nonewline Write-Host $mongoDbPath -foregroundcolor white -nonewline md $mongoDbPath -force | out-null Write-Host " ...Finished!" -foregroundcolor green Write-Host "Creating " -foregroundcolor yellow -nonewline Write-Host $mongoDbConfigPathLog -foregroundcolor white -nonewline md "$mongoDbConfigPathLog" -force | out-null Write-Host " ...Finished!" -foregroundcolor green Write-Host "Creating " -foregroundcolor yellow -nonewline Write-Host $mongoDbConfigPathData -foregroundcolor white -nonewline md "$mongoDbConfigPathData" -force | out-null Write-Host " ...Finished!" -foregroundcolor green Write-Host "Creating " -foregroundcolor yellow -nonewline Write-Host $mongoDbConfigPathData\db -foregroundcolor white -nonewline md "$mongoDbConfigPathData\db" -force | out-null Write-Host " ...Finished!`n" -foregroundcolor green # Generate YAML formatted configuration file Write-Host "`nGenerating MongoDB Configuration File...`n" -foregroundcolor white # Check if configuration file already exists if ((Test-Path -path $mongoDbConfigPath) -eq $True){ Write-Host "`nERROR! " -foregroundcolor red -nonewline Write-Host "MongoDB configuration file already exists: " -foregroundcolor white -nonewline Write-Host "$mongoDbConfigPath`n" -foregroundcolor yellow -nonewline Write-Host " Removing..." -foregroundcolor white -nonewline Remove-Item $mongoDbConfigPath -force Write-Host "Done!`n" -foregroundcolor green } [System.IO.File]::AppendAllText("$mongoDbConfigPath", "systemLog:`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " destination: file`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " path: `"C:`\`\tools`\`\mongodb`\`\log`\`\mongo.log`"`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " logAppend: true`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", "storage:`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " dbPath: `"C:`\`\tools`\`\mongodb`\`\data`\`\db`"`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " smallFiles: true`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " preallocDataFiles: false`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " journal:`r`n") [System.IO.File]::AppendAllText("$mongoDbConfigPath", " enabled: true`r`n") # Show User the Configuration File Contents Get-Content $mongoDbConfigPath Write-Host "`nDownloading: " -foregroundcolor white -nonewline Write-Host $url -foregroundcolor yellow downloadFile $url $zipfile Write-Host "`nExtracting MongoDB Files..." -foregroundcolor white -nonewline $shellApp = New-Object -com shell.application Write-Host "Finished!" -foregroundcolor green $destination = $shellApp.namespace($mongoDbPath) Write-Host "Copying MongoDB Files..." -foregroundcolor white -nonewline $destination.Copyhere($shellApp.namespace($zipFile).items()) Copy-Item "$unzippedFolderContent\*" $mongoDbPath -recurse Write-Host "Finished!" -foregroundcolor green Write-Host "Removing Temporary Files..." -foregroundcolor white -nonewline Remove-Item $unzippedFolderContent -recurse -force Remove-Item $zipFile -recurse -force Write-Host "Finished!" -foregroundcolor green Write-Host "`nAdding MongoDB to System Path...`n" -foregroundcolor white # See if the new Folder is already in the path. if ($env:Path | Select-String -SimpleMatch $mongoDbSysPath){ Write-Host $env:Path -foregroundcolor white -nonewline Write-Host "$mongoDbSysPath`n" -foregroundcolor yellow $env:Path = "$($env:Path);$mongoDbPath\bin" [Environment]::SetEnvironmentVariable("Path",$env:Path,"Machine") } else { Write-Host $mongoDbSysPath -foregroundcolor yellow -nonewline Write-Host " is already in System Path." -foregroundcolor white } Write-Host "`nStarting MongoDB as a Service...`n" -foregroundcolor white # The --install command makes MongoDB run as a daemon & $mongoDbPath\bin\mongod.exe --config $mongoDbConfigPath --install # Start MongoDB Service it not running $arrService = Get-Service -Name MongoDB if ($arrService.Status -ne "Running"){ Start-Service MongoDB Write-Host "Starting MongoDB service" -foregroundcolor white }
PowerShellCorpus/GithubGist/richjenks_6548962_raw_e5fab68aba6b4e0451945dd4fb5d70d27e4fc27e_full-path-file-type.ps1
richjenks_6548962_raw_e5fab68aba6b4e0451945dd4fb5d70d27e4fc27e_full-path-file-type.ps1
gci -r | where {$_.extension -match ".html|.htm|.php|.asp"} | select FullName
PowerShellCorpus/GithubGist/nopslider_0b32b15d59cd5a9b56a2_raw_081002f67f89d2acbcf0ca15a30f4a82bc3c9dec_gistfile1.ps1
nopslider_0b32b15d59cd5a9b56a2_raw_081002f67f89d2acbcf0ca15a30f4a82bc3c9dec_gistfile1.ps1
Get-ADUser -Filter * -properties * | Export-csv domain.csv
PowerShellCorpus/GithubGist/guitarrapc_cfff0c9fc907e95dd6d8_raw_3b57e0ce024171d90891d351be5f575e40ff6ac5_bashStyle.ps1
guitarrapc_cfff0c9fc907e95dd6d8_raw_3b57e0ce024171d90891d351be5f575e40ff6ac5_bashStyle.ps1
#2. ${} でくくる。これもプロパティ指定がだめ (in-line評価 => bash スタイル) "${hoge}" "${fuga}"
PowerShellCorpus/GithubGist/CapsAdmin_c33b41c6642e4338bb7a_raw_a88ea870f51a3436c67f48c0130d0b421a130474_gistfile1.ps1
CapsAdmin_c33b41c6642e4338bb7a_raw_a88ea870f51a3436c67f48c0130d0b421a130474_gistfile1.ps1
#download zip file and extract specific directory with powershell $url = "https://github.com/CapsAdmin/rpg_hitmarks/archive/master.zip" $folder_in_zip = "rpg_hitmarks-master\lua" $output_folder = $PSScriptRoot + "\windows_lol" function download() { if(!(Test-Path $output_folder)) {New-Item -ItemType directory -Path $output_folder} Write-Output $output_folder $download_location = (get-item $output_folder).parent.FullName + "\temp.zip" Remove-Item $download_location -ErrorAction SilentlyContinue -Confirm:$false -Recurse:$true Invoke-WebRequest $url -OutFile $download_location $shell = new-object -com shell.application $zip = $shell.NameSpace($download_location) foreach($item in $zip.items()) { $shell.Namespace($output_folder).copyhere($item) } Move-Item ($output_folder + "\" + $folder_in_zip + "\*") $output_folder -ErrorAction SilentlyContinue -Confirm:$false Remove-Item ($download_location) -ErrorAction SilentlyContinue -Confirm:$false -Recurse:$true Remove-Item ($output_folder + "\" + ($folder_in_zip -split '\\')[0]) -ErrorAction SilentlyContinue -Confirm:$false -Recurse:$true } download
PowerShellCorpus/GithubGist/andrerocker_655819_raw_b13a888bc8cdf142eba5c15f8b11a6cc9a33d971_sqlserver-dump-only-data.ps1
andrerocker_655819_raw_b13a888bc8cdf142eba5c15f8b11a6cc9a33d971_sqlserver-dump-only-data.ps1
$database_host = "<host>" $database_name = "<database>" $output_file = "<output_file>" $user = "<username>" $password = "<password>" [system.reflection.assembly]::loadWithPartialName('Microsoft.SqlServer.SMO') $server = new-object "Microsoft.SqlServer.Management.Smo.Server" $database_host $server.connectionContext.loginSecure = $false $server.connectionContext.set_Login($user) $server.connectionContext.set_Password($password) $database = $server.databases[$database_name] $scripter = new-object "Microsoft.SqlServer.Management.Smo.Scripter" $server $scripter.options.fileName = $output_file $scripter.options.scriptSchema = $false $scripter.options.scriptData = $true $scripter.options.toFileOnly = $true foreach ($s in $scripter.enumScript($database.tables)) { write-host $s }
PowerShellCorpus/GithubGist/glombard_516c83ef97a7ad354db1_raw_e38d9d3ae10056eb8fb908e32f09731ae9678f00_set-npm-vs-version.ps1
glombard_516c83ef97a7ad354db1_raw_e38d9d3ae10056eb8fb908e32f09731ae9678f00_set-npm-vs-version.ps1
# See: https://www.npmjs.org/package/node-gyp $vsVersion = "2012" if (Test-Path HKLM:\Software\Microsoft\VisualStudio\12.0) { $vsVersion = "2013" } npm.cmd config set msvs_version $vsVersion
PowerShellCorpus/GithubGist/jonschoning_5447741_raw_1e34b3fd80bbfa30231822d07009f4d2666ef52f_remote-exec-iis.ps1
jonschoning_5447741_raw_1e34b3fd80bbfa30231822d07009f4d2666ef52f_remote-exec-iis.ps1
$Session = New-PSSession -ComputerName '<ComputerName>' $block = { import-module 'webAdministration' # Call IIS cmdlets here for adding app pools, creating web site and so on } Invoke-Command -Session $Session -ScriptBlock $block
PowerShellCorpus/GithubGist/bgallagh3r_3535856_raw_1f09b634e99e7ddb67069abee6297630cc666e93_profile.ps1
bgallagh3r_3535856_raw_1f09b634e99e7ddb67069abee6297630cc666e93_profile.ps1
# My preferred prompt for Powershell. # Displays git branch and stats when inside a git repository. # See http://gist.github.com/180853 for gitutils.ps1. . (Resolve-Path ~/Documents/WindowsPowershell/gitutils.ps1) function prompt { $path = "" $pathbits = ([string]$pwd).split("\", [System.StringSplitOptions]::RemoveEmptyEntries) if($pathbits.length -eq 1) { $path = $pathbits[0] + "\" } else { $path = $pathbits[$pathbits.length - 1] } $userLocation = $env:username + '@' + [System.Environment]::MachineName + ' ' + $path $host.UI.RawUi.WindowTitle = $userLocation Write-Host($userLocation) -nonewline -foregroundcolor Green if (isCurrentDirectoryGitRepository) { $status = gitStatus $currentBranch = $status["branch"] Write-Host(' [') -nonewline -foregroundcolor Yellow if ($status["ahead"] -eq $FALSE) { # We are not ahead of origin Write-Host($currentBranch) -nonewline -foregroundcolor Cyan } else { # We are ahead of origin Write-Host($currentBranch) -nonewline -foregroundcolor Red } Write-Host(' +' + $status["added"]) -nonewline -foregroundcolor Yellow Write-Host(' ~' + $status["modified"]) -nonewline -foregroundcolor Yellow Write-Host(' -' + $status["deleted"]) -nonewline -foregroundcolor Yellow if ($status["untracked"] -ne $FALSE) { Write-Host(' !') -nonewline -foregroundcolor Yellow } Write-Host(']') -nonewline -foregroundcolor Yellow } Write-Host('>') -nonewline -foregroundcolor Green return " " }
PowerShellCorpus/GithubGist/jlattimer_cb2f0d7e80d06ba73f10_raw_dd6dbcea355ec194d9c229a74a9ce098222fc416_Create%20CRM%20VM%20Static%20IP%20New.ps1
jlattimer_cb2f0d7e80d06ba73f10_raw_dd6dbcea355ec194d9c229a74a9ce098222fc416_Create%20CRM%20VM%20Static%20IP%20New.ps1
<# Make sure you have installed the Azure PowerShell cmdlets: https://www.windowsazure.com/en-us/manage/downloads/ and then reboot #> <# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! The steps need to be run individually !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #> <# Step 1: Run this first to download your publisher file from Azure #> Get-AzurePublishSettingsFile <# Step 2: Change the path to the file you downloaded: C:\xxx\xxx.publishsettings #> $publisherFileLocation = "C:\xxx\xxx.publishsettings" Import-AzurePublishSettingsFile $publisherFileLocation <# Step 3: Input the 'Name' of the subscription from the output of the previous step #> $subscriptionName = "Visual Studio Ultimate with MSDN" Select-AzureSubscription -SubscriptionName $subscriptionName <# Step 4: Run this to output the list of Azure storage accounts associated with your account #> Get-AzureStorageAccount <# Step 5: Input the subscription 'Name' again and the 'StorageAccountName' from the output of the previous step when the VM gets created it will use that Azure Storage account #> $sortageAccountName = "portalxxxxxxxxxxxxxxxxx" Set-AzureSubscription -SubscriptionName $subscriptionName -CurrentStorageAccount $sortageAccountName <# Step 6: Create a reserved/static IP for your VM - input the name/label and the region your VM will be in #> $reservedIPName = "CRMIP" $reservedIPLabel = "CRMIP" $location = “North Central US” New-AzureReservedIP –ReservedIPName $reservedIPName –Label $reservedIPLabel –Location $location <# Use this to remove the reserved IP if you end up not needing it #> <# Remove-AzureReservedIP -ReservedIPName "CRMIP" -Force# > <# Show the list of reserved IP addresses if you are interested #> <# Get-AzureReservedIP #> <# Step 7: Run this to output the list of Azure VM images to base the server on, Windows Server 2012 R2 for example #> $images = Get-AzureVMImage $images | where {$_.Label -like 'windows server 2012 r2*'} | select Label, RecommendedVMSize, PublishedDate | Format-Table -AutoSize <# Step 8: Input the the 'Label' and 'Publish Date' of the specific image you want to start with #> $vmImage = Get-AzureVMImage ` | Where-Object -Property ImageFamily -ilike "Windows Server 2012 R2*" ` | Sort-Object -Descending -Property PublishedDate ` | Select-Object -First(1) Write-Output $imageName <# Step 9: Input the VM & cloud service names, VM size, and admin username & password and create the VM #> $vmName = "CRM2015" $cloudServiceName = "CRM2015" $instanceSize = "ExtraLarge" $adminUsername = "crmadmin" $adminPassword = "Str0ngP@ssw0rd?" New-AzureVMConfig -Name $vmName -InstanceSize $instanceSize -ImageName $vmImage.ImageName | Add-AzureProvisioningConfig -Windows -AdminUsername $adminUsername -Password $adminPassword | Add-AzureEndpoint -Name "HTTP" -Protocol "tcp" -PublicPort 80 -LocalPort 80 | Add-AzureEndpoint -Name "HTTPS" -Protocol "tcp" -PublicPort 443 -LocalPort 443 | Add-AzureEndpoint -Name "HTTPS2" -Protocol "tcp" -PublicPort 444 -LocalPort 444 | <# Only if you need ADFS on the same server #> Add-AzureEndpoint -Name "Remote Desktop" -Protocol "tcp" -PublicPort 60523 -LocalPort 3389 | New-AzureVM -ServiceName $cloudServiceName -ReservedIPName $reservedIPName -Location $location
PowerShellCorpus/GithubGist/gettuget_5246078_raw_a7291d9efff3edf4ebe3881200b1fb3da2e2586b_gistfile1.ps1
gettuget_5246078_raw_a7291d9efff3edf4ebe3881200b1fb3da2e2586b_gistfile1.ps1
([regex]"(?s)log[^;{]*").matches((Get-ChildItem -recurse | where { ( $_.directoryName -match '.+[/\\]main[/\\]java.*') -and ($_.directoryName -notmatch '.+[/\\]internal.*') -and ($_ -match '.*\.java')} | Get-Content -encoding "UTF8" | out-string)) | foreach { if (($_.value.tolower().indexof("warn") -gt -1 -or $_.value.tolower().indexOf("error") -gt -1) -and $_.value.indexof('"') -gt -1 ) { ($_.value.replace("`r`n", "") -replace "\s+", " ") } } | foreach { $_ -replace "(^[^\.]+\.)(warn|error)", "`$2`t" } | out-file -encoding "UTF8" log-messages.txt
PowerShellCorpus/GithubGist/ricjac_11244068_raw_7c09205725cd12d854463a076afc69cbb37ba3e0_ADDisplayMultipleUserEmailAddr.ps1
ricjac_11244068_raw_7c09205725cd12d854463a076afc69cbb37ba3e0_ADDisplayMultipleUserEmailAddr.ps1
Import-Module activedirectory $users2Find = @("USERNAME1","USERNAME2") foreach ($user in $users2Find) { $tempuser = Get-ADUser $user -Properties mail Write-Host $tempuser.mail }
PowerShellCorpus/GithubGist/DominicCronin_9088961_raw_235c7faf6b02041b9aea7429676e312ae242b328_gistfile1.ps1
DominicCronin_9088961_raw_235c7faf6b02041b9aea7429676e312ae242b328_gistfile1.ps1
function get-ImportExportServiceClient { param( [parameter(Mandatory=$false)] [AllowNull()] [ValidateSet("Service","Upload","Download")] [string]$type="Service" ) InitImportExport $binding = new-object System.ServiceModel.BasicHttpBinding $binding.MaxBufferPoolSize = [int]::MaxValue $binding.MaxReceivedMessageSize = [int]::MaxValue $binding.ReaderQuotas.MaxArrayLength = [int]::MaxValue $binding.ReaderQuotas.MaxBytesPerRead = [int]::MaxValue $binding.ReaderQuotas.MaxStringContentLength = [int]::MaxValue $binding.ReaderQuotas.MaxNameTableCharCount = [int]::MaxValue switch($type) { "Service" { $binding.Security.Mode = [System.ServiceModel.BasicHttpSecurityMode]::TransportCredentialOnly $binding.Security.Transport.ClientCredentialType = [System.ServiceModel.HttpClientCredentialType]::Windows $endpoint = new-object System.ServiceModel.EndpointAddress http://localhost/webservices/ImportExportService2013.svc/basicHttp new-object Tridion.ContentManager.ImportExport.Client.ImportExportServiceClient $binding,$endpoint } "Download" { $binding.Security.Mode = [System.ServiceModel.BasicHttpSecurityMode]::TransportCredentialOnly $binding.Security.Transport.ClientCredentialType = [System.ServiceModel.HttpClientCredentialType]::Windows $binding.TransferMode = [ServiceModel.TransferMode]::StreamedResponse $binding.MessageEncoding = [ServiceModel.WsMessageEncoding]::Mtom $endpoint = new-object System.ServiceModel.EndpointAddress http://localhost/webservices/ImportExportService2013.svc/streamDownload_basicHttp new-object Tridion.ContentManager.ImportExport.Client.ImportExportStreamDownloadClient $binding,$endpoint } "Upload" { $binding.Security.Mode = [System.ServiceModel.BasicHttpSecurityMode]::None $binding.TransferMode = [ServiceModel.TransferMode]::StreamedRequest $binding.MessageEncoding = [ServiceModel.WsMessageEncoding]::Mtom $endpoint = new-object System.ServiceModel.EndpointAddress http://localhost/webservices/ImportExportService2013.svc/streamUpload_basicHttp new-object Tridion.ContentManager.ImportExport.Client.ImportExportStreamUploadClient $binding,$endpoint } } }
PowerShellCorpus/GithubGist/altrive_7618509_raw_db8016a7818d05c1284a0edb075f3117646d89f9_XmlElementRemoting.ps1
altrive_7618509_raw_db8016a7818d05c1284a0edb075f3117646d89f9_XmlElementRemoting.ps1
$xmlDocument = [xml] "<root><elem>abcd</elem></root>" $xmlElement = $xmlDocument.root Invoke-Command localhost -ScriptBlock { $arg = $using:xmlDocument Write-Host ("Type={0}, Value={1}" -f $arg.GetType(), $arg.OuterXml) } Invoke-Command localhost -ScriptBlock { $arg = $using:xmlElement Write-Host ("Type={0}, Value={1}" -f $arg.GetType(), $arg) #XmlElement is not supported by PSRemiting }
PowerShellCorpus/GithubGist/jrwarwick_6216347_raw_a01f967ba270c26b57adbcccefd72d570fb1bdc3_gistfile1.ps1
jrwarwick_6216347_raw_a01f967ba270c26b57adbcccefd72d570fb1bdc3_gistfile1.ps1
$accumulatedList ='' foreach ($ws in dsquery computer -limit 1000 -name "*COMMON-NAME-FRAGMENT*" | dsget computer -samid | %{$_ -replace "\$",""}) { $candidatehost = $ws.trim() ping -n 2 $candidatehost if ($LASTEXITCODE -eq 0) { echo "##==-- TARGET UNIT ACTIVE! --------- $candidatehost --==##`a" ## this line only works on TServers ## query session /server:$candidatehost try { $userProc = gwmi win32_process -computer $candidatehost -filter "Name = 'explorer.exe'" -ErrorAction "Stop" } catch { echo "error.minor: unable to query executing processes for evidence of user login session." $userProc = '' $userLoggedin = '' $userDetail = '' } if ($userProc) { $userLoggedin = $userProc.GetOwner().User if ($LASTEXITCODE -eq 0) { echo "`t$userLoggedin currently logged in." $userDetail = (dsquery user -samid $userLoggedin | dsget user -display -tel -mobile)[1] } else { $userLoggedin = ' no user login detected.' $userDetail = '' } } $accumulatedList = $accumulatedList + "$candidatehost `t`t$userLoggedin`t$userDetail`n" } } Write-Host "Units up, in summary:`n $accumulatedList"
PowerShellCorpus/GithubGist/rodolfofadino_3030382_raw_95d359702ddb2d8ad6e0b4245b6dbd7abe58a53d_gistfile1.ps1
rodolfofadino_3030382_raw_95d359702ddb2d8ad6e0b4245b6dbd7abe58a53d_gistfile1.ps1
Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\AWSSDK.dll" $instancias = New-Object System.Collections.Generic.List[System.Collections.Hashtable] $instancias.Add(@{"maquina" = "i-xxxxx"; "ip" = ""; endpoint= "https://ec2.sa-east-1.amazonaws.com/"}) ##$instancias.Add(@{"maquina" = "i-xxxxx"; "ip" = "111.111.1.11"; endpoint= "https://ec2.sa-east-1.amazonaws.com/"}) ##$instancias.Add(@{"maquina" = "i-xxxxx"; "ip" = "111.111.1.11"; endpoint= "https://ec2.sa-east-1.amazonaws.com/"}) ##$instancias.Add(@{"maquina" = "i-xxxxx"; "ip" = "111.111.1.11"; endpoint= "https://ec2.sa-east-1.amazonaws.com/"}) $secretKeyID="Secret key" $secretAccessKeyID="Access key" ##Urls de endpoint ##US East (Northern Virginia) Region ec2.us-east-1.amazonaws.com HTTP and HTTPS ##US West (Oregon) Region ec2.us-west-2.amazonaws.com HTTP and HTTPS ##US West (Northern California) Region ec2.us-west-1.amazonaws.com HTTP and HTTPS ##EU (Ireland) Region ec2.eu-west-1.amazonaws.com HTTP and HTTPS ##Asia Pacific (Singapore) Region ec2.ap-southeast-1.amazonaws.com HTTP and HTTPS ##Asia Pacific (Tokyo) Region ec2.ap-northeast-1.amazonaws.com HTTP and HTTPS ##South America (Sao Paulo) Region ec2.sa-east-1.amazonaws.com HTTP and HTTPS foreach ($item in $instancias) { $config = New-Object Amazon.EC2.AmazonEC2Config $config.WithServiceURL($item.endpoint) $client = [Amazon.AWSClientFactory]::CreateAmazonEC2Client($secretAccessKeyID,$secretKeyID,$config) $request = New-Object Amazon.EC2.Model.StopInstancesRequest $request.WithInstanceId($item.maquina) $client.StopInstances($request) }
PowerShellCorpus/GithubGist/matiasherranz-santex_9785930_raw_8facee25158b8ffb9d435a62dbe1d66856553183_gistfile1.ps1
matiasherranz-santex_9785930_raw_8facee25158b8ffb9d435a62dbe1d66856553183_gistfile1.ps1
chmod a+x ~/.git-templates/hooks/post-commit
PowerShellCorpus/GithubGist/seankearon_04d4f152f81f0e5f2146_raw_7aa9ea5f045db452214e1e97e7268177a54c036e_get-script-folder.ps1
seankearon_04d4f152f81f0e5f2146_raw_7aa9ea5f045db452214e1e97e7268177a54c036e_get-script-folder.ps1
# Get the script's folder function get_script_directory # http://blogs.msdn.com/b/powershell/archive/2007/06/19/get-scriptdirectory.aspx { $Invocation = (Get-Variable MyInvocation -Scope 1).Value Split-Path $Invocation.MyCommand.Path } $scriptpath = get_script_directory cd $scriptpath # Pause for user to press a key Write-Host "Press any key to continue ..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
PowerShellCorpus/GithubGist/stevenharman_1718397_raw_f58f1e957745dd4e6766fc63fe607c8163e8760a_jenkins-service-with-interactive.ps1
stevenharman_1718397_raw_f58f1e957745dd4e6766fc63fe607c8163e8760a_jenkins-service-with-interactive.ps1
# stolen from: # http://lostechies.com/keithdahlby/2011/08/13/allowing-a-windows-service-to-interact-with-desktop-without-localsystem/ # # NOTE: Be sure to run as Admin and restart to take effect. $svcName = Get-Service -DisplayName *jenkins* | select -Exp Name $svcKey = Get-Item HKLM:\SYSTEM\CurrentControlSet\Services\$svcName # Set 9th bit, from http://www.codeproject.com/KB/install/cswindowsservicedesktop.aspx $newType = $svcKey.GetValue('Type') -bor 0x100 Set-ItemProperty $svcKey.PSPath -Name Type -Value $newType
PowerShellCorpus/GithubGist/AmaiSaeta_7874062_raw_1a82df073c622100656b1381baf401d0400d86a4_gistfile1.ps1
AmaiSaeta_7874062_raw_1a82df073c622100656b1381baf401d0400d86a4_gistfile1.ps1
((Get-Content Env:Path) -Split ";" | Where-Object { $_ -notmatch "\b" + "HOGEHOGE" + "\b" }) -Join ";" | Set-Content Env:Path
PowerShellCorpus/GithubGist/Romoku_4001927_raw_de5c93662ed48237fa392059af011a541d4d9ae2_sample.ps1
Romoku_4001927_raw_de5c93662ed48237fa392059af011a541d4d9ae2_sample.ps1
$inDirectory = "c:\temp\downloads" $encoderDirectory = "c:\temp\done" $encoder = "c:\temp\done\sample.bat" $logFile = "c:\temp\log.txt" $extension = "*.jnt" Function StripChar($s) { $s.replace(" ","_").replace(",","_").replace("~","_").replace("#", "_") } Function MoveFile($filePath, $fileName) { $newPath = "${encoderDirectory}\${fileName}" [System.IO.File]::Move($filePath, $newPath) } Function Log($fileName) { $currentDate = Get-Date Add-Content $logFile "Started encoding ${fileName} at ${currentDate}" } Function StartEncoding($fileName) { Start-Process $encoder $fileName } Get-ChildItem $inDirectory -Filter $extension | Foreach-Object { $fileName = StripChar $_.Name MoveFile $_.FullName $fileName Log $fileName StartEncoding $fileName }
PowerShellCorpus/GithubGist/kurukurupapa_7297123_raw_73af4992c4cfda8a4bf1fc3025990801ff025bca_OdbcCommand002.ps1
kurukurupapa_7297123_raw_73af4992c4cfda8a4bf1fc3025990801ff025bca_OdbcCommand002.ps1
Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" $WarningPreference = "Continue" $VerbosePreference = "Continue" $DebugPreference = "Continue" # ライブラリ読み込み [void][System.Reflection.Assembly]::LoadWithPartialName("System.Data") ###################################################################### ### 関数定義 ###################################################################### # トランザクション管理して、コミットするテスト。 function U-Test-Commit() { # トランザクション開始 $odbcTran = $odbcCon.BeginTransaction() $odbcCmd.Transaction = $odbcTran Write-Debug "トランザクション開始" # コマンド実行(INSERT) $odbcCmd.CommandText = "INSERT INTO TEST (ID, NAME) VALUES (100, 'りんご')" $odbcCmd.ExecuteNonQuery() | Out-Null # コミット $odbcTran.Commit() Write-Debug "コミット" } # トランザクション管理して、ロールバックするテスト。 function U-Test-Rollback() { # トランザクション開始 $odbcTran = $odbcCon.BeginTransaction() $odbcCmd.Transaction = $odbcTran Write-Debug "トランザクション開始" # コマンド実行(INSERT) $odbcCmd.CommandText = "INSERT INTO TEST (ID, NAME) VALUES (101, 'みかん?')" $odbcCmd.ExecuteNonQuery() | Out-Null # ロールバック $odbcTran.Rollback() Write-Debug "ロールバック" } ###################################################################### ### 処理実行 ###################################################################### # DB接続 $connectionString = "DSN=H2TestDsn;uid=sa;pwd=sa;" $odbcCon = New-Object System.Data.Odbc.OdbcConnection($connectionString) $odbcCon.Open() # コマンドオブジェクト作成 $odbcCmd = New-Object System.Data.Odbc.OdbcCommand $odbcCmd.Connection = $odbcCon # コマンド実行(テーブル作成) $odbcCmd.CommandText = "CREATE TABLE TEST (ID INT PRIMARY KEY, NAME VARCHAR(255))" $odbcCmd.ExecuteNonQuery() | Out-Null # テスト U-Test-Commit U-Test-Rollback # コマンド実行(SELECT) $odbcCmd.CommandText = "SELECT * FROM TEST ORDER BY ID" $odbcReader = $odbcCmd.ExecuteReader() while ($odbcReader.Read()) { $odbcReader["ID"].ToString() + " " + $odbcReader["NAME"].ToString() } $odbcReader.Dispose() # コマンド実行(テーブル削除) $odbcCmd.CommandText = "DROP TABLE TEST" $odbcCmd.ExecuteNonQuery() | Out-Null # コマンドオブジェクト破棄 $odbcCmd.Dispose() # DB切断 $odbcCon.Close() $odbcCon.Dispose()
PowerShellCorpus/GithubGist/mike2718_1213521_raw_8fde42d7ba294db8b129618f345db2ce5da14a56_GetMelonBooksTopillust.ps1
mike2718_1213521_raw_8fde42d7ba294db8b129618f345db2ce5da14a56_GetMelonBooksTopillust.ps1
# PSVersion : 2.0 # PSCulture : zh-CN # PSUICulture : zh-CN # get-topillust.ps1 # Program: # Download topillustrations from MelonBooks. # 从MelonBooks网站下载所有的Top图片 # 依赖 curl.exe # History: # 2012/02/04 Mike Akiba Second release # 2014/09/29 Mike Akiba 修正起始图片的地址 curl.exe --progress-bar -R -O http://www.melonbooks.co.jp/contents/melon/topillust/img/melon[06-13][01-12].jpg -O http://www.melonbooks.co.jp/contents/melon/topillust/img/melon14[01-05].jpg
PowerShellCorpus/GithubGist/davidalpert_8244886_raw_13cc63911391731e4787f0f4a7c3276ab42761c2_gistfile1.ps1
davidalpert_8244886_raw_13cc63911391731e4787f0f4a7c3276ab42761c2_gistfile1.ps1
PS C:\users\davida\dev\marv.git\src\Marv> cpack Calling 'C:\Chocolatey\chocolateyInstall\nuget.exe pack -NoPackageAnalysis'. Attempting to build package from 'Marv.csproj'. Packing files from 'C:\users\davida\dev\marv.git\src\Marv\bin\Debug'. Using 'Marv.nuspec' for metadata. Found packages.config. Using packages listed as dependencies Successfully created package 'C:\users\davida\dev\marv.git\src\Marv\marv.0.2.1.0.nupkg'. Reading environment variables from registry. Please wait... Done.
PowerShellCorpus/GithubGist/mikecrittenden_5896762_raw_ae9d370dc9feb61d370eccb477f8ee128babd651_gistfile1.ps1
mikecrittenden_5896762_raw_ae9d370dc9feb61d370eccb477f8ee128babd651_gistfile1.ps1
--timeout="<number of seconds" # Use "0" for all. Defaults to "900". --count="<number of items>" # Defaults to "0" (all)
PowerShellCorpus/GithubGist/csharpforevermore_9179614_raw_7b3d394cbff75cf4e84e37da13aab60e81a79dbe_ListInstalledPrograms.ps1
csharpforevermore_9179614_raw_7b3d394cbff75cf4e84e37da13aab60e81a79dbe_ListInstalledPrograms.ps1
Get-WmiObject -Class Win32_Product | Select-Object -Property Name
PowerShellCorpus/GithubGist/philippdolder_add59168884bafca48a3_raw_ab594e5981950d8ae200eccfee9c0f797110ecf9_cmdlet.ps1
philippdolder_add59168884bafca48a3_raw_ab594e5981950d8ae200eccfee9c0f797110ecf9_cmdlet.ps1
function Tfs-UpdateFeature { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [ValidateScript({BranchExists $_})] [string] $localBranch, [parameter(Mandatory=$false)] [string] $mainBranch = "master" ) $shouldStash = git status --porcelain if ($shouldStash) { git stash save -u --keep-index } git checkout $mainBranch git tfs pull git checkout $localBranch git rebase $mainBranch if ($shouldStash) { git stash pop } } function Tfs-StartFeature { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string] $localBranch, [parameter(Mandatory=$false)] [string] $mainBranch = "master" ) git checkout $mainBranch git tfs pull git checkout -b $localBranch } function Tfs-CommitFeature { [CmdletBinding()] param ( [parameter(Mandatory=$false)] [ValidateScript({BranchExists $_})] [string] $localBranch ) if ($localBranch) { git checkout $localBranch } git tfs checkintool } function Remove-Feature { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [ValidateScript({BranchExists $_})] [string] $localBranch, [parameter(Mandatory=$false)] [ValidateScript({BranchExists $_})] [string] $mainBranch = "master" ) git checkout $mainBranch git branch -D $localBranch } function BranchExists { param ( [parameter(Mandatory=$true)] [string] $branch) $branches = (git branch --list) | ForEach-Object { $_.Substring(2) } return $branches.Contains($branch) } function Tfs-ValidateBranch { [CmdletBinding()] param () DynamicParam { # Set the dynamic parameters' name $ParameterName = 'Branch' # Create the dictionary $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary # Create the collection of attributes $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters' attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $true $ParameterAttribute.Position = 1 # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) $AliasAttribute = New-Object System.Management.Automation.AliasAttribute("b") $AttributeCollection.Add($AliasAttribute) # Generate and set the ValidateSet $arrSet = (git branch --list) | ForEach-Object { $_.Substring(2) } $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) return $RuntimeParameterDictionary } begin { # Bind the parameter to a friendly variable $Branch = $PsBoundParameters[$ParameterName] } process { # Your code goes here Write-Host "yeah $Branch exists" } } function Tfs-Validate-Branch2 { [CmdletBinding()] param () DynamicParam { New-DynamicParameter -ParameterName "Branch" -AllowedValues {(git branch --list) | ForEach-Object { $_.Substring(2) }} -Aliases "b" } begin { $Branch = $PsBoundParameters["Branch"] } process { # Your code goes here Write-Host "yeah $Branch exists" } } function New-DynamicParameter { param( [parameter(Mandatory=$true, Position=0)] [string] $ParameterName, [parameter(Mandatory=$true, Position=1)] [scriptblock] $AllowedValues, [parameter(Mandatory=$false, Position=2, ValueFromRemainingArguments=$true)] [string[]] $Aliases ) # Create the dictionary $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary # Create the collection of attributes $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters' attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $true $ParameterAttribute.Position = 1 # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) if ($Aliases) { $AliasAttribute = New-Object System.Management.Automation.AliasAttribute($Aliases) $AttributeCollection.Add($AliasAttribute) } # Set the ValidateSet $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute(Invoke-Command $AllowedValues) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) $RuntimeParameterDictionary }
PowerShellCorpus/GithubGist/gifnksm_261775_raw_d54f7a508f119c3c056447007691514ddbb305c5_fx_optimize_sqlite.ps1
gifnksm_261775_raw_d54f7a508f119c3c056447007691514ddbb305c5_fx_optimize_sqlite.ps1
param ([switch]$force) $appProfDir = join-path $env:appdata "Mozilla\Firefox\Profiles" $localProfDir = join-path $env:localappdata "Mozilla\Firefox\Profiles" # http://csharper.blog57.fc2.com/blog-entry-206.html function global:Invoke-Process { param ([string] $processPath, [string]$processArgs, [int]$timeoutMilliseconds = [System.Threading.Timeout]::Infinite) trap { if ($() -ne $process) { $process.Dispose(); } break; } if ([String]::IsNullOrEmpty($processPath)) { throw "引数 processPath が null または空の文字列です。"; } $process = New-Object "System.Diagnostics.Process"; $process.StartInfo = New-Object "System.Diagnostics.ProcessStartInfo" @($processPath, $processArgs); $process.StartInfo.WorkingDirectory = (Get-Location).Path; $process.StartInfo.RedirectStandardOutput = $True; $process.StartInfo.RedirectStandardError = $True; $process.StartInfo.UseShellExecute = $False; $process.Start() | Out-Null; $message = $process.StandardOutput.ReadToEnd(); $errorMessage = $process.StandardError.ReadToEnd(); $complete = $process.WaitForExit($timeoutMilliseconds); if (!$complete) { $process.Kill(); } $result = @{ "IsSuccess" = ($process.ExitCode -eq 0); "IsComplete" = $complete; "Message" = $message; "ErrorMessage" = $errorMessage; }; $process.Dispose(); return $result; } function parse-dir($path) { write-host "$path"; get-childitem $path -force | where { $_.Mode -match "^d" } | foreach { $profName = (split-path $_ -leaf).split(".", 2)[1]; write-host " * $profName"; get-childitem $_.fullname -filter "*.sqlite" | where { $bak = "$($_.fullname).bak"; $force -or -not (test-path $bak) -or ($_.lastwritetime -gt (get-item $bak).lastwritetime) } | foreach { $file = $_; $bakPath = "$($file.fullname).bak"; write-host " + $($file.name): " -nonewline; copy-item $file.fullname $bakPath; $bak = get-item $bakPath; $res1 = Invoke-Process "sqlite3" "`"$($file.fullname)`" vacuum"; $res2 = Invoke-Process "sqlite3" "`"$($file.fullname)`" reindex"; if($res1.IsSuccess -and $res2.IsSuccess) { # renew fileinfo (filesize) $file = get-item $file.fullname write-host "optimized" -foregroundcolor "blue"; $diff = 100 * (1 - $file.length / $bak.length); write-host (" {0:N0} => {1:N0} bytes ({2:N2})%" -f ($bak.length, $file.length, $diff)); $bak.set_lastwritetime($(get-date)); } else { write-host "error" -foregroundcolor "red"; write-host " vacuum: " -nonewline; write-host $res1.ErrorMessage -foregroundcolor "red" -nonewline; write-host " reindex: " -nonewline; write-host $res2.ErrorMessage -foregroundcolor "red" -nonewline; $bak.set_lastwritetime($file.lastwritetime - 10) } }; }; write-host ""; } parse-dir $appProfDir parse-dir $localProfDir
PowerShellCorpus/GithubGist/guitarrapc_ad416c54c78469dc6474_raw_2ad571495f1f525746ac04f480d43a7e55fb5c3f_PowerShellStringEvaluation.ps1
guitarrapc_ad416c54c78469dc6474_raw_2ad571495f1f525746ac04f480d43a7e55fb5c3f_PowerShellStringEvaluation.ps1
# PowerShell の String中への変数埋め込みってば罠だらけね! # 例 に示す変数をString中に表示するには5つ方法がある $hoge = @{hoge = "hoge"} $fuga = "fuga" #1. 直 (Property指定がだめ "$hoge" '$hoge' "$hoge.hoge" #2. ${} でくくる。これもプロパティ指定がだめ (in-line評価 => bash スタイル) "${hoge}" "${fuga}" #3. $() でくくる。部分式扱いなので、先行評価、展開される "$($hoge.hoge)" #4. "{0}" -f オペレータでインデックス指定 "{0}" -f $hoge.hoge #5. [String]::Format() [String]::Format("{0}", $hoge.hoge) # インデックス指定の注意 #これは評価できる "{{0}}" -f $hoge.hoge # 問題はこれ => {}の間に改行が挟まるとパースに失敗する。つまり、json 中への埋め込みが苦手 "{ {0} }" -f $hoge.hoge <# Error formatting a string: Input string was not in a correct format.. At line:1 char:5 + "{ + ~~ + CategoryInfo : InvalidOperation: ({ {0} }:String) [], RuntimeException + FullyQualifiedErrorId : FormatError #> # 対応方法 # 1. 直を使う (但し、後ろの文字が変数の一部として評価される可能性が高いのでだめだめ) # 2. $() 部分式を使う # ただし インデックス指定のメリット、 # 1. 繰り返し利用時に何度も書かなくていい => "{0}-{1}-{0}" -f $hoge.hoge, $fuga # 2. 変数の変更に強い => 途中で当てる変数を変更したり、順序の変更がインデックス指定なので容易 # 結論 # 機能としては部分式最強 # だが、スクリプトなど(変更が発生しえる場合)にはインデックス指定が楽。 # ワンライナーなど単純な時は直もあり。
PowerShellCorpus/GithubGist/wictorwilen_4f40541a78b54951ebb7_raw_f0b702fff0d7fe6c9c2dbafdec5f1b731510d036_Reset-SPCache.ps1
wictorwilen_4f40541a78b54951ebb7_raw_f0b702fff0d7fe6c9c2dbafdec5f1b731510d036_Reset-SPCache.ps1
asnp microsoft.sharepoint.powershell Get-SPServer | ?{$_.Role -eq "Application"} | %{ Write-Host -ForegroundColor Green "Updating $_ ..." Invoke-Command -ComputerName $_.Name { Stop-Service SPTimerV4 Stop-Service SPAdminV4 Get-ChildItem $env:ALLUSERSPROFILE\Microsoft\SharePoint\Config | ?{$_.Name.Contains("-")} | Get-ChildItem | ?{$_.Extension -eq ".xml"} | Remove-Item $ini = Get-ChildItem $env:ALLUSERSPROFILE\Microsoft\SharePoint\Config | ?{$_.Name.Contains("-")} | Get-ChildItem | ?{$_.Extension -eq ".ini"} "1" | Set-Content $ini.FullName Start-Service SPTimerV4 Start-Service SPAdminV4 } }
PowerShellCorpus/GithubGist/racingcow_f550737490270d7ee760_raw_ddfbc33145245dcd65d07a170d7a72d62418ff16_servermachine.ps1
racingcow_f550737490270d7ee760_raw_ddfbc33145245dcd65d07a170d7a72d62418ff16_servermachine.ps1
############################################################ # Join domain ############################################################ # Rename-Computer -NewName DEVCE1 -LocalCredential admin # if (Test-PendingReboot) { Invoke-Reboot } # Add-Computer -DomainName CT -Credential CT\imagioprodsvc # if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # Boxstarter options ############################################################ $Boxstarter.RebootOk=$true # Allow reboots? $Boxstarter.NoPassword=$false # Is this a machine with no login password? $Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot ############################################################ #basic setup ############################################################ Update-ExecutionPolicy Unrestricted Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Enable-RemoteDesktop Disable-InternetExplorerESC Disable-UAC Set-TaskbarSmall Write-BoxstarterMessage "Setting time zone to Central Standard Time" & C:\Windows\system32\tzutil /s "Central Standard Time" cinst Microsoft-Hyper-V-All -source windowsFeatures cinst IIS-WebServerRole -source windowsfeatures cinst IIS-HttpCompressionDynamic -source windowsfeatures cinst IIS-WindowsAuthentication -source windowsfeatures cinst DotNet3.5 if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # Update Windows and reboot if necessary ############################################################ Install-WindowsUpdate -AcceptEula if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # utils, plugins, frameworks, and other miscellany ############################################################ cinst javaruntime cinst webpi cinst adobereader cinst flashplayeractivex cinst flashplayerplugin cinst AdobeAIR cinst 7zip cinst PDFCreator cinst lockhunter cinst windirstat cinst ransack if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # development ############################################################ cinst DotNet3.5 # Not automatically installed with VS 2013. Includes .NET 2.0. Uses Windows Features to install. if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # text editors ############################################################ cinst notepadplusplus.install if (Test-PendingReboot) { Invoke-Reboot } ############################################################ # browsers ############################################################ cinst GoogleChrome cinst GoogleChrome.Canary cinst Firefox cinst Opera cinst safari cinst lastpass if (Test-PendingReboot) { Invoke-Reboot }
PowerShellCorpus/GithubGist/alanrenouf_1a0aefc4ddf3f37c6ea7_raw_7b13ceb999f12b1a93e58680b990c569605299a1_DeployVCNS_55.ps1
alanrenouf_1a0aefc4ddf3f37c6ea7_raw_7b13ceb999f12b1a93e58680b990c569605299a1_DeployVCNS_55.ps1
Connect-VIServer 192.168.1.200 -User [email protected] -Password VMware1! $vShieldInstallFile = "C:\Temp\VMware-vShield-Manager-5.5.3-2175697.ova" $vShieldName = "VCNS01" $vShieldNetwork = "VM Network" $vShieldIP = "192.168.1.210" $vShieldSNM = "255.255.255.0" $vShieldDGW = "192.168.1.1" $vShieldDNS = "192.168.1.1" $vShieldCluster = "Home-Cluster" $vShieldPassword = "VMware1!" $vShieldvC = "192.168.1.200" $vShieldvCUser = "[email protected]" $vShieldvCPass = "VMware1!" if (!(get-pssnapin -name VMware.VimAutomation.Core -erroraction 'SilentlyContinue')) { Write-Host "[INFO] Adding PowerCLI Snapin" add-pssnapin VMware.VimAutomation.Core -ErrorAction 'SilentlyContinue' if (!(get-pssnapin -name VMware.VimAutomation.Core -erroraction 'SilentlyContinue')) { Write-Host "[ERROR] PowerCLI Not installed, please install from Http://VMware.com/go/PowerCLI" } Else { Write-Host "[INFO] PowerCLI Snapin added" } Connect-VIServer $vShieldvC -User $vShieldvCUser -Password $vShieldvCPass } $vShieldSpaceNeededGB = "5" Write-Host "[INFO] Selecting host for $vShieldName from $vShieldCluster Cluster" $vShieldVMHost = Get-Cluster $vShieldCluster | Get-VMHost | Where {$_.PowerState -eq "PoweredOn" -and $_.ConnectionState -eq "Connected" } | Get-Random Write-Host "[INFO] $vShieldVMHost selected for $vShieldName" Write-Host "[INFO] Selecting Datastore for $vShieldName" $vShieldDatastore = $vShieldVMHost | Get-Datastore | Where {$_.ExtensionData.Summary.MultipleHostAccess} | Where {$_.FreeSpaceGB -ge $vShieldSpaceNeededGB} | Get-Random if (!$vshieldDatastore) { Write-Host "[ERROR] No Available Shared datastores with $vShieldSpaceNeededGB GB available" ; Exit } Write-Host "[INFO] $vShieldDatastore selected for $vShieldName" $Settings = Get-OvfConfiguration $vShieldInstallFile $Settings.NetworkMapping.VSMgmt.value = $vShieldNetwork $Settings.Common.vsm_cli_en_passwd_0.value = $vShieldPassword $Settings.Common.vsm_cli_passwd_0.value = $vShieldPassword Write-Host "[INFO] Importing $vShieldName from $vShieldInstallFile" $vShieldDeployedVMTask = $vShieldVMHost | Import-vApp -OvfConfiguration $Settings -Name $vShieldName -Source $vShieldInstallFile -Datastore $vShieldDatastore -Force -RunAsync do { Sleep 1 Write-progress -Activity "Deploying $vShieldName" -PercentComplete $($vShieldDeployedVMTask.PercentComplete) -Status "$($vShieldDeployedVMTask.PercentComplete)% completed" } until ($vShieldDeployedVMTask.PercentComplete -eq 100 ) Write-Host "[INFO] $vShieldName deployed and the task result was $($vShieldDeployedVMTask.State)" If ($vShieldDeployedVMTask.State -ne "success") { Write-Host "[ERROR] Unable to deploy vShield, deploy failed with $($vShieldDeployedVMTask.TerminatingError)" Exit } Else { $vShieldDeployedVM = Get-VM $vShieldName $NetworkChange = $vShieldDeployedVM | Get-NetworkAdapter If ($NetworkChange.NetworkName -ne $vShieldNetwork) { Write-Host "[INFO] Reconfiguring Network on $vShieldName to join $vShieldNetwork" $NetworkChange | Set-NetworkAdapter -NetworkName $vShieldNetwork -Confirm:$false } $key = "machine.id" $value = "ip_0={0}&gateway_0={1}&computerName={2}&netmask_0={3}&markerid=1&reconfigToken=1" -f $vShieldIP, $vShieldDGW, $vShieldName, $vShieldSNM $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue $vmConfigSpec.extraconfig[0].Key=$key $vmConfigSpec.extraconfig[0].Value=$value Write-Host "[INFO] Reconfiguring $vShieldName after deployment" $SetConfig = $vShieldDeployedVM.ExtensionData.ReconfigVM_Task($vmConfigSpec) Write-Host "[INFO] Power On $vShieldName for first time" $vShieldDeployedVM | Start-VM | Out-Null Write-Host "[INFO] $vShieldName deployment and configuration completed." }
PowerShellCorpus/GithubGist/belotn_7751223_raw_70bc470ce4f84940314a6df0401440cf9b8b3dca_set-xaserverlicence.ps1
belotn_7751223_raw_70bc470ce4f84940314a6df0401440cf9b8b3dca_set-xaserverlicence.ps1
get-xaserver | get-xaserverconfiguration |? {! $_.LicenseServerUseFarmSettings } |%{ set-xaserverconfiguration -ServerNAme $_.ServerName -LicenseServerUseFarmSettings $true }
PowerShellCorpus/GithubGist/mdnmdn_7352745_raw_c364cfa20b9a75fbd39862c43adc2d75927d7a0e_excel-lib.ps1
mdnmdn_7352745_raw_c364cfa20b9a75fbd39862c43adc2d75927d7a0e_excel-lib.ps1
if (! (Test-Path variable:global:excelApp)){ $global:excelApp = $null } function createExcel(){ if ($global:excelApp -eq $null){ doEng({ Write-Host 'new excel app' $global:excelApp = New-Object -comobject Excel.Application $global:excelApp.visible = $true }) } return $global:excelApp } function resetExcel(){ if ($global:excelApp -ne $null){ doEng({ $global:excelApp.Quit() $global:excelApp= $null }) } } function createWorkbook($fileName = $null){ createExcel if ($fileName -eq $null){ doeng {$global:excelApp.Workbooks.Add()} } else { doeng {$global:excelApp.Workbooks.Open($fileName) } } } function closeWorkbook(){ if ($global:excelApp.ActiveWorkbook -ne $null) { doeng{$global:excelApp.ActiveWorkbook.Close($false)} } } function saveWorkbook($fileName = $null){ if ($fileName -eq $null){ doeng {$global:excelApp.ActiveWorkbook.Save()} } else { doeng {$global:excelApp.ActiveWorkbook.SaveAs($fileName) } } } function createWorksheet($name){ doeng { $worksheets = $global:excelApp.ActiveWorkbook.Worksheets $worksheet = $worksheets.Add([System.Reflection.Missing]::Value,$worksheets.Item($worksheets.Count)) $worksheet.name = $name } } function selectWorksheet($name){ doeng { $global:excelApp.ActiveWorkbook.Worksheets.Item($name).Activate } } function renameWorksheet($newName){ doeng { $global:excelApp.ActiveWorkbook.ActiveSheet.name = $newName } } function deleteWorksheet($name){ doeng { $global:excelApp.DisplayAlerts = $false $global:excelApp.ActiveWorkbook.Worksheets.Item($name).Delete() $global:excelApp.DisplayAlerts = $true } } function writeCell($row,$col,$value){ doeng{$global:excelApp.ActiveWorkbook.ActiveSheet.Cells.Item($row,$col).Formula = $value} } function writeCells($startRow,$col,$values){ doeng{ [Windows.Forms.Clipboard]::SetText($values -join "`r`n") $global:excelApp.ActiveWorkbook.ActiveSheet.Cells.Item($startRow,$col).PasteSpecial() | Out-Null } } function readCell($row,$col){ doeng{$global:excelApp.ActiveWorkbook.ActiveSheet.Cells.Item($row,$col).Formula} } function doCell($row,$col,$action){ doeng{&$action($global:excelApp.ActiveWorkbook.ActiveSheet.Cells.Item($row,$col) )} } function cell($row,$col,$val = $null){ doeng{ $cell = $global:excelApp.ActiveWorkbook.ActiveSheet.Cells.Item($row,$col); if ($val -eq $null) { return $cell.Formula } elseif ($val -is [Scriptblock]) { return &$val($cell) } else { $cell.Formula = $val } } } function doRange($row1,$col1,$row2,$col2,$val){ doeng{ $sheet = $global:excelApp.ActiveWorkbook.ActiveSheet $cells = $sheet.Cells; $range = $sheet.Range($cells.Item($row1,$col1),$cells.Item($row2,$col2)) if ($val -eq $null) { return $range } elseif ($val -is [Scriptblock]) { return &$val($range) } else { $range.Formula = $val } } } function convNum($val){ if ($val -is [string]){ $val = $val.replace(',','.') } return $val; } function doEng($script){ $originalCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture; [System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]"en-US" $val = &$script [System.Threading.Thread]::CurrentThread.CurrentCulture = $originalCulture return $val; }
PowerShellCorpus/GithubGist/tamirko_b07f1810517628fc1980_raw_40bef5f8e7e9e3efdfab4f6892f89806a5011eae_gitClone.ps1
tamirko_b07f1810517628fc1980_raw_40bef5f8e7e9e3efdfab4f6892f89806a5011eae_gitClone.ps1
if ($ENV:GSA_MODE -ne "agent") { # Create the git clone service/task here …. $javaExe = "$javaDir\bin\java" $gitUtilZipName = "gitUtil.zip" $gitUtilZipUrl = "REPLACE_THIS_WITH_FULL_URL/$gitUtilZipName" $gitUtilLocalZip = "$parentDirectory\$gitUtilZipName" $gitUtilFolder = "$parentDirectory\gitutil" $destGitFolder = "$parentDirectory\gigaspaces\work\cloudify_recipes_clone" $gitRepoUrl = "[email protected]:CloudifySource/cloudify-recipes.git" Write-Host "Downloading the git clone utility from $gitUtilZipUrl to $gitUtilLocalZip ..." download $gitUtilZipUrl $gitUtilLocalZip Write-Host "Unzipping the git clone utility ( $gitUtilLocalZip ) to $gitUtilFolder ..." unzip $gitUtilLocalZip $gitUtilFolder Write-Host "Creating the git clone (cloudify-git) task to run every 10 minutes ..." schtasks.exe /create /TN cloudify-git /IT /SC MINUTE /MO 10 /TR "$gitUtilFolder\MyGitGetter.bat $javaExe $gitUtilFolder $destGitFolder $gitRepoUrl" /RU $ENV:USERNAME /RP $ACTUAL_PASSWORD Write-Host "running the cloudify-git task" schtasks.exe /run /TN cloudify-git Write-Host "Created and ran the cloudify-git task" } Write-Host "Remote execution ended successfully" exit 0
PowerShellCorpus/GithubGist/pohatu_5827442_raw_cf7060b90e81dac2987bce85536420e4a0bf286b_gistfile1.ps1
pohatu_5827442_raw_cf7060b90e81dac2987bce85536420e4a0bf286b_gistfile1.ps1
# Problem: # In a country in which people only want boys every family continues to have children until they have a boy. # If they have a girl, they have another child. If they have a boy, they stop. # What is the proportion of boys to girls in the country? $global:m=0; $global:f=0; function havebabiesuntilboy(){ while($true){ if ((Get-Random -Minimum 0 -Maximum 2) -eq 1) { #write-host "boy" $global:m++; break; } else{ #write-host "girl" $global:f++; } } } 1..100000 | % { havebabiesuntilboy} # This runs iteratively, but it could run in parallel. It's a simulation so it doesn't matter to the math. # However, it is a nice simply stated problem that would make a good example for a map/reduce styled solution. # I leave that as an exercise to the reader. write-host ("{0:P2}" -f ($m/($f+$m))) "percent male" write-host ("{0:P2}" -f ($f/($f+$m))) "percent female"
PowerShellCorpus/GithubGist/whataride_7638296_raw_7d91819dd987e839d45146cc36ebdf124e1eea4b_InteractWithDocNET.ps1
whataride_7638296_raw_7d91819dd987e839d45146cc36ebdf124e1eea4b_InteractWithDocNET.ps1
# Static method [System.Diagnostics.Process]::GetProcessById(0) # Static property [System.DateTime]::Now #Instance method $process = Get-Prococess Notepad $process.WaitForExit() # Instance property $today = Get-Date $doday.DayOfWeek
PowerShellCorpus/GithubGist/bat2001_6465494_raw_266872b1720f636256ad62451d62a2c231856f8f_gistfile1.ps1
bat2001_6465494_raw_266872b1720f636256ad62451d62a2c231856f8f_gistfile1.ps1
$arrInstancesSuspended = @() foreach ($Row in $DataSet1.Tables[0].Rows) { $arrInstancesSuspended = $arrInstancesSuspended + (,($Row["ApplicationName"],$Row["InstanceID"])) # Use format: $arrInstancesSuspended [0][0] } # Sort Array $arrInstancesSuspended = $arrInstancesSuspended | Sort-Object @{Expression={$_[0]};Ascending=$true} # Get unique apps $unique_Application = $arrInstancesSuspended | foreach {$_[0]} | sort-object -unique # Ready to push out needed values foreach ($appName in $unique_Application) { $Temp = ($arrInstancesSuspended -match $appName) | where {$_[0].Length -eq $appName.Length} $Count = $Temp.count Write-Host $appName $Count }
PowerShellCorpus/GithubGist/wojtha_1034041_raw_1f09b634e99e7ddb67069abee6297630cc666e93_profile.ps1
wojtha_1034041_raw_1f09b634e99e7ddb67069abee6297630cc666e93_profile.ps1
# My preferred prompt for Powershell. # Displays git branch and stats when inside a git repository. # See http://gist.github.com/180853 for gitutils.ps1. . (Resolve-Path ~/Documents/WindowsPowershell/gitutils.ps1) function prompt { $path = "" $pathbits = ([string]$pwd).split("\", [System.StringSplitOptions]::RemoveEmptyEntries) if($pathbits.length -eq 1) { $path = $pathbits[0] + "\" } else { $path = $pathbits[$pathbits.length - 1] } $userLocation = $env:username + '@' + [System.Environment]::MachineName + ' ' + $path $host.UI.RawUi.WindowTitle = $userLocation Write-Host($userLocation) -nonewline -foregroundcolor Green if (isCurrentDirectoryGitRepository) { $status = gitStatus $currentBranch = $status["branch"] Write-Host(' [') -nonewline -foregroundcolor Yellow if ($status["ahead"] -eq $FALSE) { # We are not ahead of origin Write-Host($currentBranch) -nonewline -foregroundcolor Cyan } else { # We are ahead of origin Write-Host($currentBranch) -nonewline -foregroundcolor Red } Write-Host(' +' + $status["added"]) -nonewline -foregroundcolor Yellow Write-Host(' ~' + $status["modified"]) -nonewline -foregroundcolor Yellow Write-Host(' -' + $status["deleted"]) -nonewline -foregroundcolor Yellow if ($status["untracked"] -ne $FALSE) { Write-Host(' !') -nonewline -foregroundcolor Yellow } Write-Host(']') -nonewline -foregroundcolor Yellow } Write-Host('>') -nonewline -foregroundcolor Green return " " }
PowerShellCorpus/GithubGist/cchitsiang_7038063_raw_e4e4eced2ef695a47985a3d44c98d26308179501_getuserandgroup.ps1
cchitsiang_7038063_raw_e4e4eced2ef695a47985a3d44c98d26308179501_getuserandgroup.ps1
-- Username1 | Group1, Group 2, Group 3, Group 4, Group 5 etc. $memberOf = @{n='MemberOf';e={ ($_.MemberOf -replace '^CN=([^,]+).+$','$1') -join ';' }} Get-QADUser -SizeLimit 0 | ` Select-Object Name,DN,SamAccountName,$memberOf | ` Export-Csv report.csv
PowerShellCorpus/GithubGist/coza73_461149c412b02cc64851_raw_368bb7ddb6c545c261c121f781fc09b23b8e7250_TemplateMigrate.ps1
coza73_461149c412b02cc64851_raw_368bb7ddb6c545c261c121f781fc09b23b8e7250_TemplateMigrate.ps1
<# NAME: MigrateTemplages.ps1 AUTHOR: Cory Murdoch EMAIL: cory at coryandwendy dot com BLOG: http://vspherepowershellscripts.blogspot.com .SYNOPSIS Scipt to migrate selected templates from one virtualcenter to another .DESCRIPTION Exports templates from a selected folder location and importes them into selected cluster, datastore/datastorecluster and network of a selected virtualcenter This script requires ovftool available from vmware.com .EXAMPLE Copy-Templates -SourceViServer vcenter1 -DestinationViServer vcenter2 -DestinationDataStore datastore2 \ -SourceDataCenter datacenter1 -DestinationDataCenter datacenter2 -DestinationCluster "cluster02 (Dev)" \ -SourceNetworkName Prod -DestinationNetworkName Dev \ -SourceFolderName templates -DestinationFolderName templates -TemplateTempFolder e:\templates\ .PARAMETER SourceViServer Source virtalcenter .PARAMETER DestinationViServer Destination virtualcenter .PARAMETER DestinationDataStore Destination datastore or datastore cluster name .PARAMETER SourceDataCenter Datacenter of source virtualcenter that contaings the templates .PARAMETER DestinationDataCenter Datacenter of destination virtualcenter that will contain the templates .PARAMETER DestinationCluster Cluster in which the templates will reside .PARAMETER SourceNetworkName The network name of the network port group that the source template is connected to .PARAMETER DestinationNetworkName The network name of the network port group that the destination template will be connected to .PARAMETER SourceFolderName The folder the Templates reside. This script will not recurse folders .PARAMETER DestinationFolderName The folder you wish the templates to be placed on the destination .PARAMETER TemplateTempFolder The folder to store the exported template ova's on the system that is running the script #> if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) { Add-PsSnapin VMware.VimAutomation.Core Add-PSSnapin "Vmware.VimAutomation.Core" } function log ([string]$logdata){ $logfile = "c:\temp\MigrateTemplate.log" $date = get-date Write-Output "$date - $logdata" | Out-File $logfile -width 240 -Append } Log "Starting" # check first if ovf tool is installed if not exit $ovftoolpaths = ("C:\Program Files (x86)\VMware\VMware OVF Tool\ovftool.exe", "C:\Program Files\VMware\VMware OVF Tool\ovftool.exe") $ovftool = '' foreach ($ovftoolpath in $ovftoolpaths) { if(test-path $ovftoolpath) { $ovftool = $ovftoolpath } } if (!$ovftool) { write-host -ForegroundColor red "ERROR: OVFtool not found in it's standard path." Log "ERROR: OVFtool not found in it's standard path." write-host -ForegroundColor red "Edit the path variable or download ovftool here: http://www.vmware.com/support/..." exit } function Export-VM { param ( [parameter(Mandatory=$true)][array] $vm, [parameter(Mandatory=$true)][String] $destination ) $vmd = $($vm.name) $moref = $vm.extensiondata.moref.value $session = Get-View -Id SessionManager $ticket = $session.AcquireCloneTicket() & $ovftool "--I:sourceSessionTicket=$($ticket)" "vi://$($defaultviserver.name)?moref=vim.VirtualMachine:$($moref)" "$($destination)$($vmd.substring(0,$vmd.Length)).ova" write-host ' ' } function Copy-Templates { param ( [parameter(Mandatory=$true)][String] $SourceViServer, [parameter(Mandatory=$true)][String] $DestinationViServer, [parameter(Mandatory=$true)][String] $DestinationDataStore, [parameter(Mandatory=$true)][String] $SourceDataCenter, [parameter(Mandatory=$true)][String] $DestinationDataCenter, [parameter(Mandatory=$true)][String] $DestinationCluster, [parameter(Mandatory=$true)][String] $SourceNetworkName, [parameter(Mandatory=$true)][String] $DestinationNetworkName, [parameter(Mandatory=$true)][String] $SourceFolderName, [parameter(Mandatory=$true)][String] $DestinationFolderName, [parameter(Mandatory=$true)][String] $TemplateTempFolder # Always follow with a backslash ) write-host "Connecting .... > to $SourceViServer" connect-viserver $SourceViServer write-host 'Creating list of Templates -->' -foregroundcolor blue $templatesObject = get-Datacenter $SourceDataCenter | get-folder $SourceFolderName| get-template -NoRecursion write-host 'Reading from List of Templates -->' -foregroundcolor blue foreach($template in $templatesObject.name){ connect-viserver $SourceViServer #Export the selected template to local storage $templateObject = get-template -Server $SourceViServer $template . Export-VM -vm $templateObject -destination $TemplateTempFolder write-host "Disconnecting .... > " $SourceViServer disconnect-viserver $SourceViServer -force -confirm:$false -ErrorAction:SilentlyContinue write-host "Connecting .... > " $DestinationViServer connect-viserver $DestinationViServer $vmhost = Get-Cluster $DestinationCluster | Get-VMHost $DestinationHost = $vmhost[0] #Delete the matching template from Destination if exists if (!(Get-Template $template -ErrorAction:SilentlyContinue)){ Write-Host 'Destination template does not exist --> '"$template" } Else{ write-host 'Deleting old template --> ' "$template" Remove-Template -DeletePermanently -Template $template -confirm:$false -server $DestinationViServer } write-host 'Deploying OVA --> ' "$template" -foregroundcolor blue $source = $($TemplateTempFolder + $template + ".ova") write-host $source $session = Get-View -Server $DestinationViServer -Id SessionManager $ticket = $session.AcquireCloneTicket() & $ovftool "--noSSLVerify" "--diskMode=thin" "--I:targetSessionTicket=$ticket" "-ds=$DestinationDataStore" "--net:$SourceNetworkName=$DestinationNetworkName" "$source" "vi://$($DestinationViServer)/$($DestinationDataCenter)?dns=$DestinationHost" write-host ' ' write-host 'Deleting OVA from $TemplateTempFolder --> ' $template -foregroundcolor blue del $($TemplateTempFolder + $template + ".ova") write-host 'Converting VM to Template --> ' $template -foregroundcolor blue set-vm -vm $template -Server $DestinationViServer -ToTemplate -name "$template" -confirm:$false Move-Template -Template $template -destination (Get-datacenter $DestinationDataCenter | get-folder $DestinationFolderName) write-host "Disconnecting .... > " $DestinationViServer disconnect-viserver $DestinationViServer -force -confirm:$false -ErrorAction:SilentlyContinue } write-host 'Disconnecting .... > server :' $SourceViServer disconnect-viserver $SourceViServer -Force -confirm:$false -ErrorAction:SilentlyContinue write-host 'Disconnecting .... > server :' $DestinationViServer disconnect-viserver $DestinationViServer -Force -confirm:$false -ErrorAction:SilentlyContinue write-host "Completed" write-host "`n" write-host "The following Templates have been copied:" write-host "From SOURCE ViServer: $SourceViServer" -foregroundcolor green write-host "To DESTINATION ViServer: $DestinationViServer" -foregroundcolor green write-host $templatesObject.Name -foregroundcolor blue }
PowerShellCorpus/GithubGist/adbertram_3d820b6062c2b30cdaca_raw_631e775153883c4b77e9085566ab5075070a45d7_gistfile1.ps1
adbertram_3d820b6062c2b30cdaca_raw_631e775153883c4b77e9085566ab5075070a45d7_gistfile1.ps1
#Requires -Version 4 <# .NOTES Created on: 10/8/2014 Created by: Adam Bertram Filename: Start-ModPollMonitor.ps1 Requirements: Share permissions for Everyone on destination share The source computer account Modify NTFS rights on destination folder .DESCRIPTION .EXAMPLE PS> .\Start-ModPollMonitor.ps1 .PARAMETER SourceFolderPath This is the folder path on the local computer that will be monitored for new files. .PARAMETER DestinationHost The destination host that the file will be copied to .PARAMETER DestinationFileShare The share name on the destination host where the file will be copied to .PARAMETER FileExtension This is the file extension that, when placed into SourceFolderPath path will kick off the Modbus process. This defaults to PDF. .PARAMETER ModPollFilePath The file path where the modpoll.exe file is located .PARAMETER FailureSourceFolderPath The path to the local folder that all failed modpoll files will be placed. This is only used if the file copy is unsuccessful. .PARAMETER MonitorIntervalSecs The number of seconds between script runs. .PARAMETER LogFilePath The file path to the log file that's generated with the progress of the script. This defaults to C:\Windows\Temp\Start-ModPollMonitor.log #> [CmdletBinding(SupportsShouldProcess)] param ( [Parameter()] [ValidateScript({ if (!(Test-Path -Path $_ -PathType Container)) { throw "The source folder path '$($_)' cannot be found" } else { $true } })] [string]$SourceFolderPath = 'C:\TestSourceFolder\folder', [Parameter()] [ValidateScript({ if (!(Test-Connection -ComputerName $_ -Quiet -Count 1)) { throw "The destination host '$($_)' does not appear to be online" } else { $true } })] [string]$DestinationHost = 'labdc.lab.local', [Parameter()] [string]$DestinationFileShare = 'plcscript', [Parameter()] [ValidatePattern('^\w{3}$')] [string]$FileExtension = 'pdf', [ValidateScript({ if (!(Test-Path -Path $_ -PathType Leaf)) { throw "Modpoll.exe cannot be found at '$($_)'" } else { $true } })] [string]$ModPollFilePath = 'C:\Users\administrator.LAB\Dropbox\Side Business\GitHubRepos\MiscScripts\PLCScript\Source\modpoll.exe', [ValidateScript({ if (!(Test-Path -Path $_ -PathType Container)) { throw "The failure source folder path '$($_)' cannot be found" } else { $true } })] [string]$FailureSourceFolderPath = 'C:\FailureSourceFolder', [Parameter()] [int]$MonitorIntervalSecs = 10, [Parameter()] [string]$LogFilePath = "$([environment]::GetEnvironmentVariable('TEMP','Machine'))\Start-ModPollMonitor.log" ) begin { function Write-Log { <# .SYNOPSIS This function creates or appends a line to a log file .DESCRIPTION This function writes a log line to a log file .PARAMETER Message The message parameter is the log message you'd like to record to the log file .PARAMETER LogLevel The logging level is the severity rating for the message you're recording. You have 3 severity levels available; 1, 2 and 3 from informational messages for FYI to critical messages. This defaults to 1. .EXAMPLE PS C:\> Write-Log -Message 'Value1' -LogLevel 'Value2' This example shows how to call the Write-Log function with named parameters. #> [CmdletBinding()] param ( [Parameter( Mandatory = $true)] [string]$Message, [Parameter()] [ValidateSet(1, 2, 3)] [int]$LogLevel = 1 ) try { $TimeGenerated = "$(Get-Date -Format HH:mm:ss).$((Get-Date).Millisecond)+000" ## Build the line which will be recorded to the log file $Line = '{2} {1}: {0}' $LineFormat = $Message, $TimeGenerated, (Get-Date -Format MM-dd-yyyy) $Line = $Line -f $LineFormat Add-Content -Value $Line -Path $LogFilePath } catch { Write-Error $_.Exception.Message } } function Convert-ToUncPath($LocalFolderPath, $Computername) { $RemoteFolderPathDrive = ($LocalFolderPath | Split-Path -Qualifier).TrimEnd(':') "\\$Computername\$RemoteFolderPathDrive`$$($LocalFolderPath | Split-Path -NoQualifier)" } function Send-PollToModbusSlave ($PollNumber,$RegisterNumber) { Write-Log -Message "Polling the Modbus slave with poll number $PollNumber" $Result = Start-Process -FilePath $ModPollFilePath -ArgumentList "-r$RegisterNumber localhost $PollNumber" -Wait -NoNewWindow -PassThru Start-Sleep -Seconds 2 if ($Result.ExitCode -ne 0) { Write-Log -Message 'Poll to modbus slave failed' -LogLevel '3' $false } else { Write-Log -Message 'Poll to modbus slave succeeded' $true } } function Validate-ModbusSlaveRunning { Write-Log -Message 'Validating the Modbus slave is running' $Result = Start-Process -FilePath $ModPollFilePath -ArgumentList "-r1 localhost $((get-date).Second)" -Wait -NoNewWindow -PassThru Start-Sleep -Seconds 2 if ($Result.ExitCode -ne 0) { Write-Log -Message 'Modbus slave is not running' -LogLevel '2' $false } else { Write-Log -Message 'Modbus slave is running' $true } } function Start-ModbusSlave { if (Test-Path 'C:\Program Files (x86)\Everest\Tools\PeakHmiMBTCPSlave.exe') { Start-Process -FilePath 'C:\Program Files (x86)\Everest\Tools\PeakHmiMBTCPSlave.exe' -NoNewWindow } elseif (Test-Path 'C:\Program Files\Everest\Tools\PeakHmiMBTCPSlave.exe') { Start-Process -FilePath 'C:\Program Files\Everest\Tools\PeakHmiMBTCPSlave.exe' -NoNewWindow } Write-Log -Message 'Modbus slave started' if (!(Validate-ModbusSlaveRunning)) { throw 'Attempted to start Modbus slave but failed.' } else { Write-Log -Message 'Successfully started modbus slave' $true } } function Start-FileCopyProcess ($FilePath, $DestUncFolderPath) { Write-Log -Message "Starting file copy of '$FilePath' to '$DestUncFolderPath'" $SourceHash = (Get-FileHash $FilePath).Hash Write-Log -Message "Source hash for '$FilePath' is '$SourceHash'" Copy-Item -Path $FilePath -Destination $DestUncFolderPath $DestUncFilePath = "$DestUncFolderPath\$($FilePath | Split-Path -Leaf)" $DestHash = (Get-FileHash $DestUncFilePath).Hash Write-Log -Message "Dest hash for '$DestUncFilePath' is '$DestHash'" if ($SourceHash -ne $DestHash) { Write-Log -Message "Source and destination file hash differ post file-copy. Copy failed." -LogLevel '2' Write-Log -Message "Moving $FilePath to $FailureSourceFolderPath" -LogLevel '2' Move-Item -Path $FilePath -Destination $FailureSourceFolderPath -Force } else { Write-Log -Message "Successfully copied file '$FilePath' to '$DestUncFolderPath' after 1 try" Send-PollToModbusSlave -PollNumber 2 -RegisterNumber 1 Write-Log -Message "Removing the file '$FilePath'" Remove-Item $FilePath -Force } } function New-FileMonitor { $WmiEventFilterQuery = " SELECT * FROM __InstanceCreationEvent WITHIN $MonitorIntervalSecs WHERE targetInstance ISA 'CIM_DataFile' AND targetInstance.Drive = `"$WmiEventSourceDrive`" AND targetInstance.Path = `"$($WmiEventSourceFolderPath.Replace('\','\\'))`" AND targetInstance.Extension = `"$FileExtension`"" $WmiFilterParams = @{ 'Class' = '__EventFilter' 'Namespace' = 'root\subscription' 'Arguments' = @{ Name = 'NewFile'; EventNameSpace = 'root\cimv2'; QueryLanguage = 'WQL'; Query = $WmiEventFilterQuery } } $WmiEventFilterPath = Set-WmiInstance @WmiFilterParams $WmiConsumerParams = @{ 'Class' = 'ActiveScriptEventConsumer' 'Namespace' = 'root\subscription' 'Arguments' = @{ Name = 'CopyFile'; ScriptFileName = $WmiEventLaunchScriptFilePath; ScriptingEngine = 'VBscript' } } $WmiConsumer = Set-WmiInstance @WmiConsumerParams $WmiFilterConsumerParams = @{ 'Class' = '__FilterToConsumerBinding' 'Namespace' = 'root\subscription' 'Arguments' = @{ Filter = $WmiEventFilterPath; Consumer = $WmiConsumer } } Set-WmiInstance @WmiFilterConsumerParams | Out-Null } function Validate-IsFileMonitorCreated { Get-WmiObject -Namespace 'root\subscription' -Class __FilterToConsumerBinding -Filter { Consumer = 'ActiveScriptEventConsumer.Name="CopyFile"' } } try { $WorkingDir = $MyInvocation.MyCommand.Path | Split-Path -Parent $WmiEventLaunchScriptFilePath = Get-ChildItem $WorkingDir -Filter *.vbs | select -ExpandProperty fullname $WmiEventSourceFolderPath = "$($SourceFolderPath | Split-Path -NoQualifier)\" $WmiEventSourceDrive = $SourceFolderPath | Split-Path -Qualifier if ($WmiEventLaunchScriptFilePath -is [array]) { throw "Multiple VBS files located in '$WorkingDir'. Only a single launch VBS should exist" } } catch { Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3' exit } } process { try { if (!(Validate-ModbusSlaveRunning)) { Write-Log -Message 'Modbus slave not running. Attempting to start' Start-ModbusSlave } if (!(Validate-IsFileMonitorCreated)) { Write-Log -Message 'The file copy monitor has not been created yet. Creating now' New-FileMonitor #} elseif () { # Write-Warning 'The file copy process is still running. Skipping this time' # exit } Send-PollToModbusSlave -PollNumber (Get-Date).Seconds -RegisterNumber 2 $SourceFiles = Get-ChildItem $SourceFolderPath -Filter "*.$FileExtension" -File if ($SourceFiles) { Write-Log -Message "Found $($SourceFiles.Count) files to attempt to copy." $DestUncFolderPath = "\\$DestinationHost\$DestinationFileShare" Write-Log -Message "Destination folder path is '$DestUncFolderPath'" if (!(Test-Path $DestUncFolderPath)) { throw "Destination folder path '$DestUncFolderPath' does not exist on remote computer" } if (!(Send-PollToModbusSlave -PollNumber 1 -RegisterNumber 1)) { throw "Failed to poll modbus slave with poll number 1" } $SourceFiles | foreach { Start-FileCopyProcess -DestUncFolderPath $DestUncFolderPath -FilePath $_.FullName } } else { Write-Log -Message "No $FileExtension files to process yet" } $FailedFiles = Get-ChildItem $FailureSourceFolderPath -File if ($FailedFiles) { Write-Log -Message "Found $($FailedFiles.Count) failed file to attempt to copy." foreach ($File in $FailedFiles) { Start-FileCopyProcess -DestUncFolderPath $DestUncFolderPath -FilePath $File.FullName } $FailedFiles = Get-ChildItem $FailureSourceFolderPath -File if (!$FailedFiles) { Write-Log -Message "Successfully copied all failed files from '$FailureSourceFolderPath'" if (!(Send-PollToModbusSlave -PollNumber 2 -RegisterNumber 1)) { throw "Failed to poll modbus slave with poll number 2" } } else { throw "Failed to copy all failed files from '$FailureSourceFolderPath'" } } else { Write-Log -Message 'No previously failed file copies to process' } } catch { Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3' } }
PowerShellCorpus/GithubGist/kurukurupapa_6327478_raw_7f7990a0746e830922bd3557f7eb23f3b499c778_EnvOutputTest.ps1
kurukurupapa_6327478_raw_7f7990a0746e830922bd3557f7eb23f3b499c778_EnvOutputTest.ps1
$sep = "*" * 50 Write-Output $sep Write-Output "カレントディレクトリ関連情報" Write-Output $sep Write-Output "`$pwd=$pwd" #$tmp = Get-Location #Write-Output "Get-Location=$tmp" Write-Output "Get-Location=$(Get-Location)" Write-Output $sep Write-Output "コマンド実行情報" Write-Output $sep $MyInvocation $basedir = Split-Path -Path $MyInvocation.InvocationName -Parent $name = Split-Path -Path $MyInvocation.InvocationName -Leaf Write-Output "当スクリプトの場所=$basedir" Write-Output "当スクリプトの名前=$name" Write-Output $sep Write-Output "環境変数一覧" Write-Output $sep #cd env: Push-Location env: Get-ChildItem Pop-Location Write-Output $sep Write-Output "システム日時" Write-Output $sep $date = Get-Date -Format "yyyymmdd" $timestamp = Get-Date -Format "yyyymmdd-HHmmss" Write-Output "システム日付=$date" Write-Output "タイムスタンプ=$timestamp"
PowerShellCorpus/GithubGist/peaeater_c2bb6e80ff483b7e735c_raw_f253eba2d6bdf053459e5d3cb7a8e181c71b09f1_hocr.ps1
peaeater_c2bb6e80ff483b7e735c_raw_f253eba2d6bdf053459e5d3cb7a8e181c71b09f1_hocr.ps1
# ocr tif/png to hocr (html) # requires tesseract Param( [string]$ext = "tif", [string]$indir = ".", [string]$outdir = $indir ) if (!(test-path $outdir)) { mkdir $outdir } $files = ls "$indir\*.*" -include *.$ext foreach ($file in $files) { $o = "$outdir\{0}" -f $file.BaseName $args = "`"$file`" `"$o`" hocr" start-process tesseract $args -wait -NoNewWindow }
PowerShellCorpus/GithubGist/grenade_8973223_raw_777b1e17a0e0a7b9ec0b2ba8ab7a29da83ad5f00_update-assembly-info.ps1
grenade_8973223_raw_777b1e17a0e0a7b9ec0b2ba8ab7a29da83ad5f00_update-assembly-info.ps1
param( [string] $assemblyInfoFile, [hashtable] $parameters ) Write-Host ("`$assemblyInfoFile: {0}" -f $assemblyInfoFile) foreach($key in $($parameters.Keys)){ if($parameters[$key] -ne $null){ $assemblyInfo = Get-Content $assemblyInfoFile $pattern = ('^\[assembly: {0}\("(.*)"\)\]' -f $key) $oldValue = ($assemblyInfo | Select-String -Pattern $pattern | % { $_.Matches } ).Groups[1].Value $match = ('[assembly: {0}("{1}")]' -f $key, $oldValue) $replace = ('[assembly: {0}("{1}")]' -f $key, $parameters[$key]) $assemblyInfo | ForEach-Object { % {$_ -Replace $match, $replace } } | Set-Content $assemblyInfoFile Write-Host ("{0} changed from: '{1}', to: '{2}'." -f $key, $oldValue, $parameters[$key]) } }
PowerShellCorpus/GithubGist/pierre3_b17830375b620d1557a5_raw_8a20420dceedf9d7268f476bbb16847ea1eab1b0_MarkdownPreview.ps1
pierre3_b17830375b620d1557a5_raw_8a20420dceedf9d7268f476bbb16847ea1eab1b0_MarkdownPreview.ps1
# このスクリプト自身が格納されているディレクトリを取得 $Script:scriptDir = Split-Path $MyInvocation.MyCommand.Definition -Parent <# .Synopsis Markdownテキストのプレビュー .DESCRIPTION Markdown形式で記述されたテキストファイルの内容をHTMLに変換し、ブラウザでプレビュー表示します。 .EXAMPLE PS C:\> Start-Markdown .\markdownText.md #> function Start-Markdown { Param( # Markdownテキストファイルのパス [string]$Path ) # HTMLテンプレート $html= @' <!DOCTYPE html> <html> <head> <title>Markdown Preview</title> </head> <body> {0} </body> </html> '@ # 指定したファイルが無ければ作る if(-not(Test-Path $Path)) { New-Item $Path -ItemType file -Force } # Markdownテキストが格納されているディレクトリをフルパスで取得 $sourceDir = Split-Path (Get-ChildItem $Path).FullName -Parent # プレビュー用HTMLの保存先 $previewDir = "$scriptDir\Html" if(-not(Test-Path $previewDir)) { New-Item $previewDir -ItemType directory } $previewPath = "$previewDir\MarkdownPreview.html" # MarkdownSharpのコンパイル & Markdown オブジェクトの生成 Add-Type -Path "$scriptDir\CSharp\MarkdownSharp.cs" ` -ReferencedAssemblies System.Configuration $markdown = New-Object MarkdownSharp.Markdown # Internet Exploroler を起動 $ie = New-Object -ComObject InternetExplorer.Application $ie.StatusBar = $false $ie.AddressBar = $false $ie.MenuBar = $false $ie.ToolBar = $false # Markdownテキストファイルの内容を変換してHTMLファイルとして保存 $rawText = Get-Content $Path -raw $html -f $markdown.Transform($rawText) | Out-File $previewPath -Encoding utf8 # ブラウザで表示 $ie.Navigate($previewPath) $ie.Visible = $true # Markdownテキストファイルの変更を監視する File Watcherを生成 $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = $sourceDir $watcher.Filter = Split-Path $Path -Leaf $watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor [System.IO.NotifyFilters]::LastWrite # Markdownテキストファイルを、その拡張子に関連付けされたアプリケーション(エディタ)で起動する start $Path # ファイルが変更されるのを監視し、変更されたらMarkdownテキストをHTMLに変換してInternet Explorerでプレビューする while($ie.ReadyState -ne $null) { $result = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::Changed, 5000) if(-not $result.TimedOut) { $rawText = Get-Content $Path -raw $html -f $markdown.Transform($rawText) | Out-File $previewPath -Encoding utf8 $ie.Refresh() } Start-Sleep -Milliseconds 100 } }
PowerShellCorpus/GithubGist/ao-zkn_8a5f3ca446cac0f084db_raw_bc2734a88f131c2e1b83d9ec811b9da47b6b1e21_Rename-File.ps1
ao-zkn_8a5f3ca446cac0f084db_raw_bc2734a88f131c2e1b83d9ec811b9da47b6b1e21_Rename-File.ps1
# ------------------------------------------------------------------ # ファイル名をリネームする # 関数名:Rename-File # 引数 :FilePath 名前を変更するファイルパス # :NewFileName 新しいファイル名前 # 戻り値:なし # ------------------------------------------------------------------ function Rename-File([String]$FilePath, [String]$NewFileName){ if(Test-Path -LiteralPath $FilePath -PathType Leaf){ Rename-Item $FilePath -newName $NewFileName Write-Host "ファイル名を変更しました。置換前[ $FilePath ] 置換後[ $NewFileName ]" }else{ Write-Host "ファイルが存在しません。ファイル名[ $FilePath ]" } }
PowerShellCorpus/GithubGist/janikvonrotz_7819984_raw_38bf41c27ce7befbe8e9c1c9be4a013350abccf8_CreateFolderIfNotExist.ps1
janikvonrotz_7819984_raw_38bf41c27ce7befbe8e9c1c9be4a013350abccf8_CreateFolderIfNotExist.ps1
if(!(Test-Path -path $LogPath)){New-Item $LogPath -Type Directory}
PowerShellCorpus/GithubGist/santifdezmunoz_166397_raw_ff3fa6f1048cfdd8bb9da82a87c13fa57c15a304_listACL.ps1
santifdezmunoz_166397_raw_ff3fa6f1048cfdd8bb9da82a87c13fa57c15a304_listACL.ps1
################################################################# # Script para obtener las listas de control de acceso asociadas # # a un arbol de directorios. # # # # AUTOR: Santiago Fernández Muñoz # # eMail: [email protected] # # Versión: 0.2 # # # # ChangeLog: # # · 0.2: - Corregido un bug con la impresión de la ayuda # # - Corregida la hoja de estilo para hacerla compatible # # con Firefox # # # # TODO: # # · Corregir las funciones Javascript que permiten la # # la expansión de los nodos del listado # # · Generar un arbol de directorios por usuario # ################################################################# param ([string] $equipo = 'localhost', [string] $path = $(if ($help -eq $false) {Throw "Es necesario indicar una ruta"}), [int] $nivel = 0, [string] $ambito = 'administrador', [switch] $help = $false, [switch] $debug = $false ) #region Impresion del mensaje de ayuda if ($help) { Write-Host @" /···········································································\ · Script de recopilación de la lista de control de acceso por directorio · \···········································································/ USO: ./listACL -equipo <nombre de máquina o IP> -path <ruta> -nivel <0-10> -help:<$true|$false> PARÁMETROS: equipo [OPCIONAL] - Nombre o dirección IP del equipo donde se encuentra la ruta de la que se desea obtener el listado de ACLs (Por defecto: localhost) path [OBLIGATORIO] - Ruta de directorios que se quiere consultar. nivel [OPCIONAL] - Nivel de directorios que se desea descender para realizar la consulta. Los valores válidos comprende de 0 a $nivelesPermitidos. El valor 0 indica que no se establece límite para el descenso de niveles (Por defecto: 0) ambito [OPCIONAL] - Indica la cantidad de información que se muestra en el informe generado. Los valores posibles son: · usuario, Muestra información relevante para el usuario. · micro, Muestra la información del ambito usuario más información relevante para el departamento de microinformatica. · administrador, Muestra toda la información. help [OPCIONAL] - Esta ayuda "@ exit 0 } #endregion #region Inciaclización de variables y comprobaciones previas #region Incialización de variables $nivelesPermitidos = 10 $Stamp = get-date -uformat "%Y%m%d" $informe = "$PWD\$equipo.html" $comparativa = "" $UNCPath = "\\" + $equipo + "\" + $path + "\" #endregion #region Comprobaciones previas #require -version 2.0 if ($nivel -gt $nivelesPermitidos -or $nivel -lt 0) {Throw "Nivel fuera del intervalo válido."} if ($equipo -eq 'localhost' -or $equipo -ieq $env:COMPUTERNAME) { $UNCPath = $path if (-not $(Test-Path $path)) {Throw "El directorio especificado no existe"} } switch ($ambito) { micro { $comparativa = '($acl -notlike "*Administrador*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*NT AUTHORITY*")' } usuario { $comparativa = '($acl -notlike "*Administrador*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*Microinformatica*" -and $acl -notlike "*NT AUTHORITY*" -and $acl -notlike "*Todos*")' } } #endregion #endregion #region Definición de funciones function dibujarDirectorio([ref] $directorio) { $dirHTML = ' <div class="' if ($directorio.value.nivel -eq 0) { $dirHTML += 'he0' } else { $dirHTML += 'he' + $directorio.value.nivel } $dirHTML += '"><span class="sectionTitle">Directorio ' + ` ($directorio.value.Folder.FullName -replace("á" ,"&aacute;") ` -replace("é","&eacute;") ` -replace("í","&iacute;") ` -replace("ó","&oacute;") ` -replace("ú","&uacute;")).toLower() ` + '</span></div> <div class="container"><div class="he' + ($directorio.value.nivel + 1) + '"><span class="sectionTitle">Lista de Control de Acceso</span></div> <div class="container"> <div class="heACL"> <table class="info3" cellpadding="0" cellspacing="0"> <thead> <tr><th style="width:25%"><b>Propietario</b></th> <th style="width:75%"><b>Permisos</b></th></tr> </thead> <tbody>' foreach ($itemACL in $directorio.value.ACL) { $acls = $null if ($itemACL.AccessToString -ne $null) { $acls = $itemACL.AccessToString.split("`n") } $dirHTML += '<tr><td>' + $itemACL.Owner + '</td> <td> <table class="info4"> <thead> <tr><th>Usuario</th> <th>Control</th> <th>Permisos</th></tr> </thead> <tbody>' foreach ($acl in $acls) { #$temp = [regex]::split($acl, "(?<!(,|NT))\s{1,}") $temp = [regex]::split($acl, "(Allow|Deny)") if ($debug) { write-host "ACL(" $temp.gettype().name ")[" $temp.length "]: " $temp } if ($temp.count -eq 1) { continue } $temp[1] = $temp[1] -replace("Allow", "Permitir") ` -replace("Deny", "Denegar") $temp[2] = $temp[2] -replace("FullControl", "Control Total") ` -replace("ReadAndExecute", "Lectura y Ejecuci&oacute;n") ` -replace("Read", "Lectura") ` -replace("Write", "Escritura") ` -replace("Synchronize", "Sincronizar") ` -replace("Modify", "Modificar") ` -replace("TakeOwnerShip", "Tomar posesi&oacute;n") if ($ambito -ne 'administrador') { if ( Invoke-Expression $comparativa ) { $dirHTML += "<tr><td>" + $temp[0].trim() + "</td><td>" + $temp[1].trim() + "</td><td>" + $temp[2].trim() + "</td></tr>" } } else { $dirHTML += "<tr><td>" + $temp[0].trim() + "</td><td>" + $temp[1].trim() + "</td><td>" + $temp[2].trim() + "</td></tr>" } } $dirHTML += '</tbody> </table> </td> </tr>' } $dirHTML += ' </tbody> </table> </div> </div> </div> <div class="filler"></div>' return $dirHTML } function dibujarContenedor($directorios, $elem) { #Como en todos los casos es necesario realizar la impresion de la misma estructura y lo #único que cambia es la finalización del contenedor creo una funcion interna para generar #la cadena que se debe insertar en el fichero HTML. #El parámetro de entrada es por referencia para evitar desbordamientos de memoria en las #llamadas recursivas de la función padre. function dibujarDirectorio([ref] $directorio) { $dirHTML = ' <div class="' if ($directorio.value.nivel -eq 0) { $dirHTML += 'he0_expanded' } else { $dirHTML += 'he' + $directorio.value.nivel } $dirHTML += '"><span class="sectionTitle">Directorio o Fichero ' + $directorio.value.Folder.FullName + '</span></div> <div class="container"><div class="he' + ($directorio.value.nivel + 1) + '"><span class="sectionTitle">Lista de Control de Acceso</span></div> <div class="container"> <div class="heACL"> <table class="info3" cellpadding="0" cellspacing="0"> <thead> <tr><th><b>Usuario</b></th></tr> <tr><th><b>Permisos</b></th></tr> </thead> <tbody>' foreach ($itemACL in $directorio.value.ACL) { $dirHTML += '<tr><td>' + $itemACL.Owner + '</td> <td>' + $itemACL.AccessToString + '</td></tr>' } $dirHTML += ' </tbody> </table> </div> </div> </div>' return $dirHTML } if ($debug) { #El caso base de la recursión es en el que se alcanza el mayor número de niveles permitidos Write-Host "Directorio: " $directorios[$elem].Folder Write-Host "Indice: " $elem Write-Host "Nivel Actual: " $directorios[$elem].Nivel Write-Host "Nivel Siguiente: " $directorios[$elem + 1].Nivel Write-Host "=================================================================================================================" } '<div class="container">' | Add-Content $informe if ($elem -eq $directorios.count) { dibujarDirectorio ([ref]$directorios[$elem]) + '</div><div class="filler"></div>' | Add-Content $informe } else { (dibujarDirectorio ([ref]$directorios[$elem])) | Add-Content $informe if (($directorios[$elem].Nivel -eq $nivelesPermitidos) -or ($directorios[$elem].nivel -ge $directorios[$elem + 1].nivel)) { dibujarDirectorio ([ref]$directorios[$elem]) + '</div><div class="filler"></div>' | Add-Content $informe } elseif ($directorios[$elem].nivel -lt $directorios[$elem + 1].nivel) { $elem = dibujarContenedor $directorios ($elem + 1) '</div><div class="filler"></div>' | Add-Content $informe } } return $elem + 1 } #endregion if (Test-Path $informe) { Remove-item $informe } #Para normalizar el path compruebo si el último caracter de la ruta suministrada es el separador de directorio if ($path.Substring($path.Length - 1,1) -eq "\") { $path = $path.Substring(0,$path.Length - 1) } #region Cabecera, el estilo y las funciones javascript necesarias para el informe html @" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-16" /> <title>Lista de control de acceso para $path en $equipo</title> <!-- Styles --> <style type="text/css"> body{ background-color:#FFFFFF; border:1px solid #666666; color:#000000; font-size:68%; font-family:MS Shell Dlg; margin:0px 0px 10px 0px; } table{ font-size:100%; table-layout:fixed; } .title{ background:#FFFFFF; border:none; color:#333333; display:block; height:24px; margin:0px 0px 2px 0px; padding-top:4px; padding-bottom:2px; position:relative; table-layout:fixed; z-index:5; } .filler{ background:transparent; border:none; color:#FFFFFF; display:block; font:100% MS Shell Dlg; line-height:8px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top:4px; position:relative; } .container{ display:block; position:relative; } .he0{ background-color:#FEF7D6; border:1px solid #BBBBBB; color:#3333CC; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:0px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; } .heACL { background-color:#ECFFD7; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:90px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he1{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; } .he2{ background-color:#C0D2DE; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:20px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; } .he3{ background-color:#D9E3EA; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:30px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he4{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:40px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he5{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:50px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he6{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he7{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:60px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he8{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:65px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he9{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:70px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he10{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:75px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .he11{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-bottom:-1px; margin-left:80px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; } .info4 { border-width: thin; border-style: solid; border-color: black; width: 100%; } .info, .info3, .info4, .disalign{ line-height:1.6em; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; } #dtstamp{ color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; text-align:left; width:30%; } #gposummary { display:block; } </style> </head> <body> <table class="title" cellpadding="0" cellspacing="0"> <tr><td colspan="2" class="gponame">Lista de control de acceso para $path en la m&aacute;quina $equipo</td></tr> <tr> <td id="dtstamp">Datos recopilados en: $(Get-Date)</td> <td><div id="objshowhide"></div></td> </tr> </table> <div class="filler"></div> "@ | Set-Content $informe #endregion #region Recopilación de información $colFicheros = Get-ChildItem -path $UNCPath -Filter *. -Recurse -force -Verbose | Sort-Object FullName $colACLs = @() #Comenzamos haciendo un recorrido del contenido del directorio indicado por el usuario foreach($fichero in $colFicheros) { #Para controlar el nivel del arbol en el que me encuentro es necesario contar el número de #separadores que contiene la ruta del fichero o directorio. Sin embargo para que la cuenta #resulte correcta es necesario eliminar previamente la ruta suministrada por el usuario. #Una vez eliminada el padre, el resto del nombre completo del fichero será la cadena utilizada #para realizar la cuenta del nivel. #Es necesario utilizar un objeto REGEX para obtener TODAS las ocurrencias del separador de directorios $coincidencias = (([regex]"\\").matches($fichero.FullName.substring($path.length, $fichero.FullName.length - $path.length))).count if ($nivel -ne 0 -and ($coincidencias - 1) -gt $nivel) { continue } if ($debug) { Write-Host $fichero.FullName "->" $fichero.Mode } if ($fichero.Mode -notlike "d*") { continue } $myobj = "" | Select-Object Folder,ACL,Nivel $myobj.Folder = $fichero $myobj.ACL = Get-Acl $fichero.FullName $myobj.Nivel = $coincidencias - 1 $colACLs += $myobj } #endregion #region Generación del informe '<div class="gposummary">' | Add-Content $informe $temp = "" for ($i = 0; $i -lt $colACLs.count; $i++) { #$i = dibujarContenedor $colACLs $i try { $temp += dibujarDirectorio ([ref] $colACLs[$i]) } catch { Write-Error dibujarDirectorio ([ref] $colACLs[$i]) } } $temp + '</div></body></html>' | Add-Content $informe #endregion
PowerShellCorpus/GithubGist/nlinker_4249045_raw_a4f9b47db4b5b89fa02c117c9a65a9a1f8cddf1a_C_%5CVbox%5Crabbits-headless.ps1
nlinker_4249045_raw_a4f9b47db4b5b89fa02c117c9a65a9a1f8cddf1a_C_%5CVbox%5Crabbits-headless.ps1
# make sure this mode is enabled under administrator: Set-ExecutionPolicy RemoteSigned # use a batch file like this: # C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe C:\Vbox\rabbits-headless.ps1 $items = @( 'vagrant-rabbitmq-cluster_1351840619', 'vagrant-rabbitmq-cluster_1351840685', 'vagrant-rabbitmq-cluster_1351840745', 'vagrant-rabbitmq-cluster_1351840804' ) Foreach ($item in $items) { $p = '-s ' + $item start-process 'C:\ProgramsX\Oracle\VirtualBox\VBoxHeadless.exe' $p -WindowStyle Hidden } write-host "All systems go" -foregroundcolor "magenta" -backgroundcolor "blue"
PowerShellCorpus/GithubGist/abombss_4489558_raw_d20fc212e42c5763b8799ecf9221aa0a62e6c8ac_Install-AppFabricCache.ps1
abombss_4489558_raw_d20fc212e42c5763b8799ecf9221aa0a62e6c8ac_Install-AppFabricCache.ps1
function Uninstall-AppFabricCacheNode { #TODO: Should try and remove the configuration stuff gwmi win32_product -filter "Name LIKE 'AppFabric%'" |% { $key="IdentifyingNumber=`"$($_.IdentifyingNumber)`",Name=`"$($_.Name)`",version=`"$($_.Version)`""; ([wmi]"Win32_Product.$key").uninstall() } } function Reset-AppFabricCacheDatabase { param( [Parameter(Mandatory=$true)] [string]$ConnectionString ) $con = new-object System.Data.SqlClient.SqlConnection try { $con.ConnectionString = $ConnectionString Write-Verbose "Connection to $ConnectionString" $con.Open() $cmd = $con.CreateCommand() $cmd.CommandText="SELECT DB_NAME() AS [Database]" $dbName = $cmd.ExecuteScalar() $cmd.Dispose() Write-Verbose "Found database $dbName" $cmd = $con.CreateCommand() $cmd.CommandText = @" USE master; ALTER DATABASE [$dbName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [$dbName]; "@ Write-Verbose "Dropping database $dbName" $cmd.ExecuteNonQuery() $cmd.Dispose() $cmd = $con.CreateCommand() $cmd.CommandText = "CREATE DATABASE [$dbName]; ALTER DATABASE [$dbName] SET MULTI_USER" Write-Verbose "Creating database $dbName" $cmd.ExecuteNonQuery() $cmd.Dispose() $cmd = $null } catch { Write-Error $error[0] } finally { if ($cmd) { $cmd.Dispose() } $con.Close() } } function Add-AccountPrivilege { param([string]$Account, [string]$Privilege="SeServiceLogonRight") try { [MyLsaWrapper.LsaWrapperCaller] } catch { # Special Powershell Command to Grant the service account LogOn as Service Rights Add-Type @' using System; using System.Collections.Generic; using System.Text; namespace MyLsaWrapper { using System.Runtime.InteropServices; using System.Security; using System.Management; using System.Runtime.CompilerServices; using System.ComponentModel; using LSA_HANDLE = IntPtr; [StructLayout(LayoutKind.Sequential)] struct LSA_OBJECT_ATTRIBUTES { internal int Length; internal IntPtr RootDirectory; internal IntPtr ObjectName; internal int Attributes; internal IntPtr SecurityDescriptor; internal IntPtr SecurityQualityOfService; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct LSA_UNICODE_STRING { internal ushort Length; internal ushort MaximumLength; [MarshalAs(UnmanagedType.LPWStr)] internal string Buffer; } sealed class Win32Sec { [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute] internal static extern uint LsaOpenPolicy( LSA_UNICODE_STRING[] SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, int AccessMask, out IntPtr PolicyHandle ); [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute] internal static extern uint LsaAddAccountRights( LSA_HANDLE PolicyHandle, IntPtr pSID, LSA_UNICODE_STRING[] UserRights, int CountOfRights ); [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute] internal static extern int LsaLookupNames2( LSA_HANDLE PolicyHandle, uint Flags, uint Count, LSA_UNICODE_STRING[] Names, ref IntPtr ReferencedDomains, ref IntPtr Sids ); [DllImport("advapi32")] internal static extern int LsaNtStatusToWinError(int NTSTATUS); [DllImport("advapi32")] internal static extern int LsaClose(IntPtr PolicyHandle); [DllImport("advapi32")] internal static extern int LsaFreeMemory(IntPtr Buffer); } /// <summary> /// This class is used to grant "Log on as a service", "Log on as a batchjob", "Log on localy" etc. /// to a user. /// </summary> public sealed class LsaWrapper : IDisposable { [StructLayout(LayoutKind.Sequential)] struct LSA_TRUST_INFORMATION { internal LSA_UNICODE_STRING Name; internal IntPtr Sid; } [StructLayout(LayoutKind.Sequential)] struct LSA_TRANSLATED_SID2 { internal SidNameUse Use; internal IntPtr Sid; internal int DomainIndex; uint Flags; } [StructLayout(LayoutKind.Sequential)] struct LSA_REFERENCED_DOMAIN_LIST { internal uint Entries; internal LSA_TRUST_INFORMATION Domains; } enum SidNameUse : int { User = 1, Group = 2, Domain = 3, Alias = 4, KnownGroup = 5, DeletedAccount = 6, Invalid = 7, Unknown = 8, Computer = 9 } enum Access : int { POLICY_READ = 0x20006, POLICY_ALL_ACCESS = 0x00F0FFF, POLICY_EXECUTE = 0X20801, POLICY_WRITE = 0X207F8 } const uint STATUS_ACCESS_DENIED = 0xc0000022; const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a; const uint STATUS_NO_MEMORY = 0xc0000017; IntPtr lsaHandle; public LsaWrapper() : this(null) { } // // local system if systemName is null public LsaWrapper(string systemName) { LSA_OBJECT_ATTRIBUTES lsaAttr; lsaAttr.RootDirectory = IntPtr.Zero; lsaAttr.ObjectName = IntPtr.Zero; lsaAttr.Attributes = 0; lsaAttr.SecurityDescriptor = IntPtr.Zero; lsaAttr.SecurityQualityOfService = IntPtr.Zero; lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES)); lsaHandle = IntPtr.Zero; LSA_UNICODE_STRING[] system = null; if (systemName != null) { system = new LSA_UNICODE_STRING[1]; system[0] = InitLsaString(systemName); } uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr, (int)Access.POLICY_ALL_ACCESS, out lsaHandle); if (ret == 0) return; if (ret == STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY)) { throw new OutOfMemoryException(); } throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret)); } public void AddPrivileges(string account, string privilege) { IntPtr pSid = GetSIDInformation(account); LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1]; privileges[0] = InitLsaString(privilege); uint ret = Win32Sec.LsaAddAccountRights(lsaHandle, pSid, privileges, 1); if (ret == 0) return; if (ret == STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY)) { throw new OutOfMemoryException(); } throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret)); } public void Dispose() { if (lsaHandle != IntPtr.Zero) { Win32Sec.LsaClose(lsaHandle); lsaHandle = IntPtr.Zero; } GC.SuppressFinalize(this); } ~LsaWrapper() { Dispose(); } // helper functions IntPtr GetSIDInformation(string account) { LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1]; LSA_TRANSLATED_SID2 lts; IntPtr tsids = IntPtr.Zero; IntPtr tdom = IntPtr.Zero; names[0] = InitLsaString(account); lts.Sid = IntPtr.Zero; Console.WriteLine("String account: {0}", names[0].Length); int ret = Win32Sec.LsaLookupNames2(lsaHandle, 0, 1, names, ref tdom, ref tsids); if (ret != 0) throw new Win32Exception(Win32Sec.LsaNtStatusToWinError(ret)); lts = (LSA_TRANSLATED_SID2)Marshal.PtrToStructure(tsids, typeof(LSA_TRANSLATED_SID2)); Win32Sec.LsaFreeMemory(tsids); Win32Sec.LsaFreeMemory(tdom); return lts.Sid; } static LSA_UNICODE_STRING InitLsaString(string s) { // Unicode strings max. 32KB if (s.Length > 0x7ffe) throw new ArgumentException("String too long"); LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING(); lus.Buffer = s; lus.Length = (ushort)(s.Length * sizeof(char)); lus.MaximumLength = (ushort)(lus.Length + sizeof(char)); return lus; } } public class LsaWrapperCaller { public static void AddPrivileges(string account, string privilege) { using (LsaWrapper lsaWrapper = new LsaWrapper()) { lsaWrapper.AddPrivileges(account, privilege); } } } } '@ #Swallow the exception, because it should be missing type and we just added it } # Run the command to grant the account login as service rights [MyLsaWrapper.LsaWrapperCaller]::AddPrivileges($Account, $Privilege) } function Install-AppFabricCacheNode { param( [string]$SetupFile=$null, [string]$LogFile=".\appfabricsetup.txt", [string]$WorkingDirectory=".", [string]$Provider=$null, [string]$ConnectionString=$null, [string]$ServiceAccount, [string]$Password, [int]$CachePort=22233, [int]$ClusterPort=22234, [int]$ArbitrationPort=22235, [int]$ReplicationPort=22236, [switch]$NewCacheCluster=$false ); $CurrentHost = ([System.Net.Dns]::GetHostByName(($env:computerName))).HostName $AbsoluteWorkingDir = Resolve-Path $WorkingDirectory if (![System.IO.Path]::IsPathRooted($SetupFile)) { $SetupFile = Resolve-Path $SetupFile } if (![System.IO.Path]::IsPathRooted($LogFile)) { $LogFile = Join-Path (Resolve-Path (Split-Path $LogFile -Parent)) (Split-Path $LogFile -Leaf) } $installArgs = @( "/install" "cachingservice,cacheclient,cacheadmin" "/l:`"$LogFile`"" ) $installParameters = @{ FilePath=$SetupFile ArgumentList=$installArgs Wait=$true WorkingDirectory=$AbsoluteWorkingDir Verb='runas' } Write-Verbose "Silently starting appfabric installation" Start-Process @installParameters Write-Verbose "Changing credentials of AppFabricCachingService to service account credentials" & (Join-Path (Join-Path $Env:WinDir system32) sc.exe) @( 'config' 'AppFabricCachingService' 'obj=' "`"$ServiceAccount`"" 'password=' "`"$Password`"" ) Write-Verbose "Adding Log On as Service right for Service Account" try { Add-AccountPrivilege -Account $ServiceAccount -Privilege "SeServiceLogonRight" } catch { Add-AccountPrivilege -Account $ServiceAccount -Privilege "SeServiceLogonRight" } try { Add-AccountPrivilege -Account $ServiceAccount -Privilege "SeBatchLogonRight" } catch{ Add-AccountPrivilege -Account $ServiceAccount -Privilege "SeBatchLogonRight" } Write-Verbose "Adding Scheduled Task to Start-CacheHost at machine boot" # In 2012 this becomes easier because there is a cmdlet for schedule task administration $scheduledTaskArgs = @( '/Create', '/TN',"AppFabricCache-StartCacheHost" '/SC','ONSTART', '/RL','Highest', '/RU',"`"$ServiceAccount`"", '/RP',"`"$Password`"", '/DELAY',"0000:30" '/F', '/TR',"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -NoProfile -NoLogo -Command {import-module DistributedCacheAdministration; use-cachecluster; start-cachehost -hostname $CurrentHost -cacheport $CachePort;}" ) & (Join-Path (Join-Path $Env:WinDir system32) schtasks.exe) $scheduledTaskArgs Write-Verbose "Opening Firewall for caching ports" # Open the firewall ports, run on each node in the cluster # OK if all of these don't run because some may already be open, look into a better way to verify the ports are open netsh advfirewall firewall set rule group="Appfabric Server: AppFabric Caching Service" new enable=Yes netsh advfirewall firewall set rule name="Remote Service Management (RPC)" profile=domain new enable=Yes netsh advfirewall firewall set rule name="Remote Service Management (RPC-EPMAP)" profile=domain new enable=Yes netsh advfirewall firewall set rule name="Remote Service Management (NP-In)" profile=domain new enable=Yes # Hack, manually add the appfab powershell module path, # look into registery settings or something better to get the location of the module path # or see if wmi will work to get the new PSModulePath value and then we can splice it into the current PSModulePath # $Env:PSModulePath += ";c:\Program Files\AppFabric 1.1 for Windows Server\PowershellModules" Import-Module DistributedCacheAdministration Import-Module DistributedCacheConfiguration if ($NewCacheCluster) { Write-Verbose "Creating a new cache cluster" # TODO: Parameterize this command better New-CacheCluster -Provider $Provider -ConnectionString $ConnectionString -Size Small } Use-CacheCluster -Provider $Provider -ConnectionString $ConnectionString Write-Verbose "Registering cache host" Register-CacheHost -HostName $CurrentHost -Provider $Provider -ConnectionString $ConnectionString -Account $ServiceAccount -CachePort $CachePort -ClusterPort $ClusterPort -ArbitrationPort $ArbitrationPort -ReplicationPort $ReplicationPort Write-Verbose "Adding the cache host" Add-CacheHost -Provider $Provider -ConnectionString $ConnectionString -Account $ServiceAccount Add-CacheAdmin -Provider $Provider -ConnectionString $ConnectionString Set-CacheHostConfig -IsLeadHost $true -HostName $CurrentHost -CachePort $CachePort Set-CacheConnectionString -Provider $Provider -ConnectionString $ConnectionString if ($NewCacheCluster) { Write-Verbose "Starting cache cluster" Start-CacheCluster } else { Write-Verbose "Starting cache host" Start-CacheHost -hostname $CurrentHost -cacheport $CachePort } }
PowerShellCorpus/GithubGist/StephenLujan_5358305_raw_c15aa36b0fb61f730523c06dbcf01b6489c95822_fixSharePointNavigation.ps1
StephenLujan_5358305_raw_c15aa36b0fb61f730523c06dbcf01b6489c95822_fixSharePointNavigation.ps1
function _fixLink([Microsoft.SharePoint.Navigation.SPNavigationNode]$link, [String]$bad, [String]$good) { write-verbose ('checking link "' + $link.title + '" (' + $link.url + ')') #$link | Get-Member $url = $link.url -replace $bad, $good if ([string]::Compare($url, $link.url, $True) -ne 0) { write-output("fixing url ("+$link.url+") to ("+$url+")") $link.url = $url $link.update() } } function fixLinks { <# .SYNOPSIS fixes broken links .DESCRIPTION Searches through all navigation links in the Quick launch menu, and corrects all urls based on string replacement. .EXAMPLE fixLinks (Get-SPweb "http://mdsp01/clients/") "/All Client Sites/" "/clients/" -verbose .PARAMETER SPSite The sharepoint site to fix. .PARAMETER bad the bad string that needs to be replaced from the url .PARAMETER good the good string that needs to be replace the bad one in the url #>[CmdletBinding()] param ( [Parameter(Position=1, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage='What is the address of the sharepoint site collection/ site/ subsite you would like to fix?')] [Alias('site')] [Microsoft.SharePoint.SPWeb]$SPSite, [Parameter(Position=2, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage='What is the old string that needs to be replaced from link urls on the site?')] [Alias('bad')] [String]$badUrlString, [Parameter(Position=3, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage='What is the new string to correct link urls on the site?')] [Alias('good')] [String]$goodUrlString ) BEGIN {} PROCESS { $SPPubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($SPSite); foreach($node in $SPPubWeb.Navigation.CurrentNavigationNodes) { foreach($link in $node) { _fixLink $link $badUrlString $goodUrlString foreach($childLink in $link.children) { _fixLink $childLink $badUrlString $goodUrlString } } } $SPPubWeb.update() } END{} } function fixNav { <# .SYNOPSIS Enforces a navigation policy on the input site .DESCRIPTION Global and local navigation for this site and all subsites will be fixed to match desired rules set in this function. .EXAMPLE fixNav (Get-SPweb "http://mdsp01/clients") .EXAMPLE fixNav (Get-SPweb "http://mdsp01/clients") -verbose .EXAMPLE fixNav (Get-SPweb "http://mdsp01/clients") "/All Client Sites/" "/clients/" .PARAMETER SPSite The sharepoint site to fix. .PARAMETER verbose whether to pring before and after information etc. #>[CmdletBinding()] param ( [Parameter(Position=1, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage='What is the address of the sharepoint site collection/ site/ subsite you would like to fix?')] [Alias('site')] [Microsoft.SharePoint.SPWeb]$SPSite, [Parameter(Position=2, Mandatory=$false, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage='What is the old string that needs to be replaced from link urls on the site?')] [Alias('bad')] [String]$badUrlString = $null, [Parameter(Position=3, Mandatory=$false, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage='What is the new string to correct link urls on the site?')] [Alias('good')] [String]$goodUrlString = "" ) BEGIN { Write-Output("-------------------------------------------------------------------------------"); Write-Output("fixing site: " + $SPSite.title + " at " + $SPSite.url); ## Save AllowUnsafeUpdates setting and set it to allow. $AllowUnsafeUpdatesStatus = $SPSite.AllowUnsafeUpdates; $SPSite.AllowUnsafeUpdates = $true; } PROCESS { ## Get a PublishingWeb object for the current web $SPPubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($SPSite); Write-Verbose("Navigation Before: " + [string] ($SPPubWeb.Navigation | select *)); ## fix links if received if ($badUrlString) { fixLinks $SPSite $badUrlString $goodUrlString; } else { Write-Verbose("Skipping link url corrections."); } ## UnComment the setting you will use: ## Global settings $SPPubWeb.Navigation.InheritGlobal = $true # $SPPubWeb.Navigation.InheritGlobal = $false # $SPPubWeb.Navigation.GlobalIncludeSubSites = $true $SPPubWeb.Navigation.GlobalIncludeSubSites = $false # $SPPubWeb.Navigation.GlobalIncludePages = $true $SPPubWeb.Navigation.GlobalIncludePages = $false $SPPubWeb.Navigation.GlobalDynamicChildLimit = 10 ## Current settings ## See combination of the two below $SPPubWeb.Navigation.InheritCurrent = $false $SPPubWeb.Navigation.ShowSiblings = $false $SPPubWeb.Navigation.CurrentIncludeSubSites = $true $SPPubWeb.Navigation.CurrentIncludePages = $true $SPPubWeb.Navigation.CurrentDynamicChildLimit = 20 ## Sorting $SPPubWeb.Navigation.OrderingMethod = "Automatic" # $SPPubWeb.Navigation.OrderingMethod = "Manual" # $SPPubWeb.Navigation.OrderingMethod = "ManualWithAutomaticPageSorting” $SPPubWeb.Navigation.AutomaticSortingMethod = "Title" # $SPPubWeb.Navigation.AutomaticSortingMethod = "CreatedDate" # $SPPubWeb.Navigation.AutomaticSortingMethod = "LastModifiedDate" $SPPubWeb.Navigation.SortAscending = $true # $SPPubWeb.Navigation.SortAscending = $false $SPPubWeb.Update() Write-Verbose("Navigation After: " + [string] ($SPPubWeb.Navigation | select *)) ## recurse through subsites foreach ($SPWeb in $SPSite.Webs) { ## check that this is not the root web or suffer infinite recursion if (!$SPWeb.IsRootWeb) { fixNav $SPWeb $badUrlString $goodUrlString } } } END { $SPSite.AllowUnsafeUpdates = $AllowUnsafeUpdatesStatus $SPSite.Dispose() } }
PowerShellCorpus/GithubGist/gravejester_9599c63ee03a4c681f19_raw_3a7a6514f8d592c1a1a301c01af139aab5bceb7c_Measure-ScriptBlock.ps1
gravejester_9599c63ee03a4c681f19_raw_3a7a6514f8d592c1a1a301c01af139aab5bceb7c_Measure-ScriptBlock.ps1
function Measure-ScriptBlock { <# .SYNOPSIS Measure time, memory consumption and CPU time for a block of code to execute. .DESCRIPTION Measure time, memory consumption and CPU time for a block of code to execute. This function is using Measure-Command internally, but is also trying to record how much memory and CPU time the code uses during execution. .EXAMPLE Measure-ScriptBlock -ScriptBlock {Get-ChildItem -Recurse} -Iteration 10 -TimeUnit 'Milliseconds' -SizeUnit 'KB' Run the code 10 times, formatting the mean values in Milliseconds and KB. .EXAMPLE Measure-ScriptBlock -ScriptBlock {Get-ChildItem -Recurse} -Iteration 10 -TimeUnit 'Milliseconds' -SizeUnit 'KB' -CalculateMeans:$false Run the same measurements are the above example, except skip calculating the mean value for the measurements taken. .EXAMPLE Measure-ScriptBlock -ScriptBlock $codeArray -Iteration 10 | Format-Table Run an array of script blocks 10 times, formatting the output in a table. .OUTPUTS System.Management.Automation.PSCustomObject .NOTES Author: Øyvind Kallstad Date: 28.10.2014 Version: 1.0 #> [CmdletBinding()] param ( # Code to measure [Parameter(Position = 0, Mandatory = $true)] [ValidateNotNullOrEmpty()] [ScriptBlock[]] $ScriptBlock, # Set how many times you want to execute each ScriptBlock [Parameter()] [int32] $Iterations = 1, # Pause, in milliseconds, between each iteration [Parameter()] [int32] $Pause = 600, # Use this switch to control whether the mean values of each iteration should be calculated or not [Parameter()] [switch] $CalculateMeans = $true, # Customize the unit used for timings. Valid values are 'Hours','Minutes','Seconds' and 'Milliseconds'. [Parameter()] [ValidateSet('Hours','Minutes','Seconds','Milliseconds')] [string] $TimeUnit = 'Seconds', # Customize the unit of size. Valid values are 'KB','MB','GB' and 'TB'. [Parameter()] [ValidateSet('KB','MB','GB','TB')] [string] $SizeUnit = 'MB' ) # initializing our counters - used by Write-Progress $arrayLength = $ScriptBlock.Count $totalCount = 0 $arrayCount = 0 # perform garbage collecting [gc]::Collect() [gc]::WaitForPendingFinalizers() [gc]::Collect() Start-Sleep -Seconds 1 foreach ($script in $ScriptBlock) { $arrayCount++ for ($i = 1; $i -le $Iterations; $i++) { # write progress bar $totalCount++ Write-Progress -Activity 'Measuring' -Status "Executing ScriptBlock $($arrayCount)" -CurrentOperation "Iteration $($i)" -PercentComplete (($totalCount/($arrayLength*$iterations))*100) # perform garbage collecting [gc]::Collect() [gc]::WaitForPendingFinalizers() [gc]::Collect() # get current memory usage for current process $memBefore = [System.Diagnostics.Process]::GetCurrentProcess().PrivateMemorySize64 # get current processor time for current process $cpuTimeBefore = [System.Diagnostics.Process]::GetCurrentProcess().TotalProcessorTime # run code $ttr = Measure-Command { $result = Invoke-Command -ScriptBlock $script } | Select-Object -ExpandProperty "Total$($TimeUnit)" $ttrArray += ,($ttr) # get current processor time for current process $cpuTimeAfter = [System.Diagnostics.Process]::GetCurrentProcess().TotalProcessorTime # get current memory usage for current process $memAfter = [System.Diagnostics.Process]::GetCurrentProcess().PrivateMemorySize64 # do calculations $cpuTime = ($cpuTimeAfter | Select-Object -ExpandProperty "Total$($TimeUnit)") - ($cpuTimeBefore | Select-Object -ExpandProperty "Total$($TimeUnit)") $cpuTimeArray += ,($cpuTime) $memDifference = ($memAfter/"1$SizeUnit") - ($memBefore/"1$SizeUnit") if ($memDifference -lt 0) {$memDifference = 0} # just making sure we don't get a negative value $memDifferenceArray += ,($memDifference) if (-not($CalculateMeans)) { # if we don't want the calculated means we can # write the output to the pipeline after each iteration Write-Output ([PSCustomObject] [Ordered] @{ 'ScriptBlock' = $script 'Result' = $result 'Iteration' = $i "Memory ($($SizeUnit))" = ('{0:N0}' -f $memDifference) "Processor Time ($($TimeUnit))" = ('{0:N2}' -f $cpuTime) "Time To Run ($($TimeUnit))" = ('{0:N2}' -f $ttr) }) } # a small pause before next iteration Start-Sleep -Milliseconds $Pause } # if we want the calculated means of our measurements, # we need to wait until all iterations are complete before # writing the output to the pipeline if ($CalculateMeans) { # create output object Write-Output ([PSCustomObject] [Ordered] @{ 'ScriptBlock' = $script 'Result' = $result 'Iterations' = $Iterations "Memory ($($SizeUnit))" = ('{0:N0}' -f ($memDifferenceArray | Measure-Object -Average | Select-Object -ExpandProperty Average)) "Processor Time ($($TimeUnit))" = ('{0:N2}' -f ($cpuTimeArray | Measure-Object -Average | Select-Object -ExpandProperty Average)) "Time To Run ($($TimeUnit))" = ('{0:N2}' -f ($ttrArray | Measure-Object -Average | Select-Object -ExpandProperty Average)) }) # reset the arrays Remove-Variable -Name memDifferenceArray,cpuTimeArray,ttrArray -ErrorAction SilentlyContinue } } # perform garbage collecting [gc]::Collect() [gc]::WaitForPendingFinalizers() [gc]::Collect() }
PowerShellCorpus/GithubGist/sneal_62c28e6383b89e81f697_raw_1e29b69a13ff494485ceafd4370a0770cfe21f34_gistfile1.ps1
sneal_62c28e6383b89e81f697_raw_1e29b69a13ff494485ceafd4370a0770cfe21f34_gistfile1.ps1
$is_64bit = [IntPtr]::size -eq 8 $ssh_install_dir = "$env:ProgramFiles\OpenSSH" $ssh_installer = "$env:TEMP\setupssh-6.4p1-1.exe" $ssh_download_url = "http://www.mls-software.com/files/setupssh-6.4p1-1.exe" if ($is_64bit) { $ssh_installer = "$env:TEMP\setupssh-6.4p1-1(x64).exe" $ssh_download_url = "http://www.mls-software.com/files/setupssh-6.4p1-1(x64).exe" } if (!(Test-Path $ssh_installer)) { Write-Host "Downloading $ssh_download_url" (New-Object System.Net.WebClient).DownloadFile($ssh_download_url, $ssh_installer) } if (!(Test-Path "$ssh_install_dir\bin\ssh.exe")) { Write-Host "Installing OpenSSH" Start-Process $ssh_installer "/S /port=22" -NoNewWindow -Wait } Stop-Service "OpenSSHd" -Force Write-Host "Configuring necessary privileges for Administrator account to run SSH service" $edit_rights_path = "$ssh_install_dir\bin\editrights.exe" Start-Process $edit_rights_path "-a SeServiceLogonRight -u Administrator" -NoNewWindow -Wait Write-Host "Setting SSH home directories" (Get-Content "$ssh_install_dir\etc\passwd") | Foreach-Object { $_ -replace '/home/(\w+)', '/cygdrive/c/Users/$1' } | Set-Content "$ssh_install_dir\etc\passwd" Write-Host "Setting OpenSSH to be non-strict" $sshd_config = Get-Content "$ssh_install_dir\etc\sshd_config" $sshd_config = $sshd_config -replace 'StrictModes yes', 'StrictModes no' $sshd_config = $sshd_config -replace '#PubkeyAuthentication yes', 'PubkeyAuthentication yes' $sshd_config = $sshd_config -replace '#PermitUserEnvironment no', 'PermitUserEnvironment yes' $sshd_config = $sshd_config -replace 'Banner /etc/banner.txt', '#Banner /etc/banner.txt' Set-Content "$ssh_install_dir\etc\sshd_config" $sshd_config Write-Host "Setting SSH temp directory to Windows temp" Remove-Item -Recurse -Force -ErrorAction SilentlyContinue "$ssh_install_dir\tmp" C:\Program` Files\OpenSSH\bin\junction.exe /accepteula "$ssh_install_dir\tmp" "C:\Windows\Temp" Write-Host "Setting SSH environment" New-Item -ItemType Directory -Force -Path "C:\Users\Administrator\.ssh" $sshenv = "TEMP=C:\Windows\Temp" if ($is_64bit) { $env_vars = "ProgramFiles(x86)=C:\Program Files (x86)", ` "ProgramW6432=C:\Program Files", ` "CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files", ` "CommonProgramW6432=C:\Program Files\Common Files" $sshenv = $sshenv + "`r`n" + ($env_vars -join "`r`n") } Set-Content C:\Users\Administrator\.ssh\environment $sshenv Write-Host "Setting OpenSSHd service account to administrator" $service = gwmi win32_service -computer . -filter "name='opensshd'" $service.change($null,$null,$null,$null,$null,$null,".\Administrator","password")
PowerShellCorpus/GithubGist/n3wjack_8519114_raw_016ffc0d8b36259d31f5cc0cb2902c19b2c8c320__script-template.ps1
n3wjack_8519114_raw_016ffc0d8b36259d31f5cc0cb2902c19b2c8c320__script-template.ps1
<# .SYNOPSIS <script synopsys> .DESCRIPTION <full description> .PARAMETER Foo <foo description> .PARAMETER Bar <bar description> .EXAMPLE <example> .EXAMPLE <another example> For more possible values see http://technet.microsoft.com/en-us/library/dd819489.aspx #> param ( [Switch] $SwitchParam, [DateTime] $StartDate, [string][Parameter(Mandatory)] $MandatoryParam, [string] $ParamWithDefault="foo", [string] [ValidateSet("apple","banana")] $ParamWithSetOptions )
PowerShellCorpus/GithubGist/belotn_6867678_raw_a8680e2eb55d683bdb0ed4ba4b4f68c4e20df4ee_get-requiredGPOgFlag1L.ps1
belotn_6867678_raw_a8680e2eb55d683bdb0ed4ba4b4f68c4e20df4ee_get-requiredGPOgFlag1L.ps1
Get-ADOrganizationalUnit -Filter 'OU -like "*Citrix*"' -SearchBase 'dc=fabricam,dc=com' -Properties * |% { $_.gpLink -split ']' } |? { $_ -match '[0,2]$'} |% {(($_ -replace '\[','').split(';')[0]) -replace 'LDAP://',''} |% { get-adobject $_ -properties * } | sort -Unique DisplayName | select DisplayName,flags,@{N='flagsRecommended';E={if([bool]( gci "$($_.gPCFileSysPath)\User") -eq $false){if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){3}else{ 1}}else {if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){ 2}ELSE{ 0}} } }
PowerShellCorpus/GithubGist/kyle-herzog_9536407_raw_15dac36849081ec88ee1e78783f906a4789ff169_Get-VisualStudioInstances.ps1
kyle-herzog_9536407_raw_15dac36849081ec88ee1e78783f906a4789ff169_Get-VisualStudioInstances.ps1
param ( [Parameter(Mandatory=$true)][string] $solutionFullName ) function Register-CSharpCode ([string] $code, $FrameworkVersion="v2.0.50727", [Array]$References) { # # Get an instance of the CSharp code provider # $cp = new-object Microsoft.CSharp.CSharpCodeProvider # # Build up a compiler params object... $framework = Join-Path $env:windir "Microsoft.NET\Framework\$FrameWorkVersion" $refs = New-Object Collections.ArrayList $refs.AddRange( @("${framework}\System.dll", "C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\PublicAssemblies\envdte.dll", "${framework}\system.windows.forms.dll", "${framework}\System.data.dll", "${framework}\System.Drawing.dll", "${framework}\System.Xml.dll")) if ($references.Count -ge 1) { $refs.AddRange($References) } $cpar = New-Object System.CodeDom.Compiler.CompilerParameters $cpar.GenerateInMemory = $true $cpar.GenerateExecutable = $false $cpar.OutputAssembly = "custom" $cpar.ReferencedAssemblies.AddRange($refs) $cr = $cp.CompileAssemblyFromSource($cpar, $code) if ( $cr.Errors.Count) { $codeLines = $code.Split("`n"); foreach ($ce in $cr.Errors) { write-host "Error: $($codeLines[$($ce.Line - 1)])" $ce |out-default } Throw "INVALID DATA: Errors encountered while compiling code" } } $code = @' using System; using System.Collections; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.Win32; namespace PInvoke { public class VisualStudioInstances { [DllImport("ole32.dll")] public static extern int GetRunningObjectTable(int reserved, out UCOMIRunningObjectTable prot); [DllImport("ole32.dll")] public static extern int CreateBindCtx(int reserved, out UCOMIBindCtx ppbc); public static Hashtable GetRunningObjectTable() { Hashtable result = new Hashtable(); int numFetched; UCOMIRunningObjectTable runningObjectTable; UCOMIEnumMoniker monikerEnumerator; UCOMIMoniker[] monikers = new UCOMIMoniker[1]; GetRunningObjectTable(0, out runningObjectTable); runningObjectTable.EnumRunning(out monikerEnumerator); monikerEnumerator.Reset(); while (monikerEnumerator.Next(1, monikers, out numFetched) == 0) { UCOMIBindCtx ctx; CreateBindCtx(0, out ctx); string runningObjectName; monikers[0].GetDisplayName(ctx, null, out runningObjectName); object runningObjectVal; runningObjectTable.GetObject( monikers[0], out runningObjectVal); result[ runningObjectName ] = runningObjectVal; } return result; } public static Hashtable GetIDEInstances( bool openSolutionsOnly ) { Hashtable runningIDEInstances = new Hashtable(); Hashtable runningObjects = GetRunningObjectTable(); IDictionaryEnumerator rotEnumerator = runningObjects.GetEnumerator(); while ( rotEnumerator.MoveNext() ) { string candidateName = (string) rotEnumerator.Key; if (!candidateName.StartsWith("!VisualStudio.DTE")) continue; _DTE ide = rotEnumerator.Value as _DTE; if (ide == null) continue; if (openSolutionsOnly) { try { string solutionFile = ide.Solution.FullName; if (solutionFile != String.Empty) { runningIDEInstances[ candidateName ] = ide; } } catch {} } else { runningIDEInstances[ candidateName ] = ide; } } return runningIDEInstances; } public static EnvDTE.DTE GetIDEInstance( string solutionFile ) { Hashtable runningInstances = GetIDEInstances( true ); IDictionaryEnumerator enumerator = runningInstances.GetEnumerator(); while ( enumerator.MoveNext() ) { try { _DTE ide = (_DTE) enumerator.Value; if (ide != null) { if (ide.Solution.FullName == solutionFile) { return (EnvDTE.DTE) ide; } } } catch{} } return null; } } } '@ Add-Type -AssemblyName "EnvDTE" Register-CSharpCode $code $vsInstances = [PInvoke.VisualStudioInstances]::GetIDEInstances($true) $vsInstances.Keys | Foreach-Object ` { $vs = $vsInstances.Item($_) if($vs) { Write-Host "$($vs.Solution.FullName)" } } $vsInstance = [PInvoke.VisualStudioInstances]::GetIDEInstance($solutionFullName) if($vsInstance) { $dte = $vsInstance.DTE $solution = $dte.Solution $solution.Projects | Foreach-Object ` { Write-Host "Project - $($_.Name)" } }
PowerShellCorpus/GithubGist/AmrEldib_e1a12ddee601bd80480c_raw_4a8baf204135e81735ceb55317bc5bff6fa3db90_MirrorHardDrives.ps1
AmrEldib_e1a12ddee601bd80480c_raw_4a8baf204135e81735ceb55317bc5bff6fa3db90_MirrorHardDrives.ps1
Clear-Host # Decleare variable to hold the service name $serviceName = "MSSQL`$SQLEXPRESS" # Where the log file will be stored $logHome = "D:\Amr\Backup\BackupLogs\" # Get timestamp $timeStamp = Get-Date -Format "yyyy-MM-dd HH-mm-ss" # Generate name of log file $logFile = $logHome + "Backup Log " + $timeStamp + ".txt" # Write a starting message "Starting backup at $timestamp" | out-file $logFile -Append -Force # Stop the SQL service if it's running $serviceStatus = Get-SqlServiceStatus ($serviceName) "Service $serviceName is $serviceStatus." | out-file $logFile -Append -Force if ($serviceStatus -eq "Running") { "SQL service is running, stopping it..." | out-file $logFile -Append -Force Stop-SqlService ($serviceName) | out-file $logFile -Append -Force } # Unmount Codebox if it was already mounted $CodeboxMounted = Exists-Drive "M:" if ($CodeboxMounted -eq "True") { "Codebox is mounted. Unmounting Codebox..." | out-file $logFile -Append -Force # Unmount Codebox Unmount-Codebox | out-file $logFile -Append -Force "Codebox is not mounted now." | out-file $logFile -Append -Force } else { "Codebox is not mounted" | out-file $logFile -Append -Force } # Run sync toy Run-SyncToy ("TestBackup") | out-file $logFile -Append -Force # Mount Codebox if it was already mounted if ($CodeboxMounted -eq "True") { "Mounting Codebox..." | out-file $logFile -Append -Force # Mount Codebox Mount-Codebox | out-file $logFile -Append -Force "Codebox is mounted now." | out-file $logFile -Append -Force } # Run the SQL service if it's stopped $serviceStatus = Get-SqlServiceStatus ($serviceName) "Service $serviceName is $serviceStatus." | out-file $logFile -Append -Force if ($serviceStatus -eq "Stopped") { "Starting SQL service..." | out-file $logFile -Append -Force Start-SqlService ($serviceName) | out-file $logFile -Append -Force } # Write end message $finishTime = Get-Date -Format "yyyy-MM-dd HH-mm-ss" "Backup script finished at $finishTime" | out-file $logFile -Append -Force
PowerShellCorpus/GithubGist/aradriel_4953342_raw_53ed86e8bc30f8f5d09ea15909ae928526265f8c_FileOwnerFullAccess.ps1
aradriel_4953342_raw_53ed86e8bc30f8f5d09ea15909ae928526265f8c_FileOwnerFullAccess.ps1
Param($folder) $arr = @() #function Test-FileLock function Test-FileLock { param ( [parameter(Mandatory=$true)] [string]$Path ) $oFile = New-Object System.IO.FileInfo $Path if ((Test-Path -Path $Path) -eq $false){ $false return } try{ $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($oStream){ $oStream.Close() } #file is NOT locked $false } catch{ if (Test-Path -Path $Path -Pathtype container){ #is folder $oDir = New-Object System.IO.DirectoryInfo $Path try{ $dirACL = $oDir.GetAccessControl() $oDir.SetAccessControl($dirACL) #folder NOT locked $false } catch{ #folder locked $true } } else{ #file is locked $true } } } #function fix-file function fix-file{ Param( [Parameter(Mandatory=$true)] [String]$ipath = "" ) Write-Host $ipath try{ if ((Test-FileLock $ipath) -eq $false){ $acl = (Get-Item $ipath).GetAccessControl('Access') $owner = (Get-Item $ipath).GetAccessControl('Owner') $sid = $owner.GetOwner("System.Security.Principal.SecurityIdentifier") $objUser = $sid.Translate( [System.Security.Principal.NTAccount]) $colRights = [System.Security.AccessControl.FileSystemRights]"FullControl" $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None $objType =[System.Security.AccessControl.AccessControlType]::Allow $objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($objUser, $colRights, $InheritanceFlag, $PropagationFlag, $objType) $acl.AddAccessRule($objACE) $acl | set-acl -Path $ipath Write-Host ".....done" } else{ $arr += $_.fullname Write-Host ".....failed|--->filelock" } } catch{ Write-Host("! XS Error !") } } #proc-folder function proc-folder{ Param( [Parameter(Mandatory=$true)] [String]$Pfad = "" ) $Directories = @(Get-ChildItem $Pfad -Recurse -force | Where-Object {$_.PsIsContainer}) $Directories += get-childitem (Split-Path $Pfad) -include (Split-Path $Pfad -Leaf) -force $Data = @() $Directories | foreach { $Files = @(Get-ChildItem -force "$($_.FullName)") $Files | foreach { fix-file($_.FullName) } } } ##functions end proc-folder $folder $arr |foreach { Write-Host("Filelocked -->"+$_) }
PowerShellCorpus/GithubGist/so0k_e96c3dc5a81ef89715f8_raw_562eb25a156c223c6095642c6b25738f90f98e31_Update-Hosts.ps1
so0k_e96c3dc5a81ef89715f8_raw_562eb25a156c223c6095642c6b25738f90f98e31_Update-Hosts.ps1
Param( [Parameter(Mandatory=$true)] [string]$hostName, [Parameter(Mandatory=$true)] [string]$hostIp ) function IsAdministrator { $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity) $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) } # Check to see if we are currently running "as Administrator" if (!(IsAdministrator)) { # We are not running "as Administrator" - so relaunch as administrator [string[]]$argList = @('-NoProfile', '-File', $MyInvocation.MyCommand.Path) $argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"} $argList += $MyInvocation.UnboundArguments Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList return } write "updating hosts file.." $hostsfile = "$env:windir\System32\drivers\etc\hosts" (gc $hostsfile ) -replace "[0-9.]+ $hostName", "$hostIp $hostName" | sc $hostsfile write "done"
PowerShellCorpus/GithubGist/p0w3rsh3ll_03643595d8ac50a7c938_raw_c8f7598d1d7e81f7a20ea06c1cbc38a046fbd18e_Get-FileHash.ps1
p0w3rsh3ll_03643595d8ac50a7c938_raw_c8f7598d1d7e81f7a20ea06c1cbc38a046fbd18e_Get-FileHash.ps1
function Get-FileHash { [CmdletBinding(DefaultParameterSetName = "Path")] param( [Parameter(Mandatory=$true, ParameterSetName="Path", Position = 0)] [System.String[]] $Path, [Parameter(Mandatory=$true, ParameterSetName="LiteralPath", ValueFromPipelineByPropertyName = $true)] [Alias("PSPath")] [System.String[]] $LiteralPath, [Parameter(Mandatory=$true, ParameterSetName="Stream")] [System.IO.Stream] $InputStream, [ValidateSet("SHA1", "SHA256", "SHA384", "SHA512", "MACTripleDES", "MD5", "RIPEMD160")] [System.String] $Algorithm="SHA256" ) begin { # Construct the strongly-typed crypto object $hasher = [System.Security.Cryptography.HashAlgorithm]::Create($Algorithm) } process { if($PSCmdlet.ParameterSetName -eq "Stream") { GetStreamHash -InputStream $InputStream -RelatedPath $null -Hasher $hasher } else { $pathsToProcess = @() if($PSCmdlet.ParameterSetName -eq "LiteralPath") { $pathsToProcess += Resolve-Path -LiteralPath $LiteralPath | Foreach-Object { $_.ProviderPath } } if($PSCmdlet.ParameterSetName -eq "Path") { $pathsToProcess += Resolve-Path $Path | Foreach-Object { $_.ProviderPath } } foreach($filePath in $pathsToProcess) { if(Test-Path -LiteralPath $filePath -PathType Container) { continue } try { # Read the file specified in $FilePath as a Byte array [system.io.stream]$stream = [system.io.file]::OpenRead($filePath) GetStreamHash -InputStream $stream -RelatedPath $filePath -Hasher $hasher } catch [Exception] { $errorMessage = 'FileReadError {0}:{1}' -f $FilePath, $_ Write-Error -Message $errorMessage -Category ReadError -ErrorId "FileReadError" -TargetObject $FilePath return } finally { if($stream) { $stream.Close() } } } } } } function GetStreamHash { param( [System.IO.Stream] $InputStream, [System.String] $RelatedPath, [System.Security.Cryptography.HashAlgorithm] $Hasher) # Compute file-hash using the crypto object [Byte[]] $computedHash = $Hasher.ComputeHash($InputStream) [string] $hash = [BitConverter]::ToString($computedHash) -replace '-','' if ($RelatedPath -eq $null) { $retVal = [PSCustomObject] @{ Algorithm = $Algorithm.ToUpperInvariant() Hash = $hash } $retVal.psobject.TypeNames.Insert(0, "Microsoft.Powershell.Utility.FileHash") $retVal } else { $retVal = [PSCustomObject] @{ Algorithm = $Algorithm.ToUpperInvariant() Hash = $hash Path = $RelatedPath } $retVal.psobject.TypeNames.Insert(0, "Microsoft.Powershell.Utility.FileHash") $retVal } }
PowerShellCorpus/GithubGist/stknohg_711293bbfa69fd2499b3_raw_a191d0922e02a5e5f0d3ce0c53521f877fd13cf8_Calculate-IPAddress.ps1
stknohg_711293bbfa69fd2499b3_raw_a191d0922e02a5e5f0d3ce0c53521f877fd13cf8_Calculate-IPAddress.ps1
<# .SYNOPSIS IPアドレスからサブネットマスク、ネットワークアドレス、ブロードキャストアドレスを計算します。 ipcalcコマンドと同等の機能になりますが、IPV4のみに対応しています。 .DESCRIPTION .EXAMPLE Calculate-IPAddress -CalcType Subnet,Broadcast,Network -Address 192.168.123.45/21 Calculate-IPAddress -CalcType Prefix,Broadcast,Network -Address 192.168.123.45 255.255.254.0 #> Function Calculate-IPAddress() { [OutputType('Collections.Hashtable')] [cmdletbinding()] param( [Parameter(Mandatory=$true, Position=0, HelpMessage='計算対象を選びます。SubnetとPrefixを同時に指定することは出来ません。')] [ValidateSet('Subnet', 'Prefix', 'Network', 'Broadcast', 'Hostname')] $CalcType, [Parameter(Mandatory=$true, Position=1, HelpMessage='IPアドレスを指定します。CalcTypeがSubnetの場合はCIDR形式でサブネットマスク長を指定してください。')] [string]$Address, [Parameter(Mandatory=$false, Position=2, HelpMessage='サブネットマスクを指定します。CalcTypeがPrefixの場合に指定してください。')] [string]$Subnet ) $MSG_SELECT_PREFIX = "サブネットマスクのPrefixを指定してください。" $MSG_DONT_SELECT_PREFIX = "サブネットマスクのPrefixは指定しないでください。" $MSG_INVALID_IP_ADDRESS = "IPアドレスの指定が正しくありません。({0})" $MSG_INVALID_SUBNET_LEN = "サブネットマスクの桁数が正しくありません。({0})" $MSG_INVALID_SUBNETMASK = "サブネットマスクの指定が正しくありません。({0})" $MSG_UNKNOWN_HOSTNAME = "IPアドレス({0})のホスト名が見つかりません。" # IPアドレスの検証 $SubnetLength = 0; $Items = $Address.Split("/") switch( $Items.Count ) { 1 { if( $CalcType -contains 'Subnet' ){ Write-Error $MSG_SELECT_PREFIX return; } } 2 { if( $CalcType -contains 'Prefix' ){ Write-Error $MSG_DONT_SELECT_PREFIX return; } $Address = $Items[0]; if( !( [Int]::TryParse($Items[1], [ref]$null) ) ){ Write-Error ( $MSG_INVALID_SUBNET_LEN -f $Items[1] ); return; } if( $Items[1] -le 0 -or $Items[1] -gt 32 ){ Write-Error ( $MSG_INVALID_SUBNET_LEN -f $Items[1] ); return; } $SubnetLength = $Items[1] } default { Write-Error ( $MSG_INVALID_IP_ADDRESS -F $Address); return; } } $ParsedIPAddress = $null; if( !( [Net.IPAddress]::TryParse($Address, [ref]$ParsedIPAddress) ) ) { Write-Error ( $MSG_INVALID_IP_ADDRESS -F $Address); return; } # IPV4のみサポート if( $ParsedIPAddress.AddressFamily -ne [Net.Sockets.AddressFamily]::InterNetwork ) { Write-Error ( $MSG_INVALID_SUBNETMASK -F $Address); return; } $ParsedIPBytes = $ParsedIPAddress.GetAddressBytes(); Write-Verbose ("IP Address : {0}" -f $ParsedIPAddress) # サブネットマスクの検証 # 真面目にBit計算するのがめんどうだったので全パターン配列にぶっこんでみる # TODO : IPV6に対応させる気が出たら真面目にやる。 $SubnetArray = @( "0.0.0.0" ,"128.0.0.0" ,"192.0.0.0" ,"224.0.0.0" ,"240.0.0.0" ,"248.0.0.0" ,"252.0.0.0" ,"254.0.0.0" ,"255.0.0.0" ,"255.128.0.0" ,"255.192.0.0" ,"255.224.0.0" ,"255.240.0.0" ,"255.248.0.0" ,"255.252.0.0" ,"255.254.0.0" ,"255.255.0.0" ,"255.255.128.0" ,"255.255.192.0" ,"255.255.224.0" ,"255.255.240.0" ,"255.255.248.0" ,"255.255.252.0" ,"255.255.254.0" ,"255.255.255.0" ,"255.255.255.128" ,"255.255.255.192" ,"255.255.255.224" ,"255.255.255.240" ,"255.255.255.248" ,"255.255.255.252" ,"255.255.255.254" ,"255.255.255.255" ) if( $SubnetLength -gt 0 ) { $Subnet = $SubnetArray[$SubnetLength]; } if( [Array]::IndexOf($SubnetArray, $Subnet) -le 0 ){ Write-Error ( $MSG_INVALID_SUBNETMASK -f $Subnet ); return; } $ParsedSubnet = $null; if( !( [Net.IPAddress]::TryParse($Subnet, [ref]$ParsedSubnet) ) ) { Write-Error ( $MSG_INVALID_SUBNETMASK -F $Address); return; } $ParsedSubnetBytes = $ParsedSubnet.GetAddressBytes(); Write-Verbose ("Argument Subnetmask Prefix : {0}" -f $SubnetLength) Write-Verbose ("Subnetmask : {0}" -f $ParsedSubnet) $RetValue = @{} # サブネットマスクの計算 if( $CalcType -contains 'Subnet' ){ $RetValue.Add("SubnetMask", $Subnet); } # Prefixの計算 if( $SubnetLength -eq 0 ){ $SubnetLength = [Array]::IndexOf($SubnetArray, $Subnet); Write-Verbose ("Calculated Subnetmask Prefix : {0}" -f $SubnetLength) } if( $CalcType -contains 'Prefix' ){ $RetValue.Add("Prefix", $SubnetLength); } # ネットワークアドレスの計算 if( $CalcType -contains 'Network' ){ $WorksAddressBytes = New-Object Byte[] 4 for($i = 0; $i -lt $WorksAddressBytes.Length; $i++) { $WorksAddressBytes[$i] = ($ParsedIPBytes[$i] -band $ParsedSubnetBytes[$i]) Write-Verbose ("NetworkAddress {0} octet : {1} & {2} -> {3}" -f ($i + 1), $ParsedIPBytes[$i], $ParsedSubnetBytes[$i], $WorksAddressBytes[$i]) } $RetValue.Add("NetworkAddress", ($WorksAddressBytes -join ".")); } # ブロードキャストアドレスの計算 if( $CalcType -contains 'Broadcast' ){ $BroadcastAddresBytes = New-Object Byte[] 4 for($i = 0; $i -lt $BroadcastAddresBytes.Length; $i++) { $BroadcastAddresBytes[$i] = ($ParsedIPBytes[$i] -bor ($ParsedSubnetBytes[$i] -bxor 255)) Write-Verbose ("BroadcastAddress {0} octet : {1} | ( {2} ^ 255 ) -> {3}" -f ($i + 1), $ParsedIPBytes[$i], $ParsedSubnetBytes[$i], $BroadcastAddresBytes[$i]) } $RetValue.Add("BroadcastAddress", ($BroadcastAddresBytes -join ".")); } # ホスト名を取得 if( $CalcType -contains 'Hostname' ){ $Hostname = "" try{ $Hostname = [Net.Dns]::GetHostEntry($ParsedIPAddress).HostName }catch{ Write-Warning ( $MSG_UNKNOWN_HOSTNAME -f $ParsedIPAddress ) } $RetValue.Add("Hostname", $Hostname); } return $RetValue; }
PowerShellCorpus/GithubGist/FeodorFitsner_835d0d2408d816c28bec_raw_9373079f4570f8f576257301642546a37c587724_download-appvyr-artifacts.ps1
FeodorFitsner_835d0d2408d816c28bec_raw_9373079f4570f8f576257301642546a37c587724_download-appvyr-artifacts.ps1
$apiUrl = 'https://ci.appveyor.com/api' $token = '<your-api-token>' $headers = @{ "Authorization" = "Bearer $token" "Content-type" = "application/json" } $accountName = '<your-account-name>' $projectSlug = '<your-project-slug>' $downloadLocation = 'C:\projects' # get project with last build details $project = Invoke-RestMethod -Method Get -Uri "$apiUrl/projects/$accountName/$projectSlug" -Headers $headers # we assume here that build has a single job # get this job id $jobId = $project.build.jobs[0].jobId # get job artifacts (just to see what we've got) $artifacts = Invoke-RestMethod -Method Get -Uri "$apiUrl/buildjobs/$jobId/artifacts" -Headers $headers # here we just take the first artifact, but you could specify its file name # $artifactFileName = 'MyWebApp.zip' $artifactFileName = $artifacts[0].fileName # artifact will be downloaded as $localArtifactPath = "$downloadLocation\$artifactFileName" # download artifact # -OutFile - is local file name where artifact will be downloaded into Invoke-RestMethod -Method Get -Uri "$apiUrl/buildjobs/$jobId/artifacts/$artifactFileName" ` -OutFile $localArtifactPath -Headers $headers
PowerShellCorpus/GithubGist/aarismendi_5528486_raw_adaa864c2d6e7effcad5bd7eb89a64651c069b49_New-HgChangesetReport.ps1
aarismendi_5528486_raw_adaa864c2d6e7effcad5bd7eb89a64651c069b49_New-HgChangesetReport.ps1
cd 'C:\hg\repo' $rev_range = 671..720 filter Select-CommitAttribute ($Name) { $_ | ? {$_.startswith($Name)} | % { $_ -replace "${Name}:\s+", "" } } $rev_infos = $rev_range | % { $rev_info_out = & hg log --rev $_ $rev_id = ($rev_info_out | Select-CommitAttribute -Name changeset).Split(':')[0] New-Object -TypeName PsObject -Property @{ revision = $rev_id changeset_id = ($rev_info_out | Select-CommitAttribute -Name changeset).Split(':')[1] user = $rev_info_out | Select-CommitAttribute -Name user date = $rev_info_out | Select-CommitAttribute -Name date summary = $rev_info_out | Select-CommitAttribute -Name summary files = (& hg status --change $rev_id) } } $rev_infos | ? {$_.summary -notmatch 'merge|^added tag'} | group user | % { "[ $($_.Name) ]" ($_.Group | select -exp files | Select -Unique | Sort) "`n" }
PowerShellCorpus/GithubGist/jrotello_5925064_raw_870377d8cf71bf7598bc515aea44b8439eae9083_gitignore.io.ps1
jrotello_5925064_raw_870377d8cf71bf7598bc515aea44b8439eae9083_gitignore.io.ps1
# Description: # A couple of PowerShell helper functions to interact with # http://gitignore.io. These functions will allow you to # list the terms recognized by http://gitignore.io as well # as generate .gitignore files. # # Install: # Save this file to your machine and dot source it in your PowerShell # profile. function Get-GitIgnore() { <# .SYNOPSIS Generate .gitignore files from http://gitignore.io. .DESCRIPTION Generate .gitignore files from http://gitignore.io. .PARAMETER terms A comma separated list of terms to generate your .gitignore file from. .EXAMPLE Get-GitIgnore visualstudio Preview a .gitignore file suitable for Visual Studio. .EXAMPLE Get-GitIgnore visualstudio > .gitignore Save a .gitignore file suitable for Visual Studio to disk. .EXAMPLE Get-GitIgnore linux,java #> param( [Parameter(Mandatory=$true)] [string[]]$terms ) $url = "http://gitignore.io/api/" + [string]::Join(",",$terms) Invoke-RestMethod $url } function List-GitIgnore() { <# .SYNOPSIS List the available terms recognized by http://gitignore.io. .DESCRIPTION List the available terms recognized by http://gitignore.io. .EXAMPLE List-GitIgnore Display all of the terms recognized by http://gitignore.io. #> Get-GitIgnore list | % { $_.Split(",", [StringSplitOptions]::RemoveEmptyEntries) } | Sort-Object | Format-Wide -Property { $_.Trim() } -AutoSize -Force }
PowerShellCorpus/GithubGist/tugberkugurlu_2851100_raw_1743b28a57d19ebb6b953b5eb2e06bd38206b51d_RemoveALLCAPSVS2012RC.ps1
tugberkugurlu_2851100_raw_1743b28a57d19ebb6b953b5eb2e06bd38206b51d_RemoveALLCAPSVS2012RC.ps1
Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\11.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1
PowerShellCorpus/GithubGist/sayedihashimi_f2048fd957f860f38ecd_raw_aef94cd2591c8b964c271d1a317be9b8b4c25994_remove-items.ps1
sayedihashimi_f2048fd957f860f38ecd_raw_aef94cd2591c8b964c271d1a317be9b8b4c25994_remove-items.ps1
[cmdletbinding()] param( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline=$true)] $folder, [bool]$backup = $true, [switch]$recurse ) # add msbuild types here Add-Type -AssemblyName Microsoft.Build <# .SYNOPSIS This can be used to open an MSBuild projcet file. The object returned is of type Microsoft.Build.Construction.ProjectRootElement. You can get the project either from a file or from an object. Regarding the from an existing object if the passed in is a ProjectRootElement it will be returned, and otherwise the value for $sourceObject.ContainingProject is returned. This is useful to enable pipeline continuations based on the return type of the previous function call. .OUTPUTS [Microsoft.Build.Construction.ProjectRootElement] .EXAMPLE Get-MSBuildProject -projectFile 'C:\temp\msbuild\new\new.proj' .EXAMPLE Get-MSBuildProject -projectFile 'C:\temp\msbuild\new\new.proj' | Find-PropertyGroup -labelValue second | Remove-Property -name Configuration | Get-MSBuildProject | Save-MSBuildProject -filePath $projFile #> function Get-MSBuildProject{ [cmdletbinding()] param( [Parameter( Position=1)] $projectFile, [Parameter( ValueFromPipeline=$true)] $sourceObject, $projectCollection = (New-Object Microsoft.Build.Evaluation.ProjectCollection) ) begin{ Add-Type -AssemblyName System.Core Add-Type -AssemblyName Microsoft.Build } process{ $project = $null if($projectFile){ $fullPath = (Get-Fullpath $projectFile) $project = ([Microsoft.Build.Construction.ProjectRootElement]::Open([string]$fullPath,$projectCollection)) } elseif($sourceObject -is [Microsoft.Build.Construction.ProjectRootElement]){ $project = $sourceObject } else{ $project = $sourceObject.ContainingProject } return $project } } <# .SYNOPSIS Can be used to convert a relative path (i.e. .\project.proj) to a full path. #> function Get-Fullpath{ [cmdletbinding()] param( [Parameter( Mandatory=$true, ValueFromPipeline = $true)] $path, $workingDir = ($pwd) ) process{ $fullPath = $path $oldPwd = $pwd Push-Location Set-Location $workingDir [Environment]::CurrentDirectory = $pwd $fullPath = ([System.IO.Path]::GetFullPath($path)) Pop-Location [Environment]::CurrentDirectory = $oldPwd return $fullPath } } function RemoveItemsFromProj{ [cmdletbinding()] param( [Parameter( Mandatory=$true, ValueFromPipeline=$true)] $project, $itemsToRemove = @('Content','Compile','None') ) process{ foreach($p in $project){ if(!($p)){ continue } 'Removing items from project [{0}]' -f ($p.FullPath) | Write-Verbose # remove any item in the list foreach($item in $p.Items){ if($itemsToRemove -contains ($item.ItemType)){ # remove the item "Removing item [(ln {0} col {1}){2}:{3}]" -f ($item.Location.Line), ($item.Location.Column),($item.ItemType), ($item.Include) | Write-Verbose $item.Parent.RemoveChild($item) } } # look for and remove empty ItemGroup elements foreach($ig in $p.ItemGroups){ if(!$ig.Items -or $ig.Items.Count -le 0){ "Removing empty ItemGroup at [({0}:{1})]" -f $ig.Location.Line,$ig.Location.Column | Write-Verbose $ig.Parent.RemoveChild($ig) } } } } } ################################################# # Begin script ################################################# 'Looking for .kproj files under [{0}], please wait' -f $folder | Write-Host $projects = Get-ChildItem -Path $folder -Include *.kproj -Recurse:$recurse if($backup){ 'Backing up files' | Write-Host $utcNow = [DateTime]::UtcNow foreach($p in $projects){ $projPath = $p.Fullname $backupName = ('{0}.bak.{1}' -f $projPath, ($utcNow.Ticks)) 'Backing up project from [{0}] to [{1}]' -f $projPath, $backupName | Write-Verbose Copy-Item $projPath $backupName } } else{ 'Skipping backup as requested' | Write-Host } foreach($p in $projects){ $msbProj = Get-MSBuildProject -projectFile $p RemoveItemsFromProj -project $msbProj $msbProj.Save() }
PowerShellCorpus/GithubGist/andreaswasita_84bb3133bc7b915bc352_raw_6bbbc6c09ceccde9166b33fda907c1b223cd6648_NewVM.ps1
andreaswasita_84bb3133bc7b915bc352_raw_6bbbc6c09ceccde9166b33fda907c1b223cd6648_NewVM.ps1
cls Import-module Azure $subscription = Read-Host -Prompt 'Microsoft Azure Subscription:' $storage = Read-Host -Prompt 'Storage Account Name:' Set-azuresubscription -SubscriptionName $subscription -CurrentStorageAccountName $storage #Get the latest image ; Windows Server 2012 Datacenter or mykloud2012datacenterimage $images = Get-AzureVMImage ` | where { $_.Label -like "Windows Server 2012 Datacenter" } ` | Sort-Object -Descending -Property PublishedDate $latestImage = $images[0] $latestImage #image $myimage = Read-Host -Prompt 'Azure Image Name:' #cloudservice $service = Read-Host -Prompt 'Azure Service Name:' #vmname $name = Read-Host -Prompt 'Azure VM Name:' #instance size: ExtraSmall, Small, Medium, Large, ExtraLarge, A5, A6, A7, A8, A9 $instance = Read-Host -Prompt 'Instance Size:' #admin $username = Read-Host -Prompt 'Admin User Name:' #password $password = Read-Host -Prompt 'Password:' #location $location = Read-Host -Prompt 'Azure Location:' #vm configuration $myVM = New-AzureVMConfig -Name $name -InstanceSize $instance -ImageName $myimage -DiskLabel "OS" ` | Add-AzureProvisioningConfig -Windows -Password $password -AdminUsername $username -DisableAutomaticUpdates #createVM New-AzureVM -ServiceName $service -VMs $myVM -Location $location
PowerShellCorpus/GithubGist/halr9000_6604542_raw_93da99b6f7f8f9034d2e6e60450b1c4e81e9efbe_Export-SplunkSearch.ps1
halr9000_6604542_raw_93da99b6f7f8f9034d2e6e60450b1c4e81e9efbe_Export-SplunkSearch.ps1
# Conversion of http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#search.2Fjobs.2Fexport # example using curl, to PowerShell with Invoke-RestMethod cmdlet # # $ curl -k -u admin:changeme https://localhost:8089/services/search/jobs/export # --data-urlencode search="search index=_internal | stats count by sourcetype" # -d output_mode=json -d earliest="rt-5m" -d latest="rt" $cred = Get-Credential # This will allow for self-signed SSL certs to work [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } $server = 'server.company.com' $url = "https://${server}:8089/services/search/jobs/export" # braces needed b/c the colon is otherwise a scope operator $search = "search index=_internal | stats count by sourcetype" # Cmdlet handles urlencoding $body = @{ search = $search output_mode = "json" earliest_time = "rt-5m" latest_time = "rt" } Invoke-RestMethod -Method Post -Uri $url -Credential $cred -Body $body
PowerShellCorpus/GithubGist/gravejester_5041834_raw_5e9e40a46bd03822ffd51284e1f76d2dc5e9e258_Get-ClusterGroupInfo.ps1
gravejester_5041834_raw_5e9e40a46bd03822ffd51284e1f76d2dc5e9e258_Get-ClusterGroupInfo.ps1
Get-WmiObject -namespace rootmscluster -class mscluster_resourcegroup -computer $computer -Authentication PacketPrivacy|Add-Member -pass ScriptProperty Node {Get-WmiObject -namespace rootmscluster -computer $computer -Authentication PacketPrivacy -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.name)'} WHERE AssocClass = MSCluster_NodeToActiveGroup"|Select -ExpandProperty Name}|Select @{Name="Group";Expression={$_.Name}},Node,@{Name="Status";Expression={if($_.State -eq 0){"Online"}else{"Offline"}}}|ft -autosize
PowerShellCorpus/GithubGist/seanbamforth_9436783_raw_d2c72ccbc178f9f60b78969db3d16a5ca5111841_copys3tolocal.ps1
seanbamforth_9436783_raw_d2c72ccbc178f9f60b78969db3d16a5ca5111841_copys3tolocal.ps1
param ( [string]$from = "selectcs-backup", [string]$to = $(get-location).ToString() ) #todo:if no parameters, then show instructions #todo:mirror option that deletes items that don't exist #todo:aws details need to be in the environment. #$DebugPreference = "Continue" import-module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1" add-type -assemblyName "System.Web" $maxkeys = 1000 $blocksize = (1024*1024*5) $startblocks = (1024*1024*16) $region = "eu-west-1" # Regions: us-east-1, us-west-2, us-west-1, eu-west-1, ap-southeast-1 $AccessKeyId = (get-item env:aws-access-key-id -erroraction ignore).value $AccessKeySecret = (get-item env:aws-access-key-secret -erroraction ignore).value if ( !($AccessKeyId) -or !($AccessKeySecret)) { $ok = ($AccessKeyId) -or ($AccessKeySecret) Write-Host "AWS Access keys have not been created." Write-Host "===================================================================" Write-Host "To run this script you must create two environment variables called" Write-Host "aws-access-key-id and aws-access-key-secret" Write-Host "--" break } $restoreTo = $to $restoreFrom = $from $restoreTo = $restoreTo.ToLower() if ($restoreTo[-1] -ne "\") { $restoreTo += "\" } $restoreFrom = $restoreFrom.ToLower() $bucket = $restoreFrom.Split(":")[0] $s3folder = $restoreFrom.Split(":")[1] if (!($s3folder)) { $s3folder = $env:COMPUTERNAME + "/" $s3folder += $(get-location).ToString() + "/" $s3folder = $s3folder.replace("\\","/").replace(":\","/").replace("\","/") $s3folder = $s3folder.ToLower() } $s3folder = $s3folder.ToLower().replace("\" , "/") if ($s3folder[-1] -ne "/") { $s3folder += "/" } $msg="Restoring files from $restoreFrom to $restoreTo " Write-Host $msg Write-Host "-" Write-Host "Bucket: $bucket" Write-Host "S3 Folder: $s3folder" Write-Host ("=" * $msg.Length) $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider function AmazonEtagHashForFile($filename) { $lines = 0 [byte[]] $binHash = @() $reader = [System.IO.File]::Open($filename,"OPEN","READ") if ((Get-Item $filename).length -gt $startblocks) { $buf = new-object byte[] $blocksize while (($read_len = $reader.Read($buf,0,$buf.length)) -ne 0){ $lines += 1 $binHash += $md5.ComputeHash($buf,0,$read_len) } $binHash=$md5.ComputeHash( $binHash ) } else { $lines = 1 $binHash += $md5.ComputeHash($reader) } $reader.Close() $hash = [System.BitConverter]::ToString( $binHash ) $hash = $hash.Replace("-","").ToLower() if ($lines -gt 1) { $hash = $hash + "-$lines" } return $hash } function s3RestoreFile($RestoreFile) { $LocalFile = $RestoreFile $LocalFile = $LocalFile.replace($s3Folder,"") $LocalFile = $LocalFile.replace("/" , "\") $LocalFile = [System.Web.HttpUtility]::UrlDecode($LocalFile) $LocalFile = $restoreTo + $LocalFile $copyfile = $true if (Test-Path $LocalFile) { $hash = AmazonEtagHashForFile($LocalFile) $s3file = (Get-S3Object -BucketName $bucket -Key $RestoreFile) $etag =$s3file[0].etag.Replace('"',"") $copyfile = ($etag -ne $hash) } if ($copyfile) { Read-S3Object -BucketName $bucket -File $LocalFile -Key $RestoreFile } } Set-AWSCredentials -AccessKey $AccessKeyId -SecretKey $AccessKeySecret Set-DefaultAWSRegion $region # we use -Marker to start searching from a point. # because AWS only returns up to 1000 items at a time. $marker = "" do { $s3files = (Get-S3Object -Marker $marker -MaxKeys $maxkeys -BucketName $bucket -KeyPrefix $s3Folder ) $s3files | Foreach-Object{ $marker = $_.key s3RestoreFile $_.key } } while ($s3files.length -eq $maxkeys) Write-Host("..")
PowerShellCorpus/GithubGist/Rutix_1225506_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
Rutix_1225506_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
# SSH Agent Functions # Mark Embling (http://www.markembling.info/) # # How to use: # - Place this file into %USERPROFILE%\Documents\WindowsPowershell (or location of choice) # - Import into your profile.ps1: # e.g. ". (Resolve-Path ~/Documents/WindowsPowershell/ssh-agent-utils.ps1)" [without quotes] # - Enjoy # # Note: ensure you have ssh and ssh-agent available on your path, from Git's Unix tools or Cygwin. # Retrieve the current SSH agent PId (or zero). Can be used to determine if there # is an agent already starting. function Get-SshAgent() { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "User") if ([int]$agentPid -eq 0) { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "Process") } if ([int]$agentPid -eq 0) { 0 } else { # Make sure the process is actually running $process = Get-Process -Id $agentPid -ErrorAction SilentlyContinue if(($process -eq $null) -or ($process.ProcessName -ne "ssh-agent")) { # It is not running (this is an error). Remove env vars and return 0 for no agent. [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") 0 } else { # It is running. Return the PID. $agentPid } } } # Start the SSH agent. function Start-SshAgent() { # Start the agent and gather its feedback info [string]$output = ssh-agent $lines = $output.Split(";") $agentPid = 0 foreach ($line in $lines) { if (([string]$line).Trim() -match "(.+)=(.*)") { # Set environment variables for user and current process. [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process") [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "User") if ($matches[1] -eq "SSH_AGENT_PID") { $agentPid = $matches[2] } } } # Show the agent's PID as expected. Write-Host "SSH agent PID:", $agentPid } # Stop a running SSH agent function Stop-SshAgent() { [int]$agentPid = Get-SshAgent if ([int]$agentPid -gt 0) { # Stop agent process $proc = Get-Process -Id $agentPid if ($proc -ne $null) { Stop-Process $agentPid } # Remove all enviroment variables [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") } } # Add a key to the SSH agent function Add-SshKey() { if ($args.Count -eq 0) { # Add the default key (~/id_rsa) ssh-add } else { foreach ($value in $args) { ssh-add $value } } } # Start the agent if not already running; provide feedback $agent = Get-SshAgent if ($agent -eq 0) { Write-Host "Starting SSH agent..." Start-SshAgent # Start agent Add-SshKey # Add my default key } else { Write-Host "SSH agent is running (PID $agent)" }
PowerShellCorpus/GithubGist/newyear2006_8257709_raw_3afb0332619ae6bb8c46396410cbb531c337a132_TestDatei.ps1
newyear2006_8257709_raw_3afb0332619ae6bb8c46396410cbb531c337a132_TestDatei.ps1
$conn = New-Object system.net.sockets.tcpclient($host, $port) $stream = New-Object system.net.security.sslstream($conn.getstream(), $null, { Write-Host $args[2].ChainElements[0].Certificate.Subject; Write-Host "PolicyErrors: $($args[3])"; # Immer True zurückgeben, damit alle Zertifikate auch mit Fehler akzeptiert werden. $true; }) $result = $stream.authenticateasclient("chocolatey.org") $conn.Close()
PowerShellCorpus/GithubGist/victorvogelpoel_8387918_raw_1cf3df81518651c396349d566d04dc8dc87dba8a_Write-HelloWorld.ps1
victorvogelpoel_8387918_raw_1cf3df81518651c396349d566d04dc8dc87dba8a_Write-HelloWorld.ps1
# Write-HelloWorld.ps1 # Sample file for calculating PowerShell script code metrics # Jan 2014 # If this works, Victor Vogelpoel <[email protected]> wrote this. # If it doesn't, I don't know who wrote this. Set-PSDebug -Strict Set-StrictMode -Version Latest function Write-HelloWorld { # Just write it to the host! # This line has no code, just comment Write-Host "Hello World!" # A line of comment on a codeline Write-Verbose "Hello World!" <# .Synopsis Writes hello world to the host .DESCRIPTION Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet .INPUTS Inputs to this cmdlet (if any) .OUTPUTS Output from this cmdlet (if any) .NOTES General notes .COMPONENT The component this cmdlet belongs to .ROLE The role this cmdlet belongs to .FUNCTIONALITY The functionality that best describes this cmdlet #> }
PowerShellCorpus/GithubGist/tophatsteve_2888783_raw_ae121fb938493a28eaebc94bb770a5e391d9533d_GenerateFunction.ps1
tophatsteve_2888783_raw_ae121fb938493a28eaebc94bb770a5e391d9533d_GenerateFunction.ps1
function GenerateFunction($functionName, $codeBlock) { $argList = "" foreach($argName in $args) { if($argList.Length -gt 0) { $argList += "," } $argList += "`$" + $argName } $newFunc = @" function global:$functionName($argList) { $codeBlock } "@ Invoke-Expression $newFunc } GenerateFunction myfunc -codeBlock {echo "hello"} # PS> myfunc # hello GenerateFunction myAdd -codeBlock {$a + $b} a b # PS> myAdd 1 2 # 3
PowerShellCorpus/GithubGist/johnmontero_3729087_raw_22b31e4241a517a244758818c10c96705cac2b3e_appsync.ps1
johnmontero_3729087_raw_22b31e4241a517a244758818c10c96705cac2b3e_appsync.ps1
#-----------------------------------------------------------------------------# # Name : appsync.ps1 # Autor : John Montero # Create: 14.09.2012 #-----------------------------------------------------------------------------# $__version__ = "0.0.1" Function writelog($msg, $fileOut) { $datetime = (get-date).ToString() if($fileOut) { Write-Output "$datetime : $msg" | Out-File $fileOut -append } else { Write-Host "$datetime : $msg" } } Function hg_version() { $pinfo = New-Object System.Diagnostics.ProcessStartInfo $pinfo.FileName = "hg.exe" $pinfo.RedirectStandardError = $true $pinfo.RedirectStandardOutput = $true $pinfo.UseShellExecute = $false $pinfo.Arguments = "version" $p = New-Object System.Diagnostics.Process $p.StartInfo = $pinfo $p.Start() | Out-Null $p.WaitForExit() return $p.StandardOutput.ReadToEnd() } Function hg_cmd($arguments) { $pinfo = New-Object System.Diagnostics.ProcessStartInfo $pinfo.FileName = "hg.exe" $pinfo.RedirectStandardError = $true $pinfo.RedirectStandardOutput = $true $pinfo.UseShellExecute = $false $pinfo.Arguments = $arguments $p = New-Object System.Diagnostics.Process $p.StartInfo = $pinfo $p.Start() | Out-Null $p.WaitForExit() $output = $p.StandardOutput.ReadToEnd() $error = $p.StandardError.ReadToEnd() if ($error) { Write-Host "" Write-Host "Error:" Write-Host " $error" Write-Host } else { Write-Host $output } } function show_args($option) { Write-Host Write-Host "appsync - sincronizador de aplicaciones" Write-Host Write-Host "appsync.ps1 [option]" Write-Host if ($option.ToLower().CompareTo("") -eq 0) { Write-Host "Opciones :" Write-Host " --help Muestra la lista de opciones." Write-Host " --clone Clonar el repositorio." Write-Host " --push Empuja los cambios al repositorio destino." Write-Host " --pull Actualiza los cambios del repositorio." } elseif ( $option.ToLower().CompareTo("--clone") -eq 0 ) { Write-Host "Sintaxis :" Write-host Write-Host " appsync.ps1 --clone [source] [/path/to/target]" Write-Host Write-Host "source Repositorio origen." Write-Host "/path/to/target Directorio destino." } elseif ( $option.ToLower().CompareTo("push") -eq 0 ) { Write-Host "Sintaxis :" Write-host Write-Host " appsync.ps1 --push" } elseif ( $option.ToLower().CompareTo("pull") -eq 0 ) { Write-Host "Sintaxis :" Write-host Write-Host " appsync.ps1 --pull" } else { Write-Host "Error: No existe opcion implementada." } Write-Host } # # Validar cantidad de argumentos if ($args.count -lt 1) { show_args("") exit } $date_time_process = (get-date).ToString('yyyyMMdd_HHmmss') $FileLOG = "appsync_ofismart_$date_time_process.log" # Servidor de Repositorio de OFISMART $REPO_OFISMART = "http://128.1.1.12:8081/OFISMART" $TARGET = "C:\opt\" if ( $args[0] -eq "--help" ) { # Ayuda de opciones if ($args.count -lt 2 ) { show_args("") } else { show_args($args[1]) } exit } elseif ( $args[0] -eq "--clone" ) { # # Clonar el repositorio # if ($args.count -lt 3 ) { show_args($args[0]) exit } $action = "clone " + $args[1] + " " + $args[2] } elseif( $args[0] -eq "--pull" ) { $action = "pull" } elseif( $args[0] -eq 0) { $action = "push" } #$msg = "=== Iniciando $action ===" #writelog $msg #writelog $msg $FileLOG if ( "Mercurial" -constains hg_version() ){ Write-Host Write-Host "Un momento por favor ...." hg_cmd($action) } else { Write-Host Write-Host "Debe instalar Mercurial pude ver mayot informacion en http://mercurial.selenic.com" Write-Host } #$msg = "=== Finalizando ===" #writelog $msg #writelog $msg $FileLOG
PowerShellCorpus/GithubGist/jonschoning_1149220_raw_98da989292fb94776874f3290e0d9502601e4b60_TypeHelpers.ps1
jonschoning_1149220_raw_98da989292fb94776874f3290e0d9502601e4b60_TypeHelpers.ps1
function Get-Type() { [AppDomain]::CurrentDomain.GetAssemblies() | % { $_.GetTypes() }} function Get-MSDNInfo([Type]$t) { (New-Object –com Shell.Application).Open(“http://msdn.microsoft.com/$(Get-Culture)/library/$($t.FullName).aspx” ) } function Show-ClassInfo([Type]$t) { Get-Member –input (New-Object $t.FullName $args) | Out-Gridview}
PowerShellCorpus/GithubGist/ullet_31e6cc9d1d9cb9c1fac8_raw_99b072acde705504af8a768827ec9f9b8d206140_RecursiveClearReadonly.ps1
ullet_31e6cc9d1d9cb9c1fac8_raw_99b072acde705504af8a768827ec9f9b8d206140_RecursiveClearReadonly.ps1
# Recursively clear read-only flag for all files in current directory and # sub-directories. Get-ChildItem . -Recurse | Where-Object {-not $_.PSIsContainer} | Set-ItemProperty -name IsReadOnly -value $false
PowerShellCorpus/GithubGist/pcgeek86_d4caa8628e2aa4282ac0_raw_7231289d4c6b2c4b9f8d501d9be0262d9e342fe8_Import-IseHg.ps1
pcgeek86_d4caa8628e2aa4282ac0_raw_7231289d4c6b2c4b9f8d501d9be0262d9e342fe8_Import-IseHg.ps1
Import-Module -Name IseHg;
PowerShellCorpus/GithubGist/morgansimonsen_8039966_raw_cbe73314e0004b811e5fddc280cbc8840fc63b71_gistfile1.ps1
morgansimonsen_8039966_raw_cbe73314e0004b811e5fddc280cbc8840fc63b71_gistfile1.ps1
$mu = New-Object -ComObject Microsoft.Update.ServiceManager -Strict $mu.AddService2("7971f918-a847-4430-9279-4a52d1efe18d",7,"")