elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [APORTE] [PowerShell] Crear un archivo dummy de forma fácil e interactiva
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] [PowerShell] Crear un archivo dummy de forma fácil e interactiva  (Leído 222 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.892



Ver Perfil
[APORTE] [PowerShell] Crear un archivo dummy de forma fácil e interactiva
« en: Ayer a las 09:36 »

El siguiente script, desarrollado de manera híbrida en PowerShell y VisualBasic.NET, permite crear de manera interactiva un archivo dummy (vacío o con contenido aleatorio) con un tamaño determinado.

La creación de un archivo dummy resulta útil para realizar pruebas de escritura en discos, o para sobrescribir el espacio en blanco del disco dificultando o imposibilitando la recuperación de datos, por ejemplo, generando un archivo dummy (con datos aleatorios) que ocupe todo el espacio disponible en el disco.

Al ejecutar este script, aparecerá el siguiente formulario que permitirá seleccionar la ubicación del archivo a crear y configurar las opciones disponibles:



Este es el procedimiento completo:



La interfaz gráfica y el resto del procedimiento está contenido en un script de PowerShell de 31 kilobytes, ideal para incluirlo como herramienta adicional en entornos de pruebas y recuperación, sin dependencias adicionales ...más allá de PowerShell y .NET Framework.



Así se verá un archivo dummy en un editor hexadecimal:



Y así se verá el archivo dummy rellenado con datos aleatorios:





CreateDummyFile.ps1
Código
  1. <#PSScriptInfo
  2. .VERSION 1.0
  3. .GUID 26C67DF9-0F1E-4806-9D23-586DFBDECF88
  4. .AUTHOR ElektroStudios
  5. .COMPANYNAME ElektroStudios
  6. .COPYRIGHT ElektroStudios © 2025
  7. #>
  8.  
  9. $vbCode = @'
  10. #Region " Option Statements "
  11.  
  12. Option Strict On
  13. Option Explicit On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Imports "
  19.  
  20. Imports Microsoft.VisualBasic
  21.  
  22. Imports System
  23. Imports System.Collections.Generic
  24. Imports System.ComponentModel
  25. Imports System.Diagnostics
  26. Imports System.Diagnostics.CodeAnalysis
  27. Imports System.Drawing
  28. Imports System.Drawing.Design
  29. Imports System.Globalization
  30. Imports System.IO
  31. Imports System.Linq
  32. Imports System.Reflection
  33. Imports System.Runtime.CompilerServices
  34. Imports System.Runtime.InteropServices
  35. Imports System.Security
  36. Imports System.Text
  37. Imports System.Windows.Forms
  38. Imports System.Xml
  39. Imports System.Xml.Serialization
  40.  
  41. Imports DevCase.Core.IO.DigitalInformation
  42. Imports DevCase.Core.IO.FileSystem
  43. Imports DevCase.Runtime.TypeConverters
  44. Imports DevCase.Win32
  45. Imports DevCase.Win32.Enums
  46.  
  47. #End Region
  48.  
  49. #Region " CreateDummyFileOptionsForm "
  50.  
  51. Public NotInheritable Class CreateDummyFileOptionsForm : Inherits System.Windows.Forms.Form
  52.  
  53.    Public Sub New()
  54.        Me.InitializeComponent()
  55.    End Sub
  56.  
  57.    'Form overrides dispose to clean up the component list.
  58.    <System.Diagnostics.DebuggerNonUserCode()>
  59.    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
  60.        Try
  61.            If disposing AndAlso components IsNot Nothing Then
  62.                components.Dispose()
  63.            End If
  64.        Finally
  65.            MyBase.Dispose(disposing)
  66.        End Try
  67.    End Sub
  68.  
  69.    'Required by the Windows Form Designer
  70.    Private components As System.ComponentModel.IContainer
  71.    Friend WithEvents PropertyGrid1 As New PropertyGrid
  72.    Friend WithEvents ButtonCancel As Button
  73.    Friend WithEvents ButtonOk As Button
  74.    Friend WithEvents TableLayoutPanel1 As TableLayoutPanel
  75.    Friend WithEvents Panel1 As Panel
  76.  
  77.    'NOTE: The following procedure is required by the Windows Form Designer
  78.    'It can be modified using the Windows Form Designer.  
  79.    'Do not modify it using the code editor.
  80.    <System.Diagnostics.DebuggerStepThrough()>
  81.    Private Sub InitializeComponent()
  82.        Me.PropertyGrid1 = New System.Windows.Forms.PropertyGrid()
  83.        Me.ButtonCancel = New System.Windows.Forms.Button()
  84.        Me.ButtonOk = New System.Windows.Forms.Button()
  85.        Me.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel()
  86.        Me.Panel1 = New System.Windows.Forms.Panel()
  87.        Me.TableLayoutPanel1.SuspendLayout()
  88.        Me.Panel1.SuspendLayout()
  89.        Me.SuspendLayout()
  90.        '
  91.        'PropertyGrid1
  92.        '
  93.        Me.PropertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill
  94.        Me.PropertyGrid1.Location = New System.Drawing.Point(3, 4)
  95.        Me.PropertyGrid1.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
  96.        Me.PropertyGrid1.Name = "PropertyGrid1"
  97.        Me.PropertyGrid1.PropertySort = System.Windows.Forms.PropertySort.NoSort
  98.        Me.PropertyGrid1.Size = New System.Drawing.Size(733, 157)
  99.        Me.PropertyGrid1.TabIndex = 0
  100.        Me.PropertyGrid1.ToolbarVisible = False
  101.        '
  102.        'ButtonCancel
  103.        '
  104.        Me.ButtonCancel.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
  105.        Me.ButtonCancel.Location = New System.Drawing.Point(624, 6)
  106.        Me.ButtonCancel.Name = "ButtonCancel"
  107.        Me.ButtonCancel.Size = New System.Drawing.Size(100, 40)
  108.        Me.ButtonCancel.TabIndex = 1
  109.        Me.ButtonCancel.Text = "Cancel"
  110.        Me.ButtonCancel.UseVisualStyleBackColor = True
  111.        '
  112.        'ButtonOk
  113.        '
  114.        Me.ButtonOk.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
  115.        Me.ButtonOk.Location = New System.Drawing.Point(518, 6)
  116.        Me.ButtonOk.Name = "ButtonOk"
  117.        Me.ButtonOk.Size = New System.Drawing.Size(100, 40)
  118.        Me.ButtonOk.TabIndex = 2
  119.        Me.ButtonOk.Text = "Ok"
  120.        Me.ButtonOk.UseVisualStyleBackColor = True
  121.        '
  122.        'TableLayoutPanel1
  123.        '
  124.        Me.TableLayoutPanel1.ColumnCount = 1
  125.        Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
  126.        Me.TableLayoutPanel1.Controls.Add(Me.Panel1, 0, 1)
  127.        Me.TableLayoutPanel1.Controls.Add(Me.PropertyGrid1, 0, 0)
  128.        Me.TableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill
  129.        Me.TableLayoutPanel1.Location = New System.Drawing.Point(0, 0)
  130.        Me.TableLayoutPanel1.Name = "TableLayoutPanel1"
  131.        Me.TableLayoutPanel1.RowCount = 2
  132.        Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 73.17073!))
  133.        Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 26.82927!))
  134.        Me.TableLayoutPanel1.Size = New System.Drawing.Size(739, 226)
  135.        Me.TableLayoutPanel1.TabIndex = 3
  136.        '
  137.        'Panel1
  138.        '
  139.        Me.Panel1.Controls.Add(Me.ButtonOk)
  140.        Me.Panel1.Controls.Add(Me.ButtonCancel)
  141.        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
  142.        Me.Panel1.Location = New System.Drawing.Point(3, 168)
  143.        Me.Panel1.Name = "Panel1"
  144.        Me.Panel1.Size = New System.Drawing.Size(733, 55)
  145.        Me.Panel1.TabIndex = 4
  146.        '
  147.        'CreateDummyFileOptionsForm
  148.        '
  149.        Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 17.0!)
  150.        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
  151.        Me.ClientSize = New System.Drawing.Size(739, 226)
  152.        Me.Controls.Add(Me.TableLayoutPanel1)
  153.        Me.Font = New System.Drawing.Font("Segoe UI", 10.0!)
  154.        Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
  155.        Me.MaximizeBox = False
  156.        Me.Name = "CreateDummyFileOptionsForm"
  157.        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
  158.        Me.Text = "Create Dummy File Options"
  159.        Me.TableLayoutPanel1.ResumeLayout(False)
  160.        Me.Panel1.ResumeLayout(False)
  161.        Me.ResumeLayout(False)
  162.  
  163.    End Sub
  164.  
  165.    Public Property DummyFileOptions As New DummyFileOptions
  166.  
  167.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  168.  
  169.        Me.PropertyGrid1.SelectedObject = Me.DummyFileOptions
  170.        DevCase.Extensions.PropertyGridExtensions.SetSplitterPosition(Me.PropertyGrid1, 145)
  171.        Me.MinimumSize = Me.Size
  172.        Me.MaximumSize = New Size(3840, Me.Height)
  173.    End Sub
  174.  
  175.    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles ButtonCancel.Click
  176.        Me.DialogResult = DialogResult.Cancel
  177.        Me.Close()
  178.    End Sub
  179.  
  180.    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles ButtonOk.Click
  181.        Me.DialogResult = DialogResult.OK
  182.        Me.Close()
  183.    End Sub
  184.  
  185. End Class
  186.  
  187. #End Region
  188.  
  189. #Region " DummyFileOptions "
  190.  
  191. Public NotInheritable Class DummyFileOptions
  192.  
  193.    <Browsable(True)>
  194.    <Editor(GetType(SaveFileNameEditor), GetType(UITypeEditor))>
  195.    <DisplayName("File Path")>
  196.    <Description("File path where to create the dummy file.")>
  197.    Public Property FilePath As String = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "File.dummy")
  198.  
  199.    <TypeConverter(GetType(FileSizeConverter))>
  200.    <DisplayName("File Size")>
  201.    <Description("Size of the dummy file.")>
  202.    Public Property FileSize As New FileSize(1, DigitalStorageUnits.Megabyte)
  203.  
  204.    <Browsable(False)>
  205.    Public ReadOnly Property FileSizeBytes As ULong
  206.        Get
  207.            Return CULng(Me.FileSize.Size(DigitalStorageUnits.Byte))
  208.        End Get
  209.    End Property
  210.  
  211.    <TypeConverter(GetType(FileSizeConverter))>
  212.    <DisplayName("Buffer Size")>
  213.    <Description("Size of the buffer used to write the dummy file.")>
  214.    Public Property BufferSize As New FileSize(4, DigitalStorageUnits.Megabyte)
  215.  
  216.    <Browsable(False)>
  217.    Public ReadOnly Property BufferSizeBytes As Integer
  218.        Get
  219.            Return CInt(Me.BufferSize.Size(DigitalStorageUnits.Byte))
  220.        End Get
  221.    End Property
  222.  
  223.    <DisplayName("Use Random Data")>
  224.    <Description("If True, uses random bytes to fill the dummy file content; othewise, fills the dummy file with zero bytes.")>
  225.    Public Property UseRandomData As Boolean = False
  226.  
  227. End Class
  228.  
  229. #End Region
  230.  
  231. #Region " SaveFileNameEditor "
  232.  
  233. Public NotInheritable Class SaveFileNameEditor : Inherits UITypeEditor
  234.  
  235.    Public Overrides Function GetEditStyle(context As ITypeDescriptorContext) As UITypeEditorEditStyle
  236.        Return UITypeEditorEditStyle.Modal
  237.    End Function
  238.  
  239.    Public Overrides Function EditValue(context As ITypeDescriptorContext, provider As IServiceProvider, value As Object) As Object
  240.        If context Is Nothing OrElse context.Instance Is Nothing OrElse provider Is Nothing Then
  241.            Return MyBase.EditValue(context, provider, value)
  242.        End If
  243.  
  244.        Using saveFileDialog As New SaveFileDialog()
  245.            If value IsNot Nothing Then
  246.                saveFileDialog.FileName = value.ToString()
  247.            End If
  248.  
  249.            saveFileDialog.Title = "Select a location to save the dummy file"
  250.            saveFileDialog.Filter = "All files (*.*)|*.*"
  251.            saveFileDialog.FileName = "File.dummy"
  252.            If saveFileDialog.ShowDialog() = DialogResult.OK Then
  253.                value = saveFileDialog.FileName
  254.            End If
  255.        End Using
  256.  
  257.        Return value
  258.    End Function
  259. End Class
  260.  
  261. #End Region
  262.  
  263. #Region " NativeMethods "
  264.  
  265. Namespace DevCase.Win32.NativeMethods
  266.  
  267.    <HideModuleName>
  268.    <SuppressUnmanagedCodeSecurity>
  269.    <SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification:="Required to migrate this code to .NET Core")>
  270.    <SuppressMessage("Interoperability", "CA1401:P/Invokes should not be visible", Justification:="")>
  271.    Public Module ShlwApi
  272.  
  273. #Region " ShlwApi.dll "
  274.  
  275.        <DllImport("ShlwApi.dll", SetLastError:=True, ExactSpelling:=True, CharSet:=CharSet.Ansi, BestFitMapping:=False, ThrowOnUnmappableChar:=True)>
  276.        Public Function StrFormatByteSize64A(number As ULong,
  277.                                            buffer As StringBuilder,
  278.                                            bufferSize As UInteger
  279.        ) As IntPtr
  280.        End Function
  281.  
  282.        <DllImport("ShlwApi.dll", SetLastError:=False, ExactSpelling:=True, CharSet:=CharSet.Unicode)>
  283.        Public Function StrFormatByteSizeEx(number As ULong,
  284.                                            flags As StrFormatByteSizeFlags,
  285.                                            buffer As StringBuilder,
  286.                                            bufferSize As UInteger
  287.        ) As Integer ' HResult
  288.        End Function
  289.  
  290. #End Region
  291.  
  292.    End Module
  293.  
  294. End Namespace
  295.  
  296. #End Region
  297.  
  298. #Region " StrFormatByteSizeFlags "
  299.  
  300. Namespace DevCase.Win32.Enums
  301.  
  302.    Public Enum StrFormatByteSizeFlags
  303.        RoundToNearest = 1
  304.        Truncate = 2
  305.    End Enum
  306.  
  307. End Namespace
  308.  
  309. #End Region
  310.  
  311. #Region " Size Units "
  312.  
  313. Namespace DevCase.Core.IO.DigitalInformation
  314.  
  315.    Public Enum DigitalStorageUnits As Long
  316.        [Byte] = CLng(2 ^ 0)
  317.        Kilobyte = CLng(2 ^ 10)
  318.        Megabyte = CLng(2 ^ 20)
  319.        Gigabyte = CLng(2 ^ 30)
  320.        Terabyte = CLng(2 ^ 40)
  321.        Petabyte = CLng(2 ^ 50)
  322.        Exabyte = CLng(2 ^ 60)
  323.    End Enum
  324.  
  325. End Namespace
  326.  
  327. #End Region
  328.  
  329. #Region " Filesize "
  330.  
  331. Namespace DevCase.Core.IO.FileSystem
  332.  
  333.    Public NotInheritable Class FileSize
  334.  
  335. #Region " Private Fields "
  336.  
  337.        Private ReadOnly bytesB As Double
  338.  
  339. #End Region
  340.  
  341. #Region " Properties "
  342.  
  343.        Public ReadOnly Property Size(sizeUnit As DigitalStorageUnits) As Double
  344.            Get
  345.                Return Convert(size:=Me.bytesB, fromUnit:=DigitalStorageUnits.Byte, toUnit:=sizeUnit)
  346.            End Get
  347.        End Property
  348.  
  349.        Public ReadOnly Property Size(sizeUnit As DigitalStorageUnits, decimalPrecision As Integer, Optional numberFormatInfo As NumberFormatInfo = Nothing) As String
  350.            Get
  351.                If numberFormatInfo Is Nothing Then
  352.                    numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
  353.                End If
  354.                Return Me.Size(sizeUnit).ToString(String.Format("N{0}", decimalPrecision), numberFormatInfo)
  355.            End Get
  356.        End Property
  357.  
  358.        Public Property SizeRounded As Double
  359.  
  360.        Public ReadOnly Property SizeRounded(decimalPrecision As Integer, Optional numberFormatInfo As NumberFormatInfo = Nothing) As String
  361.            Get
  362.                If numberFormatInfo Is Nothing Then
  363.                    numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
  364.                End If
  365.                Return Me.SizeRounded.ToString(String.Format("N{0}", decimalPrecision), numberFormatInfo)
  366.            End Get
  367.        End Property
  368.  
  369.        Public Property SizeUnit As DigitalStorageUnits
  370.        Public Property SizeUnitNameShort As String
  371.        Public Property SizeUnitNameLong As String
  372.  
  373. #End Region
  374.  
  375. #Region " Constructors "
  376.  
  377.        Private Sub New()
  378.        End Sub
  379.  
  380.        <DebuggerStepThrough>
  381.        Public Sub New(size As Double, sizeUnit As DigitalStorageUnits)
  382.  
  383.            Me.bytesB = System.Convert.ToDouble(size * sizeUnit)
  384.  
  385.            Select Case System.Math.Abs(Me.bytesB)
  386.  
  387.                Case Is >= DigitalStorageUnits.Petabyte
  388.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Petabyte
  389.                    Me.SizeUnit = DigitalStorageUnits.Petabyte
  390.                    Me.SizeUnitNameShort = "PB"
  391.                    Me.SizeUnitNameLong = "PetaBytes"
  392.  
  393.                Case Is >= DigitalStorageUnits.Terabyte
  394.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Terabyte
  395.                    Me.SizeUnit = DigitalStorageUnits.Terabyte
  396.                    Me.SizeUnitNameShort = "TB"
  397.                    Me.SizeUnitNameLong = "TeraBytes"
  398.  
  399.                Case Is >= DigitalStorageUnits.Gigabyte
  400.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Gigabyte
  401.                    Me.SizeUnit = DigitalStorageUnits.Gigabyte
  402.                    Me.SizeUnitNameShort = "GB"
  403.                    Me.SizeUnitNameLong = "GigaBytes"
  404.  
  405.                Case Is >= DigitalStorageUnits.Megabyte
  406.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Megabyte
  407.                    Me.SizeUnit = DigitalStorageUnits.Megabyte
  408.                    Me.SizeUnitNameShort = "MB"
  409.                    Me.SizeUnitNameLong = "MegaBytes"
  410.  
  411.                Case Is >= DigitalStorageUnits.Kilobyte
  412.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Kilobyte
  413.                    Me.SizeUnit = DigitalStorageUnits.Kilobyte
  414.                    Me.SizeUnitNameShort = "KB"
  415.                    Me.SizeUnitNameLong = "KiloBytes"
  416.  
  417.                Case Is >= DigitalStorageUnits.Byte, Is = 0
  418.                    Me.SizeRounded = Me.bytesB / DigitalStorageUnits.Byte
  419.                    Me.SizeUnit = DigitalStorageUnits.Byte
  420.                    Me.SizeUnitNameShort = "Bytes"
  421.                    Me.SizeUnitNameLong = "Bytes"
  422.            End Select
  423.  
  424.        End Sub
  425.  
  426. #End Region
  427.  
  428. #Region " Public Methods "
  429.  
  430.        Public Overrides Function ToString() As String
  431.            Return Me.ToString(CultureInfo.InvariantCulture.NumberFormat)
  432.        End Function
  433.  
  434.        Public Overloads Function ToString(provider As IFormatProvider) As String
  435.            Return If(Me.SizeUnit = DigitalStorageUnits.Byte,
  436.                String.Format(provider, "{0:0.##} {1}", System.Math.Floor(Me.SizeRounded * 100) / 100, Me.SizeUnitNameShort),
  437.                String.Format(provider, "{0:0.00} {1}", System.Math.Floor(Me.SizeRounded * 100) / 100, Me.SizeUnitNameShort))
  438.        End Function
  439.  
  440.        Public Function ToStringFormatByteSize(flags As StrFormatByteSizeFlags) As String
  441.  
  442.            Dim buffer As New StringBuilder(8, 16)
  443.            Dim result As Integer = NativeMethods.StrFormatByteSizeEx(CULng(Me.bytesB), flags, buffer, 16) ' HRESULT
  444.            If result <> 0 Then
  445.                Marshal.ThrowExceptionForHR(result)
  446.            End If
  447.  
  448.            Return buffer.ToString()
  449.        End Function
  450.  
  451. #End Region
  452.  
  453. #Region " Private Methods "
  454.  
  455.        <DebuggerStepThrough>
  456.        Private Shared Function Convert(size As Double,
  457.                                 fromUnit As DigitalStorageUnits,
  458.                                 toUnit As DigitalStorageUnits) As Double
  459.  
  460.            Dim bytes As Double = If(fromUnit = DigitalStorageUnits.Byte, size, System.Convert.ToDouble(size * fromUnit))
  461.  
  462.            If toUnit < fromUnit Then
  463.                Select Case toUnit
  464.                    Case DigitalStorageUnits.Byte
  465.                        Return bytes
  466.  
  467.                    Case DigitalStorageUnits.Kilobyte
  468.                        Return bytes / DigitalStorageUnits.Kilobyte
  469.  
  470.                    Case DigitalStorageUnits.Megabyte
  471.                        Return bytes / DigitalStorageUnits.Megabyte
  472.  
  473.                    Case DigitalStorageUnits.Gigabyte
  474.                        Return bytes / DigitalStorageUnits.Gigabyte
  475.  
  476.                    Case DigitalStorageUnits.Terabyte
  477.                        Return bytes / DigitalStorageUnits.Terabyte
  478.  
  479.                    Case DigitalStorageUnits.Petabyte
  480.                        Return bytes / DigitalStorageUnits.Petabyte
  481.  
  482.                    Case Else
  483.                        Throw New InvalidEnumArgumentException(argumentName:="toUnit", invalidValue:=CInt(toUnit),
  484.                                                               enumClass:=GetType(DigitalStorageUnits))
  485.                End Select
  486.  
  487.            ElseIf toUnit > fromUnit Then
  488.                Select Case toUnit
  489.  
  490.                    Case DigitalStorageUnits.Byte
  491.                        Return bytes
  492.  
  493.                    Case DigitalStorageUnits.Kilobyte
  494.                        Return bytes * DigitalStorageUnits.Kilobyte / (DigitalStorageUnits.Kilobyte ^ 2)
  495.  
  496.                    Case DigitalStorageUnits.Megabyte
  497.                        Return bytes * DigitalStorageUnits.Megabyte / (DigitalStorageUnits.Megabyte ^ 2)
  498.  
  499.                    Case DigitalStorageUnits.Gigabyte
  500.                        Return bytes * DigitalStorageUnits.Gigabyte / (DigitalStorageUnits.Gigabyte ^ 2)
  501.  
  502.                    Case DigitalStorageUnits.Terabyte
  503.                        Return bytes * DigitalStorageUnits.Terabyte / (DigitalStorageUnits.Terabyte ^ 2)
  504.  
  505.                    Case DigitalStorageUnits.Petabyte
  506.                        Return bytes * DigitalStorageUnits.Petabyte / (DigitalStorageUnits.Petabyte ^ 2)
  507.  
  508.                    Case Else
  509.                        Throw New InvalidEnumArgumentException(argumentName:="toUnit", invalidValue:=CInt(toUnit),
  510.                                                               enumClass:=GetType(DigitalStorageUnits))
  511.                End Select
  512.  
  513.            Else ' If toUnit = fromUnit
  514.                Return bytes
  515.  
  516.            End If
  517.        End Function
  518.  
  519. #End Region
  520.  
  521.    End Class
  522.  
  523. End Namespace
  524.  
  525. #End Region
  526.  
  527. #Region " FileSizeConverter "
  528.  
  529. Namespace DevCase.Runtime.TypeConverters
  530.  
  531.    Public Class FileSizeConverter : Inherits TypeConverter
  532.  
  533. #Region " Private Fields "
  534.  
  535.        Private ReadOnly sizeUnitsDictionary As Dictionary(Of String(), ULong)
  536.  
  537. #End Region
  538.  
  539. #Region " Constructors "
  540.  
  541.        Public Sub New()
  542.            Me.sizeUnitsDictionary = New Dictionary(Of String(), ULong)(StringComparison.OrdinalIgnoreCase) From {
  543.                {{"b", "byte", "bytes"}, 1UL},
  544.                {{"KB", "kilo", "kilos", "kilobyte", "kilobytes", "kilo byte", "kilo bytes"}, 1024UL},
  545.                {{"MB", "mega", "megas", "megabyte", "megabytes", "mega byte", "mega bytes"}, CULng(1024UL ^ 2UL)},
  546.                {{"GB", "giga", "gigas", "gigabyte", "gigabytes", "giga byte", "giga bytes"}, CULng(1024UL ^ 3UL)},
  547.                {{"TB", "tera", "teras", "terabyte", "terabytes", "tera byte", "tera bytes"}, CULng(1024UL ^ 4UL)},
  548.                {{"PB", "peta", "petas", "petabyte", "petabytes", "peta byte", "peta bytes"}, CULng(1024UL ^ 5UL)},
  549.                {{"EB", "exa", "exas", "exabyte", "exabytes", "exa byte", "exa bytes"}, CULng(1024UL ^ 6UL)}
  550.            }
  551.        End Sub
  552.  
  553. #End Region
  554.  
  555. #Region " Public Methods "
  556.  
  557.        Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  558.  
  559.            Return sourceType Is GetType(String) OrElse
  560.                   MyBase.CanConvertFrom(context, sourceType)
  561.        End Function
  562.  
  563.        Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  564.  
  565.            Return destinationType Is GetType(ULong) OrElse
  566.                   destinationType Is GetType(String) OrElse
  567.                   MyBase.CanConvertTo(context, destinationType)
  568.        End Function
  569.  
  570.        <DebuggerStepThrough>
  571.        Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object
  572.  
  573.            If TypeOf value Is String Then
  574.                Dim strValue As String = DirectCast(value, String)
  575.                If strValue.Contains("("c) Then
  576.                    strValue = strValue.Substring(0, strValue.IndexOf("("c))
  577.                End If
  578.                Dim bytes As ULong
  579.                If ULong.TryParse(strValue, bytes) Then
  580.                    Return bytes
  581.                End If
  582.                bytes = Me.ParseFileSizeString(strValue)
  583.                If bytes <> 0UL Then
  584.                    If context.PropertyDescriptor IsNot Nothing AndAlso context.PropertyDescriptor.PropertyType Is GetType(FileSize) Then
  585.                        Return New FileSize(bytes, DigitalStorageUnits.Byte)
  586.                    Else
  587.                        Return DirectCast(bytes, Object)
  588.                    End If
  589.                End If
  590.            End If
  591.  
  592.            Return MyBase.ConvertFrom(context, culture, value)
  593.        End Function
  594.  
  595.        <DebuggerStepThrough>
  596.        Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object
  597.            If destinationType Is GetType(String) Then
  598.                Dim bytes As ULong = If((TypeOf value Is FileSize), CULng(DirectCast(value, FileSize).Size(DigitalStorageUnits.Byte)), DirectCast(value, ULong))
  599.                Dim formattedSize As String = Me.FormatByteFileSize(bytes)
  600.                Return If(bytes < 1024, String.Format("{0}", formattedSize), String.Format("{0} ({1:N0} bytes)", formattedSize, bytes))
  601.            End If
  602.  
  603.            Return MyBase.ConvertTo(context, culture, value, destinationType)
  604.        End Function
  605.  
  606. #End Region
  607.  
  608. #Region " Private Methods "
  609.  
  610.        <DebuggerStepThrough>
  611.        Private Function ParseFileSizeString(sizeString As String) As ULong
  612.  
  613.            Dim trimmedSizeString As String = sizeString.Trim()
  614.            If trimmedSizeString.Contains("("c) Then
  615.                trimmedSizeString = trimmedSizeString.Substring(0, trimmedSizeString.IndexOf("("c))
  616.            End If
  617.  
  618.            For Each kvp As KeyValuePair(Of String(), ULong) In sizeUnitsDictionary
  619.                For Each sizeUnitName As String In kvp.Key
  620.                    If trimmedSizeString.EndsWith(sizeUnitName, StringComparison.OrdinalIgnoreCase) Then
  621.                        Dim numString As String = trimmedSizeString.Substring(0, trimmedSizeString.Length - sizeUnitName.Length).Trim()
  622.                        Dim num As Double
  623.                        Dim numberFormat As IFormatProvider
  624. #If NETCOREAPP Then
  625.                        numberFormat = Thread.CurrentThread.CurrentUICulture.NumberFormat
  626. #Else
  627.                        numberFormat = My.Application.UICulture.NumberFormat
  628. #End If
  629.                        If Double.TryParse(numString, NumberStyles.Number, numberFormat, num) Then
  630.                            Try
  631.                                Return CULng((num * kvp.Value))
  632.                            Catch ex As OverflowException
  633.                                Return ULong.MaxValue
  634.                            Catch ex As Exception
  635.                                Throw
  636.                            End Try
  637.                        End If
  638.                    End If
  639.                Next sizeUnitName
  640.            Next kvp
  641.  
  642.            Throw New Exception("Cannot parse the specified file size value.")
  643.        End Function
  644.  
  645.  
  646.        <DebuggerStepThrough>
  647.        Private Function FormatByteFileSize(bytes As ULong) As String
  648.            Dim unitIndex As Integer = 0
  649.            Dim fileSize As Double = bytes
  650.  
  651.            While (fileSize >= 1024) AndAlso (unitIndex < sizeUnitsDictionary.Count - 1)
  652.                fileSize /= 1024
  653.                unitIndex += 1
  654.            End While
  655.  
  656.            Return If(unitIndex = 0,
  657.                       String.Format("{0} bytes", fileSize),
  658.                       String.Format("{0:F2} {1}", fileSize, sizeUnitsDictionary.ElementAt(unitIndex).Key(0)).Replace(",00", ""))
  659.        End Function
  660.  
  661. #End Region
  662.  
  663.    End Class
  664.  
  665. End Namespace
  666.  
  667. #End Region
  668.  
  669. #Region " PropertyGridExtensions "
  670.  
  671. Namespace DevCase.Extensions.PropertyGridExtensions
  672.  
  673.    <HideModuleName>
  674.    Public Module PropertyGridExtensions
  675.  
  676. #Region " Public Extension Methods "
  677.  
  678.        <DebuggerStepThrough>
  679.        <Extension>
  680.        <EditorBrowsable(EditorBrowsableState.Always)>
  681.        Public Function IsInitialized(propGrid As PropertyGrid) As Boolean
  682.  
  683.            Return PropertyGridExtensions.GetInternalLabelWidth(propGrid) <> -1
  684.        End Function
  685.  
  686.        <DebuggerStepThrough>
  687.        <Extension>
  688.        <EditorBrowsable(EditorBrowsableState.Always)>
  689.        Public Sub SetSplitterPosition(propGrid As PropertyGrid, xPos As Integer)
  690.  
  691.            If Not PropertyGridExtensions.IsInitialized(propGrid) Then
  692.                Throw New InvalidOperationException("The PropertyGrid must be initialized in order to set the splitter control position.")
  693.            End If
  694.  
  695.            Dim internalGridView As Control = PropertyGridExtensions.GetPropertyGridInternal(propGrid)
  696.            Dim moveSplitterToMethod As MethodInfo = internalGridView.GetType().GetMethod("MoveSplitterTo", BindingFlags.NonPublic Or BindingFlags.Instance)
  697.            moveSplitterToMethod.Invoke(internalGridView, {xPos})
  698.        End Sub
  699.  
  700. #End Region
  701.  
  702. #Region " Private Methods "
  703.  
  704.        Private Function GetPropertyGridInternal(propGrid As PropertyGrid) As Control
  705.  
  706.            ' Class: System.Windows.Forms.PropertyGridInternal.PropertyGridView
  707.  
  708.            Dim getPropertyGridViewMethod As MethodInfo = GetType(PropertyGrid).GetMethod("GetPropertyGridView", BindingFlags.NonPublic Or BindingFlags.Instance)
  709.            Dim gridView As Control = DirectCast(getPropertyGridViewMethod.Invoke(propGrid, Array.Empty(Of Object)()), Control)
  710.            Return gridView
  711.  
  712.            ' We can also retrieve the internal PropertyGridView this other way:
  713.            ' ------------------------------------------------------------------
  714.            ' Dim gridViewFieldInfo As FieldInfo = propGrid.GetType().GetField("gridView", BindingFlags.Instance Or BindingFlags.NonPublic)
  715.            ' Dim gridView As Control = DirectCast(gridViewFieldInfo.GetValue(propGrid), Control)
  716.            ' Return gridView
  717.        End Function
  718.  
  719.        Private Function GetInternalLabelWidth(propGrid As PropertyGrid) As Integer
  720.  
  721.            Dim internalGridView As Control = PropertyGridExtensions.GetPropertyGridInternal(propGrid)
  722.            Dim propInfo As PropertyInfo = internalGridView.GetType().GetProperty("InternalLabelWidth", BindingFlags.NonPublic Or BindingFlags.Instance)
  723.            Return CInt(propInfo.GetValue(internalGridView))
  724.        End Function
  725.  
  726. #End Region
  727.  
  728.    End Module
  729.  
  730. End Namespace
  731.  
  732. #End Region
  733. '@
  734. $assembly = Add-Type -TypeDefinition $vbCode `
  735.                      -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) `
  736.                      -PassThru `
  737.                      -ReferencedAssemblies "Microsoft.VisualBasic.dll", `
  738.                                            "System.Windows.Forms.dll", `
  739.                                            "System.Security.dll", `
  740.                                            "System.Collections.dll", `
  741.                                            "System.Drawing.dll", `
  742.                                            "System.Globalization.dll", `
  743.                                            "System.Reflection.dll", `
  744.                                            "System.Linq.dll", `
  745.                                            "System.IO.dll", `
  746.                                            "System.Xml.dll", `
  747.                                            "System.Xml.Serialization.dll", `
  748.                                            "System.dll" `
  749.                      | where { $_.IsPublic }
  750.  
  751.  
  752. function Get-FormattedSize {
  753.    param (
  754.        [int64]$sizeInBytes
  755.    )
  756.  
  757.    $buffer = New-Object System.Text.StringBuilder 24
  758.    $resultPtr = [DevCase.Win32.NativeMethods.ShlwApi]::StrFormatByteSize64A($sizeInBytes, $buffer, $buffer.Capacity)
  759.  
  760.    if ($resultPtr -eq [IntPtr]::Zero) {
  761.        return "Error formatting the file size."
  762.    } else {
  763.        return $buffer.ToString()
  764.    }
  765. }
  766.  
  767. function WriteDummyFile {
  768.    param (
  769.        [string]$FilePath,
  770.        [uint64]$FileSize,
  771.        [uint64]$BufferSize = 4MB,
  772.        [bool]$randomData = $false
  773.    )
  774.  
  775.    $formattedFileSize = Get-FormattedSize -sizeInBytes $FileSize
  776.  
  777.    $fs = [System.IO.File]::Create($FilePath)
  778.  
  779.    if ($BufferSize -ge $FileSize) {
  780.        $BufferSize = [math]::Floor($FileSize / 2)
  781.    }
  782.  
  783.    [int64]$bytesWritten = 0
  784.    $buffer = New-Object byte[] $BufferSize
  785.    $rand = New-Object Random
  786.  
  787.    Write-Host "Creating dummy file at '$FilePath' with a size of $formattedFileSize..."
  788.  
  789.    while ($bytesWritten -lt $FileSize) {
  790.        $bytesToWrite = [math]::Min($BufferSize, $FileSize - $bytesWritten)
  791.  
  792.        if ($randomData) {
  793.            $rand.NextBytes($buffer)
  794.        } else {
  795.            [Array]::Clear($buffer, 0, $bytesToWrite)
  796.        }
  797.  
  798.        $fs.Write($buffer, 0, $bytesToWrite)
  799.  
  800.        $bytesWritten += $bytesToWrite
  801.        $formattedBytesWritten = Get-FormattedSize -sizeInBytes $bytesWritten
  802.  
  803.        $progressPercent = [math]::Min(($bytesWritten / $FileSize) * 100, 100)
  804.  
  805.        Write-Progress -PercentComplete $progressPercent -Status "$FilePath" -Activity "Writing dummy file..." -CurrentOperation "$formattedBytesWritten written."
  806.    }
  807.        Write-Progress -PercentComplete 100 -Status "$FilePath" -Activity "Dummy file has been written." -CurrentOperation "$formattedBytesWritten written."
  808.  
  809.    $fs.Close()
  810.  
  811.    Write-Host ""
  812.    Write-Host ""
  813.    Write-Host ""
  814.    Write-Host ""
  815.    Write-Host ""
  816.    Write-Host ""
  817.    Write-Host ""
  818.    Write-Host ""
  819.    Write-Host ""
  820.    Write-Host "Dummy file successfully created at '$FilePath' with a size of $formattedFileSize."
  821. }
  822.  
  823.  
  824. $form = New-Object CreateDummyFileOptionsForm
  825. $dlgResult = $form.ShowDialog()
  826.  
  827. if ($dlgResult -eq [System.Windows.Forms.DialogResult]::OK) {
  828.    $fileOptions = $form.DummyFileOptions
  829.    WriteDummyFile -FilePath $fileOptions.FilePath -FileSize $fileOptions.FileSizeBytes -BufferSize $fileOptions.BufferSizeBytes -randomData $fileOptions.UseRandomData
  830. } else {
  831.    Write-Host "Operation canceled. No file selected."
  832. }
  833.  
  834. Write-Host "Press any key to exit..."
  835. $key = [System.Console]::ReadKey($true)
  836. Exit(0)
  837.  


« Última modificación: Ayer a las 09:58 por Eleкtro » En línea



Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines