Wednesday, October 21, 2015

BigFix Powershell to manually cache files

Cool things about this script:
  • Runs in powershell 1 or later
  • Does a SHASUM (sha1) for regular files in the current directory
  • Converts an array of characters to a string
  • Converts binary to hex
  • Checks for the existence of files before copying them
I use this script to check for files, sha them, and copy them to the bigfix cache server.

Let's jump right into the full text of the script:
# If you can't run scripts, try the following:
# Set-ExecutionPolicy unrestricted -scope currentuser
# Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 - AKA do what you want with it, use at your own risk.


$sha1 = new-Object System.Security.Cryptography.SHA1Managed
$fileloop=gci . | where-Object {$_.Extension -notmatch ".ps1"}
$files=gci . | where-Object {$_.Extension -notmatch ".ps1"}

[Console]::WriteLine("Looking at all non .ps1 files, it is not recommended to run this in a folder with lots of files or large files; This script does a shasum for every file.")

foreach($file in $fileloop)
{
    $filetosha=[System.IO.File]::Open($file.FullName, "open", "read")
    $shasum = $sha1.ComputeHash($filetosha) | %{$_.ToString("x2")}
    $filetosha.Dispose()
    $p = -join $shasum
    if ($file -ne $p)
    {
        #[Console]::WriteLine("$file - $p not equal");
        if ($files -like $p)
        {
            #[Console]::WriteLine("$p exists elsewhere");
        }
        else
        {
            [Console]::WriteLine("copy $file > $p");
            copy $file $p
            $files=gci .
        }
    }
    else
    {
        [Console]::WriteLine("$file = $p");
    }
}

$cachefiles=gci \\bigfixserver.contoso.com\DownloadCache | where-Object {$_.Extension -like ""}
$localfiles=gci . | where-Object {$_.Extension -like ""}
foreach($file in $localfiles)
{
    if($cachefiles -like $file)
    {
    }
    else
    {
        [Console]::WriteLine("copy $file > cache");
        copy $file \\bigfixserver.contoso.com\DownloadCache\
    }
}

I'm actually not going to break this one down too much it is fairly self-explanatory... well all but the SHA functionality:


The first thing we need to do is open the file:
$filetosha=[System.IO.File]::Open($file.FullName, "open", "read")
Now we run the "ComputeHash" function that comes from the system cryptography library. This will give us an array of bytes, but we don't want bytes, we want hex, so we pass that array of bytes to and convert them to an string array string of hex characters:
$sha1 = new-Object System.Security.Cryptography.SHA1Managed
$shasum = $sha1.ComputeHash($filetosha) | %{$_.ToString("x2")}
Cleanup: Done reading the file? Close the file:
$filetosha.Dispose() 
Let's take that array and join them into a single string and store it in the variable "p":
$p = -join $shasum

That's it.
I hope that this helps you out.

No comments:

Post a Comment