Cuma Eğlencesi: Örnek Dosyalar Oluşturma


Ancak, bazı kukla veya örnek dosyalar isteyebileceğiniz yer, çeşitli dosyalardan oluşan bir kullanıcı klasörünün benzetimini yapmaktır. PowerShell komut dosyalarınızı geliştirmek için bu test dizinini kullanabilirsiniz. Bir sürü örnek dosyaya ihtiyaç duymak için kendi nedenleriniz olabilir. Ben de orijinal kodu aldım ve genellikle yaptığım gibi onunla koştum. New-SampleFile adında bir işlev buldum.

#requires -version 4.0

Function New-SampleFile {
<#
.SYNOPSIS
Create sample files
.DESCRIPTION
This command will create sample, or dummy files of random sizes in the folder you specified.
.PARAMETER Path
The folder where the files will be created. The default is the current location.
.PARAMETER Filename
You can specify a filename or let the function create a random name.
.PARAMETER MaximumSize
The maximum file size in bytes for the sample file. The minimum is 5 bytes.
.PARAMETER Force
Overwrite existing files with the same name.
.PARAMETER Passthru
Write the new file to the pipeline.

.EXAMPLE
PS C:\> new-samplefile -path c:\files -filename fileA.txt

Create a random sized file called FileA.txt in C:\files.
.EXAMPLE
PS C:\> (1..5).foreach({new-samplefile -path c:\work -Filename "file$_.txt" -Passthru -MaximumSize 1kb -Force})


    Directory: C:\work


Mode                LastWriteTime     Length Name                                       
----                -------------     ------ ----                                       
-a---         1/20/2015   9:11 AM        296 file1.txt                                  
-a---         1/20/2015   9:11 AM         22 file2.txt                                  
-a---         1/20/2015   9:11 AM        979 file3.txt                                  
-a---         1/20/2015   9:11 AM        320 file4.txt                                  
-a---         1/20/2015   9:11 AM        855 file5.txt 

Create 5 files, file1.txt to file5.txt under C:\work with a maximum size of 1KB.

.NOTES
NAME        :  New-SampleFile
VERSION     :  1.0   
LAST UPDATED:  1/20/2015
AUTHOR      :  Jeff Hicks (@JeffHicks)

Learn more about PowerShell:
Essential PowerShell Learning Resources
**************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** .INPUTS None .OUTPUTS System.IO.FileInfo #> [cmdletbinding(SupportsShouldProcess)] Param( [Parameter(Position=0)] [string]$Path=".", [string]$Filename = [System.IO.Path]::GetRandomFileName(), [ValidateNotNullorEmpty()] [int]$MaximumSize = 100KB, [switch]$Force, [switch]$Passthru ) Write-Verbose -Message "Starting $($MyInvocation.Mycommand)" #validate path to make sure it is valid and a FileSystem path if ((Test-Path $Path) -AND ((Resolve-Path $path).Provider.Name -eq 'FileSystem')) { #define the output path $Output = Join-Path -Path (Convert-Path $path) -ChildPath $Filename #delete existing file if found and using $Force, otherwise #the function will throw an exception if ($Force -AND (Test-Path -Path $Output)) { Write-Verbose "Deleting existing file" Remove-Item -Path $Output } #if $force and output file exists #generate a random file size $Size = Get-Random -Minimum 5 -Maximum $MaximumSize Write-Verbose -message "Creating $output with size $Size" if ($PSCmdlet.ShouldProcess($Output)) { $stream = New-Object System.IO.FileStream($Output, [System.IO.FileMode]::CreateNew) $stream.Seek($Size, [System.IO.SeekOrigin]::Begin) | Out-Null $stream.WriteByte(0) $Stream.Close() Write-Verbose "File created." if ($Passthru) { Get-Item -Path $Output } } #close should process } #if path test else { Write-Warning "Could not verify $(Convert-path $Path) as a filesystem path." } Write-Verbose -Message "Ending $($MyInvocation.Mycommand)" } #end New-SampleFile function

İşlev, belirtilen klasörde rastgele boyutlu bir dosya oluşturacaktır. Varsayılan geçerli konumdur. Kodu incelerken, yolu doğrulamak ve bunun bir Dosya Sistemi yolu olduğundan ve kayıt defteri gibi bir şey olmadığından emin olmak için bir test eklediğimi göreceksiniz. Ayrıca varsayılan olarak işlev, rcstwqyg.34e gibi rastgele oluşturulmuş bir dosya adı kullanacaktır. Şahsen ben bir dosya adı belirleyeceğim. İşlev, 5 bayt ile varsayılan değeri 100 KB olan MaximumSize parametresinin değeri arasında rastgele boyutta bir dosya oluşturacaktır.

-Force kullanmadığınız sürece işlev mevcut dosyaların üzerine yazmaz. -Passthru kullanmadığınız sürece herhangi bir çıktı görmezsiniz. Bunlar ortak parametreler olsa da bunları uygulamak için PowerShell ifadelerini yazmam gerekiyordu. Aynı şey -WhatIf için de geçerlidir. Cmdletbinding özelliğinde işlevin ShouldProcess'i desteklediğini göreceksiniz. Ancak çağırdığım .NET sınıflarının WhatIf kavramı yok. Bunu kendim halletmek zorunda kaldım

if ($PSCmdlet.ShouldProcess($Output)) {
    $stream = New-Object System.IO.FileStream($Output, [System.IO.FileMode]::CreateNew)
    $stream.Seek($Size, [System.IO.SeekOrigin]::Begin) | Out-Null
    $stream.WriteByte(0)
    $Stream.Close()

    Write-Verbose "File created."

    if ($Passthru) {
        Get-Item -Path $Output
    }
} #close should process

İşte eylemdeki işlev:

Bu aynı zamanda birden fazla dosya oluşturmayı da kolaylaştırır.

1..10 | foreach { new-samplefile -Path c:\work -Filename "TestFile_$_.dat" -passthru -MaximumSize 50KB}

Peki ya buna ne dersiniz? Farklı adlara sahip çeşitli dosyalar oluşturmak istiyorum.

$extensions = ".txt",".docx",".xlsx",".pdf",".pptx",".doc",".png",".mp3"
$names = "sales","data","marketing","file","demo","test","finance","HR","MFG","project"
$path = "C:\SampleFiles"
1..10 | foreach {
$file = "{0}_{1}{2}" -f (Get-Random -InputObject $names),(Get-Random -Minimum 10 -Maximum 1000),(Get-Random -InputObject $extensions)
New-SampleFile -Path $path -Filename $file -Passthru -Force
}

Artık üzerinde çalışabileceğim bazı test dosyalarım var

Normalde mümkün olan her yerde cmdlet'leri kullanmayı tercih ederim. Ancak Microsoft'un sahte dosyalar oluşturmaya yönelik bir cmdlet'i olmadığından, .NET Framework'e başvurma konusunda hiçbir sorunum yok. Ancak, bugün yaptığım gibi, .NET komutlarını kullanıcı dostu ve kullanımı kolay gelişmiş bir işleve sarmanın yine de zaman ayırmaya değer olduğunu düşünüyorum.

Bu işlevi kullanmanın bir yolunu bulursanız bana haber vereceğinizi umuyorum.

İlgili makaleler