forked from jayharris/dotfiles-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.ps1
218 lines (177 loc) · 7.69 KB
/
functions.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# Basic commands
function which($name) { Get-Command $name -ErrorAction SilentlyContinue | Select-Object Definition }
function touch($file) { "" | Out-File $file -Encoding ASCII }
# Common Editing needs
function Edit-Hosts { Invoke-Expression "sudo $(if($env:EDITOR -ne $null) {$env:EDITOR } else { 'notepad' }) $env:windir\system32\drivers\etc\hosts" }
function Edit-Profile { Invoke-Expression "$(if($env:EDITOR -ne $null) {$env:EDITOR } else { 'notepad' }) $profile" }
# Sudo
function sudo() {
if ($args.Length -eq 1) {
start-process $args[0] -verb "runAs"
}
if ($args.Length -gt 1) {
start-process $args[0] -ArgumentList $args[1..$args.Length] -verb "runAs"
}
}
# System Update - Update RubyGems, NPM, and their installed packages
function System-Update() {
Install-WindowsUpdate -IgnoreUserInput -IgnoreReboot -AcceptAll
Update-Module
Update-Help -Force
gem update --system
gem update
npm install npm -g
npm update -g
}
# Reload the Shell
function Reload-Powershell {
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$newProcess.Arguments = "-nologo";
[System.Diagnostics.Process]::Start($newProcess);
exit
}
# Download a file into a temporary folder
function curlex($url) {
$uri = new-object system.uri $url
$filename = $name = $uri.segments | Select-Object -Last 1
$path = join-path $env:Temp $filename
if( test-path $path ) { rm -force $path }
(new-object net.webclient).DownloadFile($url, $path)
return new-object io.fileinfo $path
}
# Empty the Recycle Bin on all drives
function Empty-RecycleBin {
$RecBin = (New-Object -ComObject Shell.Application).Namespace(0xA)
$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}
}
# Sound Volume
function Get-SoundVolume { [math]::Round([Audio]::Volume * 100) }
function Set-SoundVolume([Parameter(mandatory=$true)][Int32] $Volume) { [Audio]::Volume = ($Volume / 100) }
function Set-SoundMute { [Audio]::Mute = $true }
function Set-SoundUnmute { [Audio]::Mute = $false }
### File System functions
### ----------------------------
# Create a new directory and enter it
function CreateAndSet-Directory([String] $path) { New-Item $path -ItemType Directory -ErrorAction SilentlyContinue; Set-Location $path}
# Determine size of a file or total size of a directory
function Get-DiskUsage([string] $path=(Get-Location).Path) {
Convert-ToDiskSize `
( `
Get-ChildItem .\ -recurse -ErrorAction SilentlyContinue `
| Measure-Object -property length -sum -ErrorAction SilentlyContinue
).Sum `
1
}
# Cleanup all disks (Based on Registry Settings in `windows.ps1`)
function Clean-Disks {
Start-Process "$(Join-Path $env:WinDir 'system32\cleanmgr.exe')" -ArgumentList "/sagerun:6174" -Verb "runAs"
}
### Environment functions
### ----------------------------
# Reload the $env object from the registry
function Refresh-Environment {
$locations = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
'HKCU:\Environment'
$locations | ForEach-Object {
$k = Get-Item $_
$k.GetValueNames() | ForEach-Object {
$name = $_
$value = $k.GetValue($_)
Set-Item -Path Env:\$name -Value $value
}
}
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
}
# Set a permanent Environment variable, and reload it into $env
function Set-Environment([String] $variable, [String] $value) {
Set-ItemProperty "HKCU:\Environment" $variable $value
# Manually setting Registry entry. SetEnvironmentVariable is too slow because of blocking HWND_BROADCAST
#[System.Environment]::SetEnvironmentVariable("$variable", "$value","User")
Invoke-Expression "`$env:${variable} = `"$value`""
}
# Add a folder to $env:Path
function Prepend-EnvPath([String]$path) { $env:PATH = $env:PATH + ";$path" }
function Prepend-EnvPathIfExists([String]$path) { if (Test-Path $path) { Prepend-EnvPath $path } }
function Append-EnvPath([String]$path) { $env:PATH = $env:PATH + ";$path" }
function Append-EnvPathIfExists([String]$path) { if (Test-Path $path) { Append-EnvPath $path } }
### Utilities
### ----------------------------
# Convert a number to a disk size (12.4K or 5M)
function Convert-ToDiskSize {
param ( $bytes, $precision='0' )
foreach ($size in ("B","K","M","G","T")) {
if (($bytes -lt 1000) -or ($size -eq "T")){
$bytes = ($bytes).tostring("F0" + "$precision")
return "${bytes}${size}"
}
else { $bytes /= 1KB }
}
}
# Start IIS Express Server with an optional path and port
function Start-IISExpress {
[CmdletBinding()]
param (
[String] $path = (Get-Location).Path,
[Int32] $port = 3000
)
if ((Test-Path "${env:ProgramFiles}\IIS Express\iisexpress.exe") -or (Test-Path "${env:ProgramFiles(x86)}\IIS Express\iisexpress.exe")) {
$iisExpress = Resolve-Path "${env:ProgramFiles}\IIS Express\iisexpress.exe" -ErrorAction SilentlyContinue
if ($iisExpress -eq $null) { $iisExpress = Get-Item "${env:ProgramFiles(x86)}\IIS Express\iisexpress.exe" }
& $iisExpress @("/path:${path}") /port:$port
} else { Write-Warning "Unable to find iisexpress.exe"}
}
# Extract a .zip file
function Unzip-File {
<#
.SYNOPSIS
Extracts the contents of a zip file.
.DESCRIPTION
Extracts the contents of a zip file specified via the -File parameter to the
location specified via the -Destination parameter.
.PARAMETER File
The zip file to extract. This can be an absolute or relative path.
.PARAMETER Destination
The destination folder to extract the contents of the zip file to.
.PARAMETER ForceCOM
Switch parameter to force the use of COM for the extraction even if the .NET Framework 4.5 is present.
.EXAMPLE
Unzip-File -File archive.zip -Destination .\d
.EXAMPLE
'archive.zip' | Unzip-File
.EXAMPLE
Get-ChildItem -Path C:\zipfiles | ForEach-Object {$_.fullname | Unzip-File -Destination C:\databases}
.INPUTS
String
.OUTPUTS
None
.NOTES
Inspired by: Mike F Robbins, @mikefrobbins
This function first checks to see if the .NET Framework 4.5 is installed and uses it for the unzipping process, otherwise COM is used.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]$File,
[ValidateNotNullOrEmpty()]
[string]$Destination = (Get-Location).Path
)
$filePath = Resolve-Path $File
$destinationPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination)
if (($PSVersionTable.PSVersion.Major -ge 3) -and
((Get-ItemProperty -Path "HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full" -ErrorAction SilentlyContinue).Version -like "4.5*" -or
(Get-ItemProperty -Path "HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Client" -ErrorAction SilentlyContinue).Version -like "4.5*")) {
try {
[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
[System.IO.Compression.ZipFile]::ExtractToDirectory("$filePath", "$destinationPath")
} catch {
Write-Warning -Message "Unexpected Error. Error details: $_.Exception.Message"
}
} else {
try {
$shell = New-Object -ComObject Shell.Application
$shell.Namespace($destinationPath).copyhere(($shell.NameSpace($filePath)).items())
} catch {
Write-Warning -Message "Unexpected Error. Error details: $_.Exception.Message"
}
}
}