can anybody please translate these two scripts from MKS into Powershell? i would like to remove MKS from our ETL tools and accomplish this with Powershell but do not have the chops
1)
FileSize=ls -l $1 | awk '{print $5}'
if [ $FileSize -ge 100000000 ]; then split -b 60000000 $1 $1 fi
2) find $1 -type f -name *.txt -mtime +30 -exec rm {} \;
thank开发者_高级运维s very much drew
Avoiding using even standard aliases here (eg. can use dir
or ls
rather than Get-ChildItem
):
1) FileSize=ls -l $1 | awk '{print $5}'
$filesize = (Get-ChildItem $name).Length
if [ $FileSize -ge 100000000 ]; then split -b 60000000 $1 $1 fi
if ($filesize -ge 100000000) { ... }
(can't recall function of split
)
2) find $1 -type f -name *.txt -mtime +30 -exec rm {} \;
$t = [datetime]::Now.AddSeconds(-30)
Get-ChildItem -path . -recurse -filter *.txt |
Where-Object { $_.CreationTime -gt $t -and $_.PSIsContainer } |
Remove-Item
(Add a -whatif
to the Remove-Item
to list what would be deleted without deleting them.)
1) Get the size of the file named by $1
. If the size is more than 100 megabytes, split
it into parts of 60 megabytes each.
MKS
FileSize=`ls -l $1 | awk '{print $5}'`
if [ $FileSize -ge 100000000 ]; then
split -b 60000000 $1 $1
fi
PowerShell
function split( [string]$path, [int]$byteCount ) {
# Find how many splits will be made.
$file = Get-ChildItem $path
[int]$splitCount = [Math]::Ceiling( $file.Length / $byteCount )
$numberFormat = '0' * "$splitCount".Length
$nameFormat = $file.BaseName + "{0:$numberFormat}" + $file.Extension
$pathFormat = Join-Path $file.DirectoryName $nameFormat
# Read the file in $byteCount chunks, sending each chunk to a numbered split file.
Get-Content $file.FullName -Encoding Byte -ReadCount $byteCount |
Foreach-Object { $i = 1 } {
$splitPath = $pathFormat -f $i
Set-Content $splitPath $_ -Encoding Byte
++$i
}
}
$FileSize = (Get-ChildItem $name).Length
if( $FileSize -gt 100MB ) {
split -b 60MB $name
}
Notes: Only the split functionality needed by the question was implemented, and tested just on small file sizes. You may want to look into StreamReader
and StreamWriter
to perform more efficient buffered IO.
2) In the directory named by $1
, find
all regular files with a .txt
extension that were modified over thirty days ago, and remove them.
MKS
find $1 -type f -name *.txt -mtime +30 -exec rm {} \;
PowerShell
$modifiedTime = (Get-Date).AddDays( -30 )
Get-ChildItem $name -Filter *.txt -Recurse |
Where-Object { $_.LastWriteTime -lt $modifiedTime } |
Remove-Item -WhatIf
Notes: Take off the -WhatIf
switch to actually perform the remove operation, rather than previewing it.
精彩评论