32 Commits

Author SHA1 Message Date
  Gal Szkolnik 38dab59d62 Make sure Z is loaded if it exists 3 months ago
  Gal Szkolnik 8566ea6863 Better cross platform support 3 months ago
  Gal 7dd40b7b82 Test-MyModules finalized, ready for work 3 months ago
  lksz 0d5522b8c7 test-modules startup script draft 3 months ago
  Gal Szkolnik baa3ccd04d Updated MyConfig code to include modules 3 months ago
  lksz f00e9090a5 Added ssh configuration to MyConfig 3 months ago
  lksz 524bce25de MyConfig modifications 3 months ago
  Gal Szkolnik d85aec0480 Fixed a bug in FromPowerShellCookbook 3 months ago
  lksz ac9c5ed352 Various additions 3 months ago
  lksz 59a2949268 Moved Ansible invocation to sys.Linux 3 months ago
  lksz 2302343a15 Get-PlexInfo and txm 3 months ago
  lksz 4de25b4a56 Added -OneLine which outputs a PS table 3 months ago
  lksz b1980e5820 Ansible support + sz-update alias 3 months ago
  lksz 310103c2f7 A lot of new stuff 3 months ago
  lksz 306e03874d Setup-Profile will update git scripts from git repo 4 months ago
  Gal Szkolnik f4abdf1a2d Fixed minor cross-platfrom bug in Reload-MyScripts 4 months ago
  lksz 968b6c2bbb Adding common commands + Minor modifications 4 months ago
  lksz 38aa7720de Added default env.ps1 4 months ago
  lksz e86c7350be Create $PROFILE's parent dir if it doesn't exists 4 months ago
  lksz 90e1723052 Change Move-Item to Copy-Item 4 months ago
  lksz ccaaadf371 Setup fixed setup of MyPSScriptRoot (again) 4 months ago
  lksz fe97c2880a Fixed cross linked device failing move of .git dir 4 months ago
  lksz e14f00d98d Streamline setting of /home/szmedia/.local/share/powershell/Scripts during _setup 4 months ago
  lksz a4c4334550 Merge branch 'master' of https://code.lksz.me/lksz/PowerShell_Scripts into master 4 months ago
  lksz c25de685c1 Replaced -GitClone with -NoGitClone 4 months ago
  lksz 5a119da010 Better instructions 4 months ago
  lksz ef920fbb7d Fixed /home/szmedia/.local/share/powershell/Scripts assignment 4 months ago
  lksz bb23d940ea Merge branch 'master' of https://code.lksz.me/lksz/PowerShell_Scripts into master 4 months ago
  lksz eec4eb2cbe Updating README.md with current instructinos 4 months ago
  lksz 2d2a7bba5d System specific update 4 months ago
  Gal Szkolnik a782d09b2c fixed scoping issue 4 months ago
  lksz 0718bf28c7 Minor midifications 4 months ago
60 changed files with 680 additions and 106 deletions
Unified View
  1. +1
    -0
      Aliases/dcedit.ps1
  2. +1
    -0
      Aliases/dco.ps1
  3. +1
    -0
      Aliases/dps.ps1
  4. +1
    -0
      Aliases/edit
  5. +1
    -0
      Aliases/l.ps1
  6. +1
    -0
      Aliases/ll.ps1
  7. +1
    -0
      Aliases/sz-update.ps1
  8. +1
    -0
      Aliases/vi
  9. +1
    -0
      Aliases/vidc.ps1
  10. +1
    -0
      Aliases/vim
  11. +2
    -0
      ConvertFrom-Base64.ps1
  12. +14
    -0
      Edit-DockerCompose.ps1
  13. +24
    -0
      Edit-MyConfig.ps1
  14. +36
    -4
      Edit-MyScript.ps1
  15. +24
    -0
      Get-DockerProcess.ps1
  16. +0
    -26
      Get-MyAliases.ps1
  17. +8
    -0
      Get-Path.ps1
  18. +6
    -0
      Invoke-Sudo.ps1
  19. +15
    -35
      README.md
  20. +61
    -15
      Reload-MyScripts.ps1
  21. +33
    -26
      Setup-Profile.ps1
  22. +13
    -0
      Stop-ProcessTree.ps1
  23. +3
    -0
      dcc.ps1
  24. +1
    -0
      dcdown.ps1
  25. +1
    -0
      dcl.ps1
  26. +1
    -0
      dcll.ps1
  27. +1
    -0
      dcr.ps1
  28. +1
    -0
      dcre.ps1
  29. +11
    -0
      dcreup.ps1
  30. +10
    -0
      dcup.ps1
  31. +1
    -0
      dcx.ps1
  32. +1
    -0
      di.ps1
  33. +1
    -0
      dl.ps1
  34. +1
    -0
      dll.ps1
  35. +1
    -0
      dx.ps1
  36. +21
    -0
      profile.d/FromPowerShellCookbook.ps1
  37. +61
    -0
      profile.d/MyConfig.class.ps1
  38. +2
    -0
      profile.d/Style.ps1
  39. +37
    -0
      profile.d/SystemName.class.ps1
  40. +24
    -0
      profile.d/Test-MyModules.ps1
  41. +4
    -0
      profile.d/UnixCompleters.ps1
  42. +3
    -0
      profile.d/env.local.ps1.template
  43. +1
    -0
      profile.d/env.ps1
  44. +1
    -0
      profile.d/load-z.ps1
  45. +42
    -0
      src/config.files.json
  46. +14
    -0
      src/modules.json
  47. +18
    -0
      src/smartsudo.inc.ps1
  48. +31
    -0
      sys.Linux/Get-PlexInfo.ps1
  49. +49
    -0
      sys.Linux/Invoke-ViaAnsible.ps1
  50. +3
    -0
      sys.Linux/Pull-ViaAnsible.ps1
  51. +13
    -0
      sys.Linux/Update-ArchOSz.ps1
  52. +10
    -0
      sys.Linux/Update-OSz.ps1
  53. +14
    -0
      sys.Linux/Update-UbuntuOSz.ps1
  54. +3
    -0
      sys.Linux/Update-ViaAnsible.ps1
  55. +5
    -0
      sys.Linux/ls.ps1
  56. +1
    -0
      sys.Linux/sranger.ps1
  57. +6
    -0
      sys.Linux/sz-rsync.ps1
  58. +1
    -0
      sys.Linux/txm.ps1
  59. +35
    -0
      sz-df.ps1
  60. +1
    -0
      sz-du.ps1

+ 1
- 0
Aliases/dcedit.ps1 View File

@@ -0,0 +1 @@
Edit-DockerCompose

+ 1
- 0
Aliases/dco.ps1 View File

@@ -0,0 +1 @@
docker-compose

+ 1
- 0
Aliases/dps.ps1 View File

@@ -0,0 +1 @@
Get-DockerProcess

+ 1
- 0
Aliases/edit View File

@@ -0,0 +1 @@
Edit-TextFile

+ 1
- 0
Aliases/l.ps1 View File

@@ -0,0 +1 @@
ls

+ 1
- 0
Aliases/ll.ps1 View File

@@ -0,0 +1 @@
ls

+ 1
- 0
Aliases/sz-update.ps1 View File

@@ -0,0 +1 @@
Update-OSz

+ 1
- 0
Aliases/vi View File

@@ -0,0 +1 @@
Edit-TextFile

+ 1
- 0
Aliases/vidc.ps1 View File

@@ -0,0 +1 @@
Edit-DockerCompose

+ 1
- 0
Aliases/vim View File

@@ -0,0 +1 @@
Edit-TextFile

+ 2
- 0
ConvertFrom-Base64.ps1 View File

@@ -0,0 +1,2 @@
param([string]$Base64String)
return [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Base64String))

+ 14
- 0
Edit-DockerCompose.ps1 View File

@@ -0,0 +1,14 @@
[CmdletBinding(SupportsShouldProcess)]param([string[]]$ProjectPath=@($PWD),[switch]$Force)

$local:editCandidates = @('docker-compose.yml','.base.docker-compose.yml')
$local:editFiles = @()
foreach( $local:fileName in $EditCandidates ) {
foreach( $local:path in $ProjectPath ) {
$local:testPath = Join-Path $path $fileName
if( $Force -or $(Test-Path $testPath) ) { $editFiles += $testPath }
}
}

Edit-TextFile $editFiles

$editFiles | Select-Object -First 1 | ForEach-Object { docker-compose --file $(Resolve-Path $_) config -q }

+ 24
- 0
Edit-MyConfig.ps1 View File

@@ -0,0 +1,24 @@
[CmdletBinding(SupportsShouldProcess)]param(
[Parameter(Position = 0, ValueFromRemainingArguments)]
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
[MyConfig]::_GetValidValues($wordToComplete,$true) | Sort-Object
})]
[string[]]$ConfigName,
[switch]$Force,
[switch]$sudo
)
if( -not $ConfigName ) {
([MyConfig]::_GetValidValues('',$true)) | Sort-Object
return
}
$local:ScriptPaths = [MyConfig]::GetConfigPaths($ConfigName,$Force)

Edit-TextFile -sudo:$sudo $ScriptPaths

$null = [MyConfig]::_GetValidValues('', $true)

+ 36
- 4
Edit-MyScript.ps1 View File

@@ -9,6 +9,16 @@
[FunctionName]::_GetValidValues($wordToComplete,$true) [FunctionName]::_GetValidValues($wordToComplete,$true)
})] })]
[string[]]$ImportFunction, [string[]]$ImportFunction,
[ArgumentCompleter({ param (
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters
)
[SystemName]::_GetValidValues($wordToComplete,$false,$true)
})]
[string]$System,
[switch]$ForceImport, [switch]$ForceImport,
[Parameter(Position = 0, ValueFromRemainingArguments = $true)] [Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[ArgumentCompleter({ param ( [ArgumentCompleter({ param (
@@ -18,16 +28,24 @@
$commandAst, $commandAst,
$fakeBoundParameters $fakeBoundParameters
) )
[MyScript]::_GetValidValues($wordToComplete,$true)
$local:possibleValues = [MyScript]::_GetValidValues($wordToComplete,$true)
if( $fakeBoundParameters.ContainsKey("System") ) {
$possibleValues = $possibleValues | Where-Object { $_ -match "^sys\.$($fakeBoundParameters.System)" } | ForEach-Object { $_ -replace "^sys\.$($fakeBoundParameters.System).",'' }
}
$possibleValues
})] })]
[string[]]$ScriptName [string[]]$ScriptName
) )


$local:EditRootPath=$MyPSScriptRoot
if( $System ) {
$EditRootPath = Join-Path $EditRootPath "sys.$System"
}
$local:ScriptPaths = @() $local:ScriptPaths = @()
foreach( $local:p in $ImportFunction ) { foreach( $local:p in $ImportFunction ) {
$local:f = Get-Command $p -Type Function $local:f = Get-Command $p -Type Function
if( $f ) { if( $f ) {
$local:sp = Join-Path $MyPSScriptRoot "$p`.ps1"
$local:sp = Join-Path $EditRootPath "$p`.ps1"
if( $ForceImport -or -not (Test-Path $sp) ) { if( $ForceImport -or -not (Test-Path $sp) ) {
Export-FunctionSource $p -NoHeader > $sp Export-FunctionSource $p -NoHeader > $sp
} elseif ( -not $ForceImport ) { } elseif ( -not $ForceImport ) {
@@ -37,15 +55,29 @@ foreach( $local:p in $ImportFunction ) {
} }
} }
foreach( $local:p in $ScriptName ) { foreach( $local:p in $ScriptName ) {
$local:sp = Join-Path $MyPSScriptRoot "$p`.ps1"
$local:sp = Join-Path $EditRootPath "$p`.ps1"
$ScriptPaths += $sp $ScriptPaths += $sp
} }


if( -not $ScriptPaths ) { if( -not $ScriptPaths ) {
$ScriptPaths += $MyPSScriptRoot
$ScriptPaths += $EditRootPath
} }


foreach( $local:p in $ScriptPaths ) {
$local:parentPath = Split-Path -Parent $p;
if( -not (Test-Path $p) -and -not (Test-Path $parentPath) ) {
Write-Verbose "Creating missing path $parentPath..."
New-Item -Type Directory $parentPath
}
}

$local:sw = [System.Diagnostics.Stopwatch]::StartNew();
Edit-TextFile $ScriptPaths Edit-TextFile $ScriptPaths
$sw.Stop();

if( $sw.Elapsed.TotalSeconds -lt 1 ) {
$null = Read-Host "Waiting before refreshing. Press <Enter> when you're done editing ( don't forget to save ;) )..."
}


Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | Get-Command Reload-MyScripts -ErrorAction SilentlyContinue |
ForEach-Object { . $_.Definition } ForEach-Object { . $_.Definition }

+ 24
- 0
Get-DockerProcess.ps1 View File

@@ -0,0 +1,24 @@
#[CmdletBinding(SupportsShouldProcess)]param(
[CmdletBinding()]param([string[]]$MatchName,[string[]]$OrderBy,[switch]$PassThru,[string[]]$MatchAny)
$local:result = $(docker ps --format='{{ .Image }}\t{{ .Names }}\t{{ .Status }}\t{{ .Ports }}' |
ForEach-Object {
$local:l = $_ -split '\t';
[PSCustomObject]([ordered]@{Image=$l[0];Name=$l[1];Status=$l[2];Ports=$l[3] -replace ', ',"`n"})
} ) | Sort-Object Name

if( $MatchName ) {
$result = $result | Where-Object Name -match $($MatchName -join '|')
}

if( $MatchAny ) {
$result = $result | Where-Object { $_ | Out-String | Where-Object { $_ -match $($MatchAny -join '|') } }
}

if( $OrderBy ) {
$result = $result | Sort-Object $OrderBy
}

if( $PassThru ) { return $result }
$result | Format-Table -Wrap


+ 0
- 26
Get-MyAliases.ps1 View File

@@ -1,26 +0,0 @@
[CmdletBinding(SupportsShouldProcess)]param()

$local:allAliases = @()

$MyAliasScope = 0
$local:_scope = 0
$local:_done = $false
do {
try {
$local:newAliases += Get-Alias -Scope $_scope |
Where-Object {
($_.Definition -match "^$MyPSScriptRoot") -or ($_.Description -match '#MyAlias')
}
if( $newAliases ) {
$allAliases += $newAliases
$MyAliasScope = $_scope;
Write-Verbose "`$MyAliasScope is now set to $MyAliasScope"
}
} catch {
Write-Verbose "catch: $($_.Exception.Message)"
$_done = $_.Exception.Message -match 'The scope .* exceeds'
}
$_scope += 1
} until ( $_done )

$allAliases

+ 8
- 0
Get-Path.ps1 View File

@@ -0,0 +1,8 @@
[CmdletBinding()]param([string]$Path)

try {
get-item $Path -Force -ErrorAction Stop |
Select-Object -ExpandProperty FullName
} catch {
$_.targetObject
}

+ 6
- 0
Invoke-Sudo.ps1 View File

@@ -0,0 +1,6 @@
[CmdletBinding(SupportsShouldProcess)]param(
[Parameter(Mandatory = $true,Position = 0, ValueFromRemainingArguments = $true)]
$expr
)

. Invoke-ExpressionEx -sudo $expr

+ 15
- 35
README.md View File

@@ -6,41 +6,21 @@ The development of these is documented in my blog: https://blog.lksz.me


They are provided 'as is' for your review and for your reuse. They are provided 'as is' for your review and for your reuse.


There is a [blog post](https://blog.lksz.me/keeping-track-of-everything/#-mypsscriptroot) about how to clone this repo and use it as your own.

The scripts all [assume](https://blog.lksz.me/functions-or-scripts/#myprofilecode) the code below is part of one of your $PROFILE files.
The code establishes the following variables:
* `$PathEnvDelimiter` - Linux/Unix it's `:`, while in Windows it's `;`
* `$MyPSModulePath` - Location to place personal Modules
* `$MyPSScriptRoot` - Location of personal Scripts.
This envrionment can be installed using one the following options:
### The Short, yet safer way
```PowerShell
iwr https://lksz.me/pwsz | iex
```


The code also makes sure `$MyPSScriptRoot` is in the `$env:PATH` environment vairable, and finally it calls [`Reload-MyAliases`](https://blog.lksz.me/a-case-of-sensitivity/#myaliases) if it exists.
This sets up the `$PROFILE` file, and initilizes the default dir `$MyPSScriptRoot` with a git clone of this repo.
The `https://lksz.me/pwsz` actually points to the [`Setup-Profile.ps1`](Setup-Profile.ps1) script, which means, that after you have the `Scripts` directory setup, you can call `Setup-Profile` to update the `$PROFILE` after the `Setup-Profile.ps1` has been modified (or updated via `git pull`).


### The Short, but with control option
```PowerShell
$sfw=1; iwr https://lksz.me/pwsz | iex; _setup [-sudo] [-Force] [-NoGitClone] [-GitURL <alternative git URL>] [-WhatIf] [-Confirm] [<CommonParameters>]
``` ```
$global:PathEnvDelimiter = $(if( $PSVersionTable.Platform -match 'unix' ) {':'} else {';'})
function Split-PathEnv {
param([string]$EnvPath)
$EnvPath -split $PathEnvDelimiter
}

$global:MyPSModulePath = Split-PathEnv $env:PSModulePath | Where-Object { $_ -match "^$(Resolve-Path ~)" }

if( -not $MyPSModulePath ) {
$MyPSModulePath = Resolve-Path ~/powershell/Modules
if( -not (Test-Path $MyPSModulePath) ) {
New-Item -ItemType Directory -Path $MyPSModulePath -Force | Out-Null
}
$env:PSModulePath = "$MyPSModulePath$PathEnvDelimiter$env:PSModulePath"
}

$local:p = Split-PathEnv $env:PATH
$global:MyPSScriptRoot = Join-Path (Split-Path -Parent $MyPSModulePath) Scripts
if( -not (Test-Path $MyPSScriptRoot) ) {
New-Item -ItemType Directory -Path $MyPSScriptRoot -Force | Out-Null
}

$p = @($p[0], $MyPSScriptRoot) + $($p | Select-Object -Skip 1)
$env:PATH = $p -join $PathEnvDelimiter

Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $_.Name }
```

The key here is `$sfw=1`, which can be substitued with the more verbose `$SetupFromWeb=1`, this let's the [`Setup-Profile`](Setup-Profile.ps1) script know to just load it's content, but allow you to manually call it's internal function via `_setup`

### The 'I don't trust one liners, what's going on ?!?' option
You can always clone the git repo first, and only then run the [`Setup-Profile.ps1`](Setup-Profile.ps1) script.

+ 61
- 15
Reload-MyScripts.ps1 View File

@@ -1,21 +1,51 @@
[CmdletBinding(SupportsShouldProcess)]param() [CmdletBinding(SupportsShouldProcess)]param()


$local:myAliases = [ordered]@{}
$myAliases.sudo = 'Invoke-Sudo'
$myAliases.vi = 'Edit-TextFile'
$myAliases.vim = 'Edit-TextFile'
$myAliases.nvim = 'Edit-TextFile'
$myAliases.nvim = 'Edit-TextFile'
$myAliases.l = 'ls.ps1'
$myAliases.ll = 'ls.ps1'
try { Get-Alias Get-MyAliases -ErrorAction Stop | ForEach-Object { Remove-Item "Alias:$($_.Name)" } } catch {}
function Get-MyAliases {
[CmdletBinding(SupportsShouldProcess)]param([switch]$ScriptsOnly)

$local:allAliases = @()


#######################################################################
$MyAliasScope = 0
$local:_scope = 0
$local:_done = $false
do {
try {
$local:newAliases += Get-Alias -Scope $_scope |
Where-Object {
($_.Definition -match "^$MyPSScriptRoot") -or (-not $ScriptsOnly -and ($_.Description -match '#MyAlias'))
}
if( $newAliases ) {
$allAliases += $newAliases
$MyAliasScope = $_scope;
Write-Verbose "`$MyAliasScope is now set to $MyAliasScope"
}
} catch {
Write-Verbose "catch: $($_.Exception.Message)"
$_done = $_.Exception.Message -match 'The scope .* exceeds'
}
$_scope += 1
} until ( $_done )

$allAliases
}

function getScriptName{param([string]$FullPath)
$FullPath -replace '\.ps1$','' -replace "^$([regex]::Escape($MyPSScriptRoot)).",''
}

$local:myAliases = [ordered]@{}
if( Test-Path $(Join-Path $MyPSScriptRoot Aliases) ) {
Get-ChildItem $(Join-Path $MyPSScriptRoot Aliases) | ForEach-Object {
$myAliases[$_.BaseName] = Get-Content $_.FullName
}
}


$local:IsVerbose = [bool]($PSBoundParameters['Verbose']) $local:IsVerbose = [bool]($PSBoundParameters['Verbose'])


$local:MyAliasScope = 1
$script:MyAliasScope = 0


$local:oldAliases = . Get-MyAliases
$local:oldAliases = Get-MyAliases


$oldAliases = Get-Alias -Scope $MyAliasScope | $oldAliases = Get-Alias -Scope $MyAliasScope |
Where-Object Name -in $($oldAliases.Name + $myAliases.Keys) Where-Object Name -in $($oldAliases.Name + $myAliases.Keys)
@@ -29,14 +59,30 @@ if( Get-Command Remove-Alias -ErrorAction SilentlyContinue ) {
$oldAliases | ForEach-Object { Remove-Item "Alias:$($_.Name)" } $oldAliases | ForEach-Object { Remove-Item "Alias:$($_.Name)" }
} }


Get-ChildItem (Join-Path $MyPSScriptRoot '*.ps1') |
ForEach-Object {
if( $(. Get-ScopeDepth) -gt 0 ) { Write-Host -ForegroundColor Red "Try sourcing Reload-MyScripts instead of just running it" }
Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object {
Write-Verbose "Loading $(getScriptName $_.FullName)...";
". '$($_.FullName)';"
} | Invoke-Expression

$local:CommandsToAlias = (
@( $MyPSScriptRoot ) + $(
[SystemName]::_GetValidValues("",$true,$true) | ForEach-Object {
Join-Path $MyPSScriptRoot "sys.$_"
}
)) | ForEach-Object {
if( Test-Path $_ ) {
Get-ChildItem (Join-Path $_ '*.ps1') | Where-Object Name -notmatch '\.inc\.ps1$'
}
}

$CommandsToAlias | ForEach-Object {
Write-Verbose "Creating alias for $(getScriptName $_.FullName) Script..."
Set-Alias $($_.BaseName) $_.FullName -Scope $MyAliasScope Set-Alias $($_.BaseName) $_.FullName -Scope $MyAliasScope
} }


foreach( $local:alias in $myAliases.Keys ) { foreach( $local:alias in $myAliases.Keys ) {
Write-Verbose "Adding $($alias) alias..."
Set-Alias -Name $alias -Value $myAliases[$alias] -Description '#MyAlias' -Scope $MyAliasScope Set-Alias -Name $alias -Value $myAliases[$alias] -Description '#MyAlias' -Scope $MyAliasScope
} }


if( $(. Get-ScopeDepth) -gt 0 ) { Write-Host -ForegroundColor Red "Try sourcing Reload-MyScripts instead of just running it" }
Get-ChildItem $(Join-Path $MyPSScriptRoot profile.d) -Filter '*.ps1' | ForEach-Object { ". '$($_.FullName)';" } | Invoke-Expression

+ 33
- 26
Setup-Profile.ps1 View File

@@ -3,10 +3,10 @@
[switch]$RemoveOnly, [switch]$RemoveOnly,
[switch]$ShowSkipped, [switch]$ShowSkipped,
[switch]$Force, [switch]$Force,
[switch]$GitClone,
[switch]$NoGitAction,
[string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts',
[Parameter(DontShow)] [Parameter(DontShow)]
[string]$MyPSScriptRoot = $MyPSScriptRoot
[string]$My_PSScriptRoot = $MyPSScriptRoot
) )


function _Setup { function _Setup {
@@ -15,10 +15,10 @@ function _Setup {
[switch]$RemoveOnly, [switch]$RemoveOnly,
[switch]$ShowSkipped, [switch]$ShowSkipped,
[switch]$Force, [switch]$Force,
[switch]$GitClone,
[switch]$NoGitAction,
[string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts', [string]$GitURL = 'https://code.lksz.me/lksz/PowerShell_Scripts',
[Parameter(DontShow)] [Parameter(DontShow)]
[string]$MyPSScriptRoot = $MyPSScriptRoot)
[string]$My_PSScriptRoot = $MyPSScriptRoot)




####################################################################### #######################################################################
@@ -40,12 +40,17 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { .
## _Setup Logic starts here ## _Setup Logic starts here
####################################################################### #######################################################################


if ( $GitClone -and -not (Test-Path $(Join-Path $MyPSScriptRoot '.git')) ) {
. ProfileCode_common
if( -not $MyPSScriptRoot ) { throw '$MyPSScriptRoot does NOT exist!' }

if ( -not $NoGitAction ) {
if ( -not [bool]$(Get-Command git -ErrorAction SilentlyContinue) ) { if ( -not [bool]$(Get-Command git -ErrorAction SilentlyContinue) ) {
throw "No git command found, you may either omit the -GitClone switch or install git and try again."
throw "No git command found, you may either omit run with the -NoGitAction switch or install git and try again."
} }
if ( $PSCmdlet.ShouldProcess("Pull git repo from $GitURL into $MyPSScriptRoot ?") ) {
Push-Location $MyPSScriptRoot
Push-Location $MyPSScriptRoot
if( Test-Path $(Join-Path $MyPSScriptRoot '.git') ) {
git pull
} elseif ( $PSCmdlet.ShouldProcess("Pull git repo from $GitURL into $MyPSScriptRoot ?") ) {
$local:tmpGitDir = New-TemporaryFile $local:tmpGitDir = New-TemporaryFile
Remove-Item $tmpGitDir Remove-Item $tmpGitDir
New-Item -Type Directory $tmpGitDir.FullName | Out-Null New-Item -Type Directory $tmpGitDir.FullName | Out-Null
@@ -53,14 +58,14 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { .
$local:GitOutput = "$(& git clone $GitURL $tmpGitDir.FullName --no-checkout)" $local:GitOutput = "$(& git clone $GitURL $tmpGitDir.FullName --no-checkout)"
Write-Verbose $GitOutput Write-Verbose $GitOutput
Write-Verbose "Moving git repo from temp location to $MyPSScriptRoot . . ." Write-Verbose "Moving git repo from temp location to $MyPSScriptRoot . . ."
Move-Item (Join-Path $tmpGitDir.FullName .git) ./.git
Copy-Item -Recurse (Join-Path $tmpGitDir.FullName .git) ./.git
Remove-Item $tmpGitDir.FullName Remove-Item $tmpGitDir.FullName
Write-Verbose "Checking out repo..." Write-Verbose "Checking out repo..."
$GitOutput = "$(& git checkout --force)" $GitOutput = "$(& git checkout --force)"
Write-Verbose $GitOutput Write-Verbose $GitOutput
Pop-Location
Write-Verbose "-GitClone step done."
} }
Pop-Location
Write-Verbose "Git operation done."
} }


$local:ProfileSignature = [PSCustomObject]([ordered]@{ $local:ProfileSignature = [PSCustomObject]([ordered]@{
@@ -166,7 +171,11 @@ Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { .
Invoke-ExpressionEx -sudo:$shouldSudo chmod 'a+r' $tmpOutput.FullName Invoke-ExpressionEx -sudo:$shouldSudo chmod 'a+r' $tmpOutput.FullName
} }
try { try {
$local:errMsg = $(Invoke-ExpressionEx -sudo:$shouldSudo "Move-Item $($tmpOutput.FullName) $p -Force:`$$Force -ErrorAction Stop | Out-Null" 2>&1)
$local:errMsg = $(Invoke-ExpressionEx -sudo:$shouldSudo @"
if( -not (Test-Path $(Split-Path -Parent $p)) ) { New-Item -Type Directory $(Split-Path -Parent $p) -Force };
Copy-Item $($tmpOutput.FullName) $p -Force:`$$Force -ErrorAction Stop | Out-Null;
Remove-Item $($tmpOutput.FullName) -Force:`$$Force -ErrorAction Stop
"@ 2>&1)
if ( $errMsg ) { if ( $errMsg ) {
Write-Error "$errMsg" Write-Error "$errMsg"
$status = $status -replace 'Need ', 'Failed ' $status = $status -replace 'Need ', 'Failed '
@@ -380,10 +389,10 @@ param([string]$EnvPath)


# Establish Module Path # Establish Module Path
$global:MyPSModulePath = Split-PathEnv $env:PSModulePath | $global:MyPSModulePath = Split-PathEnv $env:PSModulePath |
Where-Object { $_ -match "^$($(Resolve-Path ~) -replace '\\',"\\")" } |
Where-Object { Test-Path $_ } |
Get-Item | Sort-Object -Property LastWriteTime -Descending |
Select-Object -ExpandProperty FullName -First 1
Where-Object { $_ -match "^$($(Resolve-Path ~) -replace '\\',"\\")" } |
Where-Object { Test-Path $_ } |
Get-Item | Sort-Object -Property LastWriteTime -Descending |
Select-Object -ExpandProperty FullName -First 1


if ( -not $MyPSModulePath ) { if ( -not $MyPSModulePath ) {
$MyPSModulePath = $(Join-Path $(Join-Path $(Resolve-Path ~) 'powershell') 'Modules') $MyPSModulePath = $(Join-Path $(Join-Path $(Resolve-Path ~) 'powershell') 'Modules')
@@ -397,25 +406,23 @@ Write-Verbose $(Get-Item $MyPSModulePath | Select-Object -ExpandProperty FullNam


# Establish local/personal Script Root and make sure it's in $env:Path # Establish local/personal Script Root and make sure it's in $env:Path
$local:p = Split-PathEnv $env:PATH $local:p = Split-PathEnv $env:PATH
$MyPSScriptRoot = Join-Path (Split-Path -Parent $MyPSModulePath) Scripts
Write-Verbose "MyPSScriptRoot = $MyPSScriptRoot"
if ( -not (Test-Path $MyPSScriptRoot) ) {
New-Item -ItemType Directory -Path $MyPSScriptRoot -Force | Out-Null
New-Item -ItemType Directory -Path $MyPSScriptRoot/profile.d -Force | Out-Null
$local:My_PSScriptRoot = Join-Path (Split-Path -Parent $MyPSModulePath) Scripts
Write-Verbose "MyPSScriptRoot = $My_PSScriptRoot"
if ( -not (Test-Path $My_PSScriptRoot) ) {
New-Item -ItemType Directory -Path $My_PSScriptRoot -Force | Out-Null
New-Item -ItemType Directory -Path $My_PSScriptRoot/profile.d -Force | Out-Null
} }
$global:MyPSScriptRoot = $MyPSScriptRoot
$global:MyPSScriptRoot = $My_PSScriptRoot


$p = @($p[0], $MyPSScriptRoot) + $($p | Select-Object -Skip 1) $p = @($p[0], $MyPSScriptRoot) + $($p | Select-Object -Skip 1)
$env:PATH = $p -join $PathEnvDelimiter $env:PATH = $p -join $PathEnvDelimiter
} }


if ( -not $MyPSScriptRoot -or (Test-Path function:Test-IsAdmin, function:ConvertTo-Base64, function:Invoke-ExpressionEx, function:Get-PowerShellPath, function:Export-FunctionSource | Where-Object { -not $_ } | Measure-Object | Select-Object -ExpandProperty Count) ) {
Write-Verbose "Calling ProfileCode inline..."
. ProfileCode_common
}
$SetupFromWeb = [bool]$(@( $SetupFromWeb, $sfw, $LoadCode ) | Where-Object { $_ })


if ( -not $SetupFromWeb ) { if ( -not $SetupFromWeb ) {
_setup @PSBoundParameters _setup @PSBoundParameters
Get-Item function:_setup | Remove-Item Get-Item function:_setup | Remove-Item
Get-Command Reload-MyScripts -ErrorAction SilentlyContinue | ForEach-Object { . $_.Name }
} }
Remove-Variable SetupFromWeb -ErrorAction SilentlyContinue Remove-Variable SetupFromWeb -ErrorAction SilentlyContinue

+ 13
- 0
Stop-ProcessTree.ps1 View File

@@ -0,0 +1,13 @@
[cmdletbinding()]param([string]$ProcessName)
$local:new_KillPIDs = @() + (Get-Process -name $processName | Select-Object -ExpandProperty ID)
$local:KillPIDs = @()
Do {
$KillPIDs += $new_KillPIDs | Where-Object { $_ -notin $KillPIDs }
Write-Verbose "Again"
Write-Verbose $new_KillPIDs -join ", "
$new_KillPIDs = $new_KillPIDs | ForEach-Object { Get-CimInstance -ClassName Win32_Process -Filter "ParentProcessId = $_" } | Select-Object -ExpandProperty ProcessId
} Until ( -not $new_KillPIDs )

Write-Verbose "Done"

start-process powershell -ArgumentList "-command","Stop-Process -Force -Id @($($KillPIDs -join '', ''))" -WindowStyle Minimized

+ 3
- 0
dcc.ps1 View File

@@ -0,0 +1,3 @@
[CmdletBinding(SupportsShouldProcess)]param([string[]]$ProjectPath=@($PWD))

$ProjectPath | ForEach-Object { docker-compose --file $(Resolve-Path $(Join-Path $_ docker-compose.yml)) config | less }

+ 1
- 0
dcdown.ps1 View File

@@ -0,0 +1 @@
docker-compose down --timeout=3 --volumes --remove-orphans "$args"

+ 1
- 0
dcl.ps1 View File

@@ -0,0 +1 @@
docker-compose logs --tail=40 --follow "$args"

+ 1
- 0
dcll.ps1 View File

@@ -0,0 +1 @@
docker-compose logs "$args"

+ 1
- 0
dcr.ps1 View File

@@ -0,0 +1 @@
docker-compose run --rm "$args"

+ 1
- 0
dcre.ps1 View File

@@ -0,0 +1 @@
docker-compose restart "$args"

+ 11
- 0
dcreup.ps1 View File

@@ -0,0 +1,11 @@
#[CmdletBinding(SupportsShouldProcess)]param()

$local:dcParams = [string]::Empty
if( $args ) {
$dcParams = $args | ForEach-Object {
if( $_ -match "(?:^'[^']+'$)|(?:^`"[^`"]+`"$)|(?:^[^\s]+$)" ) { $_ }
else { "'$($_.Replace( "'", "''" ))'" }
}
}
docker-compose up -d --force-recreate --remove-orphans $dcParams && docker-compose logs --follow --tail 10 $dcParams


+ 10
- 0
dcup.ps1 View File

@@ -0,0 +1,10 @@
#[CmdletBinding(SupportsShouldProcess)]param()

$local:dcParams = [string]::Empty
if( $args ) {
$dcParams = $args | ForEach-Object {
if( $_ -match "(?:^'[^']+'$)|(?:^`"[^`"]+`"$)|(?:^[^\s]+$)" ) { $_ }
else { "'$($_.Replace( "'", "''" ))'" }
}
}
docker-compose up -d --remove-orphans $dcParams && docker-compose logs --follow --tail 10 $dcParams

+ 1
- 0
dcx.ps1 View File

@@ -0,0 +1 @@
docker-compose exec "$args"

+ 1
- 0
di.ps1 View File

@@ -0,0 +1 @@
docker inspect "$args"

+ 1
- 0
dl.ps1 View File

@@ -0,0 +1 @@
docker logs --tail=40 --follow "$args"

+ 1
- 0
dll.ps1 View File

@@ -0,0 +1 @@
docker logs "$args"

+ 1
- 0
dx.ps1 View File

@@ -0,0 +1 @@
docker exec "$args"

+ 21
- 0
profile.d/FromPowerShellCookbook.ps1 View File

@@ -0,0 +1,21 @@
# PowerShell Cookbook has a lot of code there, I'm only interested in
# the Add-ObjectCollector which adds an overloaded Out-Default version,
# which stores a history of output objects.
# One major problem with loading this from the module, is that when the
# module is removed the shell BREAKS.
#
# The code below, makes sure the module is removed, and then imports
# only the Add-ObjectCollector code from it.
# All I really want is the Out-Default function created by
# Add-ObjectCollector, and so, I'll also remove the function once done.
if( Get-Module PowerShellCookbook ) {
Remove-Module PowerShellCookbook
Import-Module PowerShellCookbook -Cmdlet Add-ObjectCollector
}
#
. Get-Command Add-ObjectCollector -ErrorAction SilentlyContinue | ForEach-Object {
Add-ObjectCollector
Get-Item function:/Add-ObjectCollector | Remove-Item
}

+ 61
- 0
profile.d/MyConfig.class.ps1 View File

@@ -0,0 +1,61 @@
class MyConfig { #: System.Management.Automation.IValidateSetValuesGenerator {
hidden static [hashtable]$_HardCodedConfigDict = @{
'myconfig' = @($(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.json'),
$(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'config.files.local.json'))
'mymodules' = @($(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'modules.json'),
$(Join-Path $(Join-Path $MyPSScriptRoot 'src') 'modules.local.json'))
}

static [hashtable]GetConfigDictionary() {
$local:result = @{}
[MyConfig]::_HardCodedConfigDict.Keys | ForEach-Object { $result[$_] = [MyConfig]::_HardCodedConfigDict[$_] }
foreach( $local:jsonSource in $result.myconfig ) {
if( -not ( Test-Path $jsonSource ) ) { continue }
foreach( $local:prop in $(Get-Content $jsonSource | ConvertFrom-Json).PSObject.Properties ) {
$result[$prop.Name] = $prop.Value
}
}
return $result;
}
static [string[]] GetConfigPaths([string[]]$ConfigNames,[switch]$Force) {
$local:configDirectory = [MyConfig]::GetConfigDictionary()
$local:result = [string[]]@()
$local:flat = $false
while(-not $flat) {
$flat = $true
$ConfigNames += $ConfigNames | ForEach-Object {
$configDirectory[$_]
} | Where-Object { $_ -match '^#[\w-\.]+$' } | ForEach-Object {
$_.Substring(1)
} | Where-Object { $_ -notin $ConfigNames } | ForEach-Object {
$flat = false; $_;
}
}

$local:flatConfigList = $ConfigNames | ForEach-Object {
$configDirectory[$_]
} | Where-Object { $_ -notmatch '^#[\w-\.]+$' }

$local:exists = $false;
$local:first = $null
foreach( $local:configPath in $flatConfigList ) {
if( -not $first ) { $first = $configPath }
if( $Force -or (Test-Path $configPath) ) {
$result += Get-Path $configPath
$exists = $true
}
}
if( -not $exists -and -not $Force ) {
$result += $first
}
return $result
}
static [string[]] _GetValidValues([string]$wordToComplete,[bool]$Strict) {
$local:possibleValues = [MyConfig]::GetConfigDictionary().Keys
return $(Get-PossibleArguments -WordToComplete $wordToComplete -FullValueSet $possibleValues -Strict:$Strict );
}

[String[]] GetValidValues() {
return [MyConfig]::_GetValidValues('',$true)
}
}

+ 2
- 0
profile.d/Style.ps1 View File

@@ -0,0 +1,2 @@
Get-Command Set-PSReadLineKeyHandler | ForEach-Object { Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete }
Get-Command Set-Theme -ErrorAction SilentlyContinue | ForEach-Object { Set-Theme Paradox }

+ 37
- 0
profile.d/SystemName.class.ps1 View File

@@ -0,0 +1,37 @@
class SystemName { #: System.Management.Automation.IValidateSetValuesGenerator {
static [string[]] _GetValidValues([string]$wordToComplete,[bool]$CurrentOnly,[bool]$Strict) {
$MyPSScriptRoot = "$global:MyPSScriptRoot";
$local:possibleValues = [ordered]@{}
$possibleValues.out = @()
$possibleValues.Current = @(
$($global:PSVersionTable.OS -split ' '|Select-Object -First 1).Replace('Microsoft','Windows'),
$global:PSVersionTable.Platform,
$global:PSVersionTable.PSEdition
);
$possibleValues.out = $possibleValues.Current

if( -not $CurrentOnly ) {
$possibleValues.Platform = @( 'Windows','Linux','Unix' );
$possibleValues.Edition = @( 'Desktop', 'Core' );
$possibleValues.Exist = Get-ChildItem (Join-Path $MyPSScriptRoot "sys.*") | ForEach-Object { $_.Name -replace 'sys\.','' };
$possibleValues.out += $possibleValues.Platform + $possibleValues.Edition + $possibleValues.Exist
}
$possibleValues.out = $possibleValues.out |
Select-Object -Unique |
Sort-Object {
$local:sortName = "zz_$_";
if( $_ -in $possibleValues.Exist -and $_ -in $possibleValues.Current ) { $sortName[0] = "a" }
elseif( $_ -in $possibleValues.Exist ) { $sortName[0] = "b" }
elseif( $_ -in $possibleValues.Current ) { $sortName[0] = "c" }
if( $_ -in $possibleValues.Platform ) { $sortName[1] = "a" }
if( $_ -in $possibleValues.Edition ) { $sortName[1] = "b" }
$sortName;
}
return $(Get-PossibleArguments -WordToComplete $wordToComplete -FullValueSet $possibleValues.out -Strict:$Strict );
}

[String[]] GetValidValues() {
return [SystemName]::_GetValidValues('',$false,$true)
}
}


+ 24
- 0
profile.d/Test-MyModules.ps1 View File

@@ -0,0 +1,24 @@
param([switch]$Force)

$local:currentSys = [SystemName]::_GetValidValues('',$true,$true);

if( -not $global:MyModulesWarning -or $Force ) {
$global:MyModulesWarning = @()
}
[MyConfig]::GetConfigPaths('mymodules',$false) |
ForEach-Object {
$local:modules = $( Get-Content $_ | ConvertFrom-Json );
$modules.Always;
$currentSys | ForEach-Object { $modules."$_" } | Where-Object { $_}
} | Where-Object {
$local:m = $_
if( $( try {
-not (Get-Module -ListAvailable $m -ErrorAction stop)
} catch { $true }
)) {
$m -notin $global:MyModulesWarning
}
} | ForEach-Object {
$global:MyModulesWarning += $_
Write-Warning "Missing module: $_"
}

+ 4
- 0
profile.d/UnixCompleters.ps1 View File

@@ -0,0 +1,4 @@
Get-Command Import-UnixCompleters -ErrorAction SilentlyContinue | ForEach-Object {
Import-UnixCompleters
Set-UnixCompleter -ShellType Zsh
}

+ 3
- 0
profile.d/env.local.ps1.template View File

@@ -0,0 +1,3 @@
# $env:DOMAIN_NAME='example.com'
#
# $env:EDITOR='/usr/bin/nvim'

+ 1
- 0
profile.d/env.ps1 View File

@@ -0,0 +1 @@
$env:SZ_SKIP_DEFAULT_SHELL = 1

+ 1
- 0
profile.d/load-z.ps1 View File

@@ -0,0 +1 @@
Get-Module -ListAvailable z | Import-Module

+ 42
- 0
src/config.files.json View File

@@ -0,0 +1,42 @@
{
"neovim": [
"~/.config/nvim/init.vim",
"~/.config/nvim/vim-plug/plugins.vim",
"#vim",
"#vi"
],
"sz-shrc": "~/.sz.shrc.sh",
"sz-rc-all": [
"#sz-aliases-sh",
"#sz-local-rc",
"#sz-shrc",
"#sz-zshrc",
"#zshrc"
],
"vi": "~/.virc",
"sz-local-rc": "~/.sz.local.sh",
"zshrc": "~/.zshrc",
"ansible": [
"/etc/ansible/ansible.cfg",
"/opt/ansible/ansible.cfg",
"/opt/ansible/hosts"
],
"sz-aliases-sh": "~/.sz.aliases.sh",
"vim": [
"~/.vimrc",
"~/.vim/vimrc"
],
"sz-zshrc": [
"~/.sz.zshrc.sh",
"#zshrc"
],
"tmux": [
"~/.tmux.conf",
"~/.byobu/.tmux.conf"
],
"ssh-pub": "~/.ssh/id_*.pub",
"ssh-id": ["~/.ssh/id_ed25519","~/.ssh/id_rsa"],
"ssh-auth": "~/.ssh/authorized_keys",
"ssh-conf": "/etc/ssh/sshd_config",
"ssh" : [ "#ssh-auth", "#ssh-conf", "#ssh-pub", "#ssh-id" ]
}

+ 14
- 0
src/modules.json View File

@@ -0,0 +1,14 @@
{
"Always": [
"PowerShellCookbook",
"oh-my-posh",
"posh-git",
"z"
],
"Desktop": [
],
"Unix": [
"Microsoft.PowerShell.UnixCompleters"
]
}

+ 18
- 0
src/smartsudo.inc.ps1 View File

@@ -0,0 +1,18 @@
function smartsudo() {
[CmdletBinding(SupportsShouldProcess)]param(
[switch]$sudo,
[switch]$Force,
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[string[]]$expr
)

if( $sudo -and -not $(Test-IsAdmin) ) {
Write-Verbose "Perofrming the following command line via SUDO:`n$($expr -join ' ')"
$local:base64command = ConvertTo-Base64 "$expr"
/usr/bin/env sudo pwsh -EncodedCommand $base64command
return
}
Write-Verbose "Perofrming the following expression in-line:`n$($expr -join ' ')"
Invoke-Expression "$expr"
}

+ 31
- 0
sys.Linux/Get-PlexInfo.ps1 View File

@@ -0,0 +1,31 @@
param([switch]$FetchFromServer,[string]$PlexHost='localhost',[switch]$PassThruOnly)

$local:content = $(try{(Get-Content /run/plex.stream.counter/sessions -Raw -ErrorAction Stop)}catch{})

if( $FetchFromServer ) {
$local:creds = New-Object System.Management.Automation.PsCredential($env:PLEX_USERNAME,$(ConvertTo-SecureString -AsPlainText $env:PLEX_PASSWORD -Force))
$local:webResp = Invoke-WebRequest -Headers @{ "Content-Length" = "0"; "X-Plex-Client-Identifier" = "my-app" } -Credential $creds -Method Post -Uri "https://my.plexapp.com/users/sign_in.xml"
$local:plexHeaders = @{ "X-Plex-Token" = ([xml]$webResp.Content).user.authenticationToken }
$webResp = Invoke-WebRequest -Headers $plexHeaders "http://${PlexHost}:32400"
$local:plexVersion = ([xml]$webResp.Content).MediaContainer.version
Write-Host -ForegroundColor Cyan "Plex Version: $plexVersion"
$webResp = Invoke-WebRequest -Headers $plexHeaders "http://${PlexHost}:32400/status/sessions"
$content = $webResp.Content
}

$local:PlexInfo = $(try{([xml]$content).MediaContainer}catch{})

$local:result = $PlexInfo.ChildNodes | ForEach-Object { [PSCustomObject]@{
Object = $_
Type = $_.type
Library = $_.librarySectionTitle
Title = $(@($_.grandparentTitle,$_.parentIndex,$_.parentTitle,$_.index,$_.title) | Where-Object {$_}) -join ' | '
User = $_.User.title
Offset = [TimeSpan]::FromMilliseconds($_.viewOffset).ToString() -split '\.' | select-object -first 1
Duration = [TimeSpan]::FromMilliseconds($_.duration).ToString() -split '\.' | select-object -first 1
Player = "$($_.Player.Platform)|$($_.Player.State)"
# UpdateTime = [TimeSpan]::FromMilliseconds($_.).ToString()
} }

if( $PassThruOnly ) { return $result }
$result | Format-Table

+ 49
- 0
sys.Linux/Invoke-ViaAnsible.ps1 View File

@@ -0,0 +1,49 @@
[CmdletBinding()]param(
[string[]]$Command,
[string[]]$Remotes = 'all',
[string[]]$MoreArgs,
[switch]$NotPowerShell,
[switch]$OneLine
)

$script:ansible_cli=@('ansible')
if( (Test-Path './ansible.cfg') -or (Test-Path '/opt/ansible/hosts') -and (Test-Path '/opt/ansible/ssh_key_for_ansible') ) {
$ansible_cli += '-i', '/opt/ansible/hosts', '--private-key=/opt/ansible/ssh_key_for_ansible'
}
if( $Command ) {
$ansible_cli += '-a'
$ansible_cli += 'ANSIBLE_PYTHON_INTERPRETER=auto_silent '
$ansible_cli += '-a'
if( $NotPowerShell ) {
$ansible_cli += $(($Command -join '; ').Replace("'","\`$(printf '\x27')").Replace('"',"\`$(printf '\x22')"))
} else {
$ansible_cli += "pwsh -encodedcommand $(ConvertTo-Base64 $($Command -join '; '))"
}
}
if( $OneLine ) {
$ansible_cli += '--one-line'
}
$ansible_cli += $Remotes
$ansible_cli += $MoreArgs

$local:expr = $('& "'+$($ansible_cli -join '" "')+'"')
Write-Verbose $expr
$local:SaveConsoleColor = [Console]::ForegroundColor
$env:ANSIBLE_DEPRECATION_WARNINGS='false'
Invoke-Expression $expr | ForEach-Object {
if( -not $OneLine ) { return $_ };
$local:res = $_.Split('|');
$res = [PSCustomObject]([ordered]@{
Machine = $res[0].Trim();
Status = $res[1].Trim();
RC = "$($res[2])".Trim();
Output = "$($res[3])".Trim();
})
if( $res.Status -match '^\w+!:' ) {
[Console]::ForegroundColor = [ConsoleColor]::Red
} else {
[Console]::ForegroundColor = [ConsoleColor]::Yellow
}
$res
}
[Console]::ForegroundColor = $SaveConsoleColor

+ 3
- 0
sys.Linux/Pull-ViaAnsible.ps1 View File

@@ -0,0 +1,3 @@
[CmdletBinding()]param([string[]]$Remotes = 'All')

Invoke-ViaAnsible -Command "git pull" -Remotes:$($Remotes.ToLower())

+ 13
- 0
sys.Linux/Update-ArchOSz.ps1 View File

@@ -0,0 +1,13 @@
param(
[ValidateSet('List','Update','Auto','All')]
[string]$Mode = 'List'
)

$script:yayCli = "cat /run/check.yay.updates/list"
switch( $Mode ){
'Update' { $yayCli = "yay -Syu --needed --ignore docker,linux,linux-api-headers,linux-firmware,linux-headers,zfs-linux" }
'Auto' { $yayCli = "yay -Syu --needed --noconfirm --ignore docker || yay -Syu --needed --ignore docker,linux,linux-api-headers,linux-firmware,linux-headers,zfs-linux --noconfirm" }
'All' { $yayCli = "yay -Syu --needed" }
}

& sh "-c" "$yayCli" -replace '#args',"$args"

+ 10
- 0
sys.Linux/Update-OSz.ps1 View File

@@ -0,0 +1,10 @@
param(
[ValidateSet('List','Update','Auto','All')]
[string]$Mode = 'List'
)

$local:detectedDisistro = cat /etc/os-release | Select-String -Pattern "^ID=" | ForEach-Object { $_ -split '=' | Select-Object -Skip 1 }
switch ($detectedDisistro) {
'arch' { Update-ArchOSz -Mode:$Mode $args }
'ubuntu' { Update-UbuntuOSz -Mode:$Mode $args }
}

+ 14
- 0
sys.Linux/Update-UbuntuOSz.ps1 View File

@@ -0,0 +1,14 @@
param(
[ValidateSet('List','Update','Auto','All')]
[string]$Mode = 'List'
)

$script:aptCli = "echo 'not defined'"
switch( $Mode ){
'List' { }
'Auto' { $aptCli = "sudo apt-get update && sudo apt-get upgrade --auto-remove --assume-yes" }
default { $aptCli = "sudo apt-get update && sudo apt-get upgrade --auto-remove " }
}

& sh "-c" "$aptCli" -replace '#args',"$args"


+ 3
- 0
sys.Linux/Update-ViaAnsible.ps1 View File

@@ -0,0 +1,3 @@
[CmdletBinding()]param([string[]]$Remotes = 'All')

Invoke-ViaAnsible -Command "Update-OSz -Mode Auto" -Remotes:$($Remotes.ToLower())

+ 5
- 0
sys.Linux/ls.ps1 View File

@@ -0,0 +1,5 @@
$local:params = $args -join ' '
if( -not $params ) { $params = '-lah' }

/usr/bin/env ls --color=auto $params


+ 1
- 0
sys.Linux/sranger.ps1 View File

@@ -0,0 +1 @@
Invoke-ExpressionEx -sudo "`$env:TERM='tmux-256color'; `$env:EDITOR='$env:EDITOR'; ranger $args"

+ 6
- 0
sys.Linux/sz-rsync.ps1 View File

@@ -0,0 +1,6 @@
#setopt dotglob
$szSrc="'$($args -join "','")'"
$szSrcCount=$(Invoke-ExpressionEx -sudo "& find $szSrc -type f | wc -l )
Invoke-ExpressionEx -sudo "& rsync --archive --acls --xattrs --human-readable -v $szSrc /szmedia/media/ | pv -lepts $szSrcCount"
#unsetopt dotglob


+ 1
- 0
sys.Linux/txm.ps1 View File

@@ -0,0 +1 @@
tmux set-option mouse $args

+ 35
- 0
sz-df.ps1 View File

@@ -0,0 +1,35 @@
param([ValidateSet('KB','GB','TB')]$SizeUnitName = 'GB')
$local:zpool_cmd = $null
$local:excludeType = ''

$script:SizeUnit = Invoke-Expression "1$SizeUnitName"
$script:SizeRound = 2
$SizeUnit /= 1KB

function NewDataRow{param($Size,$Used,$Available,$Percent,$Source,$FSType,$Target)
[PSCustomObject]@{
"Size$SizeUnitName" = [Math]::Round($Size /$SizeUnit, $SizeRound)
"Used$SizeUnitName" = [Math]::Round($Used /$SizeUnit, $SizeRound)
"Available$SizeUnitName" = [Math]::Round($Available/$SizeUnit, $SizeRound)
'Used%' = [int]($Percent -replace '%$','')
Source = $Source
FSType = $FSType
Target = $Target
}
}

$local:df = @()
& df '--output=size,used,avail,pcent,source,fstype,target' |
Select-Object -Skip 1 | ForEach-Object {
$local:df = $_.Split(' ', [StringSplitOptions]::RemoveEmptyEntries)
NewDataRow $df[0] $df[1] $df[2] $df[3] $df[4] $df[5] $df[6]
} | Where-Object {
-not ($_.FSType -eq 'zfs' -and $_.Source -match '/')
} | Sort-Object -Property Target

#$zpool_cmd = get-command zpool | Where-Object CommandType -eq 'Application' | Select-Object -ExpandProperty Source
#if( $zpool_cmd ) {
# $excludeType = '--exclude-type=zfs'
#}



+ 1
- 0
sz-du.ps1 View File

@@ -0,0 +1 @@
sudo /bin/du --human-readable --max-depth=1 --one-file-system $args | sort --human-numeric-sort --reverse

Loading…
Cancel
Save