tutorial script learn ise ejemplos commands comandos windows powershell scripting

windows - learn - script powershell ejemplos



Scripts de PowerShell que todo desarrollador debe saber (4)

Cada vez que vea algo con las mayúsculas adecuadas, es una indicación de que he utilizado la finalización de TAB. Debería saber qué cosas completará PS para usted, es bastante bueno en V2.

Cada vez que veas alias en minúscula, es algo que escribí de memoria. Deberías memorizarlo también.

# grep example - find all using statements dir -r -fil *cs | ss using # advanced version dir -fil *cs -r | ss ''^using[^/(]+'' | gpv line | sort -unique # figure out how to query for drive free space (emphasis on "figure out" -- I can never remember things like this) gcm *drive* help Get-PSDrive -full Get-PSDrive | gm # now use it Get-PSDrive | ? { $_.free -gt 1gb } # pretend mscorlib.dll is an assembly you''re developing and want to do some ad-hoc testing on $system = [system.reflection.assembly]::LoadFile("c:/blah/.../mscorlib.dll") $system | gm $types = $a.GetTypes() $types | gm $types | ? { $_.ispublic -and $_.basetype -eq [system.object] } | sort name $sbType = $types | ? { $_.name -eq "StringBuilder" } # now that we''ve loaded the assembly, we could have also done: # $sbType = [system.text.stringbuilder] # but we may not have known it was in the Text namespace $sb = new-object $sbType.FullName $sb | gm $sb.Append("asdf") $sb.Append("jkl;") $sb.ToString()

Windows PowerShell ya ha pasado bastante tiempo. En comparación con el buen shell de Windows, es mucho más poderoso. ¿Hay alguna secuencia de comandos que use para acelerar y simplificar su trabajo diario como desarrollador? Si puedes hacer magia con PowerShell -> por favor, ¡compártelo con nosotros!

Actualización No es realmente una secuencia de comandos, pero también son muy útiles las extensiones de comunidad de PowerShell . El paquete contiene una gran cantidad de nuevos cmdlets y modificaciones de PowerShell.


No es un script, pero en general es útil saber cuándo puede acortar los parámetros, tanto por nombre como por posición.

Por nombre, PowerShell solo necesita lo suficiente como para reducirlo a uno. Por ejemplo, gci -r funciona pero gci -f puede ser -filter o -force .

Los valores especificados sin una etiqueta de parámetro se aplican posicionalmente. Entonces, si quiere especificar -filter , puede hacer esto:

gci -r -fil *.cs

O proporcionar posicionalmente como -path por lo que también puede especificar -filter positionally:

gci -r . *.cs


Puse un conjunto de scripts para trabajar con Subversion en la línea de comando. La mayoría de ellos solo usa la opción --xml para poner diversa información en forma de objeto. Aquí hay un par de ejemplos:

function Get-SvnStatus( [string[]] $Path = ".", [string] $Filter = "^(?!unversioned|normal|external)", [switch] $NoFormat ) { # powershell chokes on "wc-status" and doesn''t like two definitions of "item" [xml]$status = ( ( Invoke-Expression "svn status $( $Path -join '','' ) --xml" ) -replace "wc-status", "svnstatus" ) ` -replace "item=", "itemstatus=" $statusObjects = $status.status.target | Foreach-Object { $_.entry } | Where-Object { $_.svnstatus.itemstatus -match $Filter } | Foreach-Object { $_ | Select-Object @{ Name = "Status"; Expression = { $_.svnstatus.itemstatus } }, @{ Name = "Path"; Expression = { Join-Path ( Get-Location ) $_.path } } } | Sort-Object Status, Path if ( $NoFormat ) { $statusObjects } else { $statusObjects | Format-Table -AutoSize } } function Get-SvnLog( [string] $Path = ".", [int] $Revision, [int] $Limit = -1, [switch] $Verbose, [switch] $NoFormat ) { $revisionString = "" $limitString = "" $verboseString = "" if ( $Revision ) { $revisionString = "--revision $Revision" } if ( $Limit -ne -1 ) { $limitString = "--limit $Limit" } if ( $Verbose ) { $verboseString = "--verbose" } [xml]$log = Invoke-Expression "svn log $( $path -join '','' ) --xml $revisionString $limitString $verboseString" $logObjects = $log.log.logentry | Foreach-Object { $logEntry = $_ $logEntry | Select-Object ` @{ Name = "Revision"; Expression = { [int]$logEntry.revision } }, @{ Name = "Author"; Expression = { $logEntry.author } }, @{ Name = "Date"; Expression = { if ( $NoFormat ) { [datetime]$logEntry.date } else { "{0:dd/MM/yyyy hh:mm:ss}" -f [datetime]$logEntry.date } } }, @{ Name = "Message"; Expression = { $logEntry.msg } } | Foreach-Object { # add the changed path information if the $Verbose parameter has been specified if ( $Verbose ) { $_ | Select-Object Revision, Author, Date, Message, @{ Name = "ChangedPaths"; Expression = { $paths = $logEntry.paths.path | Foreach-Object { $_ | Select-Object ` @{ Name = "Change"; Expression = { switch ( $_.action ) { "A" { "added" } "D" { "deleted" } "M" { "modified" } "R" { "replaced" } default { $_.action } } } }, @{ Name = "Path"; Expression = { $_."#text" } } } if ( $NoFormat ) { $paths } else { ( $paths | Sort-Object Change | Format-Table -AutoSize | Out-String ).Trim() } } } } else { $_ } } } if ( $NoFormat ) { $logObjects } else { $logObjects | Format-List } }

Tengo estos alias a svns y svnl, respectivamente. Hablo de algunos otros aquí .


Utilizo este todo el tiempo porque la búsqueda del contenido de archivo del Explorador de Windows nunca funciona para mí:

Get-ChildItem -Recurse -Filter *.extension | Select-String -List somestring | Format-Table filename,linenumber -AutoSize

Simplemente reemplace "extensión" con la extensión de archivo del tipo de archivo que le interesa (o elimine por completo el parámetro -Filter) y reemplace "somestring" con el texto que desea encontrar en el archivo.