Mostrando entradas con la etiqueta script. Mostrar todas las entradas
Mostrando entradas con la etiqueta script. Mostrar todas las entradas

lunes, 8 de julio de 2013

Imprimir en impresora de etiquetas SATO desde PowerShell

Aquí les dejo un pequeño programa que me habilita la impresión desde PowerShell en impresoras de etiquetas SATO. (parte del código salio de http://social.msdn.microsoft.com/Forums/en-US/94967169-a9ee-45db-9c8a-acd6f173680d/rawprinthelper-for-bold-font)...

El archivo PrinterHelper.ps1 es

clear

$src = @'
using System;
using System.IO;
using System.Runtime.InteropServices;

public class RawPrinterHelper
{
 // Structure and API declarions:
 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
 public class DOCINFOA
 {
  [MarshalAs(UnmanagedType.LPStr)]
  public string pDocName;
  [MarshalAs(UnmanagedType.LPStr)]
  public string pOutputFile;
  [MarshalAs(UnmanagedType.LPStr)]
  public string pDataType;
 }

 #region "Imports"
  [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

  [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  public static extern bool ClosePrinter(IntPtr hPrinter);

  [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

  [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  public static extern bool EndDocPrinter(IntPtr hPrinter);

  [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  public static extern bool StartPagePrinter(IntPtr hPrinter);

  [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  public static extern bool EndPagePrinter(IntPtr hPrinter);

  [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
 #endregion


 public  RawPrinterHelper(){}

 // SendBytesToPrinter()
 // When the function is given a printer name and an unmanaged array
 // of bytes, the function sends those bytes to the print queue.
 // Returns true on success, false on failure.
 public  bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
 {
  Int32 dwError = 0, dwWritten = 0;
  IntPtr hPrinter = new IntPtr(0);
  DOCINFOA di = new DOCINFOA();
  bool bSuccess = false; // Assume failure unless you specifically succeed.

  di.pDocName = "My document";
  di.pDataType = "RAW";

  try
  {
   // Open the printer.
   if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
   {
    // Start a document.
    if (StartDocPrinter(hPrinter, 1, di))
    {
     // Start a page.
     if (StartPagePrinter(hPrinter))
     {
      // Write your bytes.
      bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
      EndPagePrinter(hPrinter);
     }
     EndDocPrinter(hPrinter);
    }
    ClosePrinter(hPrinter);
   }
  }
  catch (Exception ex)
  {
   throw (ex);
  }
  // If you did not succeed, GetLastError may give more information
  // about why not.
  if (bSuccess == false)
  {
   dwError = Marshal.GetLastWin32Error();
  }
  return bSuccess;
 }

 public  bool SendStringToPrinter(string szPrinterName, string szString)
 {
  IntPtr pBytes;
  Int32 dwCount;
  szString = reemplazarCaracteres(szString);
  // How many characters are in the string?
  dwCount = szString.Length;
  // Assume that the printer is expecting ANSI text, and then convert
  // the string to ANSI text.
  pBytes = Marshal.StringToCoTaskMemAnsi(szString);
  // Send the converted ANSI string to the printer.
  SendBytesToPrinter(szPrinterName, pBytes, dwCount);
  Marshal.FreeCoTaskMem(pBytes);
  return true;
 }

 private string reemplazarCaracteres(string PrintCommand)
 {
  PrintCommand = PrintCommand.Replace("<STX>", ((char)02).ToString());
  PrintCommand = PrintCommand.Replace("<ETX>", ((char)03).ToString());
  PrintCommand = PrintCommand.Replace("<ESC>", ((char)27).ToString());
  return PrintCommand;
 }
}

'@


Add-Type -TypeDefinition $src -Language CSharpVersion3


$PrinterHelper = new-object RawPrinterHelper



 
Su uso es simple, por ejemplo desde otro archivo ps1 hacemos

. .\PrinterHelper.ps1

$PrinterHelper.SendStringToPrinter('\\PROG03\sato cg408', '<STX><ESC>A1002400880<ESC>A<ESC>H0030<ESC>V0030<ESC>BT101030100<ESC>BW03100*555*<ESC>H0030<ESC>V0133<ESC>WB0555<ESC>Q1<ESC>Z<ETX>') 


Con lo que estaríamos imprimiendo una etiqueta con el valor 555 en code39, imprimiendo el número 555 debajo.
Esta misma clase se puede usar para imprimir desde .Net (con c#)

jueves, 23 de mayo de 2013

Powershell y passwords

EnPower Shell a veces tenemos la necesidad de manejar claves, para lo que tenemos que por ejemplo para leer una clave y que aparezcan los típicos asteriscos, cada vez que pulsamos una tecla hacemos:

$psw = Read-Host "Ingrese la clave" -AsSecureString


Donde, con  "-AsSecureString" le indicamos que guarde lo ingresado en un string seguro. Bueno, ahora si ponemos

Write-Host $psw


vemos que la respuesta es

System.Security.SecureString


Lo cual nos deja un poco perplejos, para ver el valor ingresado debemos hacer

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($psw)

Write-Host [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)


...lo que nos mostrará la clave ingresada por el usuario.

martes, 7 de mayo de 2013

bat2sh

Cómo convertir fácilmente un archivo bat de windows en un sh para linux.

Para eso comencé a crear este pequeño script en perl (mejorable por cierto) para automatizar un poco esta tarea. Dejo el código en su estado actual aquí abajo, pueden encontrar la última versión (y participar en ella para mejorarla) en éste github.


#!/usr/bin/perl

sub cat_ {
local *F;
open F, $_[0] or return;
my @l = ;
wantarray() ? @l : join '', @l
}
sub output {
my $f = shift;
local *F;
open F, ">$f" or die "output in file $f failed: $!\n";
print F foreach @_; 1
}
  
if (@ARGV != 2) {
die "Usage: bat2sh.pl <input .bat file> <output .sh file>\n";
}
my @contents = cat_($ARGV[0]);

foreach my $line (@contents) {
# rem -> #
$line =~ s/rem /# /i;
# move -> mv
$line =~ s/^\s*move\b/mv/;
# del -> rm
$line =~ s/^\s*del\b/rm/;
# dos eol to unix eol
$line =~ s/\r\n/\n/;
# set
$line =~ s/^\s*set //i;
# \ -> /
$line =~ s/\\/\//g;
# copy -> cp
if ($line =~ m/^\s*copy\b/ig){
$line =~ s/^\s*copy\b/cp/ig;
$line =~ s/\n//; #remove eol
$line .= " ./\n";
}
# %varName% -> $varName
while ($line =~ m/(%\w*%)/ig){
my $word = "\$" . substr($1, 1, -1);
$line =~ s/(%\w*%)/$word/ig;
}
# if ERRORLEVEL 1 goto ERROR -> if [ "$?" = "1" ]; then sub_error fi
if ($line =~ m/^\s*if\s*ERRORLEVEL\s*1\s*goto\s*(\w*)\s*$/ig){
$line = "if [ \"\$?\" = \"1\" ]; then \n exit 1\nfi\n";
}
}
my $line = "#!/bin/sh\n\n\n";
unshift @contents, $line;

output $ARGV[1], @contents;

martes, 26 de febrero de 2013

Tips Graphite


Eliminar gráficas

Si queremos eliminar métricas realizadas en nuestro graphite, es muy fácil...
Los datos de las gráficas quedan en
 
/opt/graphite/storage/whisper/
 
...De donde los podemos borrar directamente.

Validar los esquemas

Graphite nos dá una herramienta para validar que nuestros archivos de schema estén bien formados, la misma se encuentra en
 
/opt/graphite/bin/validate-storage-schemas.py

Resulta muy útil para estar seguros de no tener errores en nuestros schemas.

Resetear Carbon

Es necesario hacer un restart al Carbon después de haber cambiado los archivos conf
/opt/graphite/bin/carbon-cache.py start

Sincronizar database

sudo /opt/graphite/webapp/graphite/python manage.py syncdb


jueves, 10 de enero de 2013

Mouse click en PowerShell

Tuve que recorrer media internet para encontrar finalmente como hacer un click del mouse con  Power Shell sin tener que usar otros programas externos. Así que acá finalmente pude armar una función que hace clicks del mouse en la posición indicada de la pantalla...

# Ejecuta un click del mouse
function MouseClick ($Button = "left", $x, $y, $cant = 1){
    $signature = @'
          [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
          public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@
    [Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y);
    $SendMouseClick = Add-Type -memberDefinition $signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru 
    for ($i = 1; $i -le $cant; $i++){
        if($Button -eq "left"){
            $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
            $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
        }
        if($Button -eq "right"){
            $SendMouseClick::mouse_event(0x00000008, 0, 0, 0, 0);
            $SendMouseClick::mouse_event(0x00000010, 0, 0, 0, 0);
        }
        if($Button -eq "middle"){
            $SendMouseClick::mouse_event(0x00000020, 0, 0, 0, 0);
            $SendMouseClick::mouse_event(0x00000040, 0, 0, 0, 0);
        }
    }
}



lunes, 7 de enero de 2013

Power Shell - ¿Cómo llamar a una función que está en otro script?

Bueno, acá explico como llamar desde un script PowerShell (ps1) a una función que se encuentra en otro script...
Supongamos que tenemos los script funciones.ps1 y principal.ps1, siendo:

funciones.ps1:
Function test(){
    Write-Host "Dentro de la funcion"
}


Para llamar a la funcion test desde principal.ps1 se hace
. .\funciones.ps1 # acá incluyo al script funciones.ps1
                  # notar que hay un espacio entre . y .\funciones.ps1

#luego llamo a la función
test


En el ejemplo estoy llamando al script de forma relativa, suponiendo que están en el mismo directorio, si no fuera así habría que hacer algo tipo ". C:\<path del script funciones.ps1>\funciones.ps1...

Espero que les sea de utilidad....