How to calculate and print number of files in each subfolder of the current folder on Linux

find . -type d | while read DIR; do find $DIR -type f | printf "%-8s %s\n" $(wc -w) $DIR; done | sort -nr

That is: find all subdirectories of current directory; for each subdirectory, find all files, and print file count and path. Finally it sorts the result to show folders with most files on top
Note that the first entry is the folder itself. Also this script omits soft links and does not count sub-folders as files.

For example:

[someone@somewhere]# cd /etc/X11/
[someone@somewhere]# find . -type d | while read DIR; do find $DIR -type f | printf "%-8s %s\n" $(wc -w) $DIR; done | sort -nr
10 .
7 ./xinit
3 ./xinit/xinitrc.d
0 ./xorg.conf.d
0 ./xinit/Xclients.d
0 ./fontpath.d
0 ./applnk

How to calculate and print number of files in each subfolder of the current folder on Linux

PowerShell Syntax HighLighting with PowerShell Script

For script in the previous post, I needed a tool that would convert PowerShell script to HTML format. Surprisingly numerous online tools somehow completely ignored PowerShell, so I found PowerShell scripts that would do the job: PowerShell Syntax Highlighting by Lee Holmes, an extended version by Helge Klein, and different implementation, which will only work on PowerShell 2.0 by Jeff Hillman.

PowerShell Syntax HighLighting with PowerShell Script

Post Issue to Jira Using PowerShell 2.0

Some time ago I was looking for a skeleton of a PowerShell 2.0 script that would allow me to post an issue to Jira. Didn’t find one, so had to come up with my own.

# Change those strings to whatever is specific to environment
[string] $SERVER = “localhost:8080”
[string] $USER = “powershelluser”
[string] $PWD = “password”
# Get Project ID from Administration -> Projects, e.g. 
[string] $PROJECTID = “10123”
# Specify fields that need to be posted
# NOTE: You must provide all required fields
# Example below submits 4 fields: 
#    assignee – automatically assigned to default user of the project
#    issuetype – selected type 3 = task
#    summary and description, which are read from elsewhere
[string] $FIELDS = “issuetype=3&priority=3&assignee=-1&summary={0}&description={1}”

# Those constants normally do not change
[string] $LOGIN_URL = http://{0}/login.jsp?os_username={1}&os_password={2}&os_destination=/secure/”
[string] $CREATE_URL = http://{0}/secure/CreateIssueDetails.jspa?pid={1}&{2}&Create=Create&atl_token={3}”
[string] $TOKEN_PREFIX = ‘<meta id=”atlassian-token” name=”atlassian-token” content=”‘
[string] $TOKEN_SUFFIX = ‘”>’

function loginToJira($server, $user, $pwd) {

[string] $postUrl = $url -f  $user, $pwd

[System.Net.WebRequest] $webRequest = [System.Net.WebRequest]::Create($postUrl)
$webRequest.CookieContainer = New-object System.Net.CookieContainer
[System.Net.WebResponse] $webResponse = $webRequest.getResponse()
# TO DO: Response can be verified here
# One of the ways to check if request was successful is to read $webResponse.StatusDescription, e.g.
Write-Host “status = “ $webResponse.StatusDescription;

$resStream = $webResponse.GetResponseStream()
[System.IO.StreamReader] $streamReader = New-Object System.IO.StreamReader -argumentList $resStream
$res = $streamReader.ReadToEnd()
$start = $res.IndexOf($TOKEN_PREFIX, 0+ $TOKEN_PREFIX.Length
$end = $res.IndexOf($TOKEN_SUFFIX, $start)
$token = $res.substring($start, $end  $start)

return $webRequest.CookieContainer, $token

function createJiraIssue($server, $session, $token, $project_id, $summary, $description) {

[string] $formattedFields = $FIELDS -f [System.Web.HttpUtility]::UrlEncode($summary), [System.Web.HttpUtility]::UrlEncode($description)
[string] $postUrl = $CREATE_URL -f $server, $project_id, $formattedFields, $token

[System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($postUrl);
$webRequest.CookieContainer = $session
[System.Net.WebResponse]$webResponse = $webRequest.getResponse()
# TO DO: Response can be verified here (similar to login)

$resStream = $webResponse.GetResponseStream()
[System.IO.StreamReader]$streamReader = New-Object System.IO.StreamReader -argumentList $resStream
$res = $streamReader.ReadToEnd()
# TO DO: Here it can be verified if the issue was posted successully, by looking into $res
# If issue is not posted, Jira will return HTML similar to the page seeing by the user who tried to post issue with missing / problematic fields

if($args.count -ne 3) {
Add-Type -AssemblyName System.Web
$session, $token = loginToJira $SERVER $USER $PWD
$testsummary = “This is a test – issue summary”
$testdscription = “This is a test.`n`nIssue description usually contains several lines of text”
createJiraIssue $session $token $PROJECTID $testsummary $testdscription

Post Issue to Jira Using PowerShell 2.0

A few PowerShell 2.0 Know-Hows

Script Snippets

1. Create a Unique Folder Name

(From: “Hey PowerShell guy, how can I create a new folder using a name based on the current date”)

function Create-UniqueFolder([string]$path) {
  md ($path + "\result_$((get-date).toString('yyyyMMddHHmmss'))")

2. Check if Script Runs on x86 or x64 Platform

(From: “What is the best way to program against PowerShells x64 vs x86 Variability”)

function Is-Wx64 {
  return test-path (join-path $env:WinDir "SysWow64")

3. Locate an Assembly (in Known Path, such As GAC)

function Get-AssemblyPathByName([string]$name) {
   return [System.Reflection.Assembly]::LoadWithPartialName($name).Location

4. Read XML File

$file = "XML file path"
[System.Xml.XmlDocument] $xd = new-object System.Xml.XmlDocument
# ... for example ...

5. Replace All Occurrences of a String in File

function Replace-InFile([string]$file, [string]$find, [string]$replace) {
  (Get-Content $file) | Foreach-Object {$_ -replace $find, $replace} | Set-Content $file

6. Handle a Process

Start a Process, Get Process Output and Standard Error Output, Wait for Process to Complete

# ... example doesn't load user profile, but redirects and retrieves stdout and stderr
$StartInfo = New-Object System.Diagnostics.ProcessStartInfo
 $StartInfo.FileName = "process path and name"
 $StartInfo.Arguments="process arguments, if any"
 $StartInfo.LoadUserProfile = $false
 $StartInfo.RedirectStandardOutput = $true
 $StartInfo.RedirectStandardError = $true
 $StartInfo.UseShellExecute = $false
 $StartInfo.WorkingDirectory = "working directory path"

 $process = [System.Diagnostics.Process]::Start($StartInfo)
# At this point can access process properties, e.g.:
Write-Host ("Started process with PID=" + $process.Id)

# Saving output to a file
 $stderr = $process.StandardError
if ($stdout -ne $null) {
  $output = $stdout.ReadToEnd()
  $outfile = "location and name of file to save output to"
  if ($output -ne "") { $output | Out-File $outfile }
# Saving standard error output to a file
$stdout = $process.StandardOutput
 if ($stderr -ne $null) {
  $errors = $stderr.ReadToEnd()
  $errfile = "file to save errors to"
  if ($errors -ne "") { $errors | Out-File $errfile }

 [void] $process.WaitForExit

7. Get Script Own Path

(From: Get Script Directory)

$scriptPath = Split-Path $MyInvocation.MyCommand.Path

Syntax and Cmdlets

1. Show Something on Screen

Write-Host "whatever you want to show on screen"

2. Run WMI Query

gwmi win32_service # or other class

Also handy in conjunction with filter:

gwmi win32_service | where-object {$_.Name -eq "service name" }

… And query on top of that:

gwmi win32_service | where-object {$_.Name -eq "service name" } | select Status,State,StartName,StartMode

3. Text File


Get-Content "my file"


Set-Content "my file" "my content"


Add-Content "my file" "my content"

4. Check if File Exists

test-path "file path and name"

5. String Functions

See: The String’s the Thing

6. Comparison Operators

See: About Comparison Operators

7. Special Characters (like tab, newline)

`0 -- Null
`a -- Alert
`b -- Backspace
`n -- New line
`r -- Carriage return
`t -- Horizontal tab
`' -- Single quote
`" -- Double quote

A few PowerShell 2.0 Know-Hows

How to identify which .NET framework version DLL was created with

1. C# Code

using System;
using System.Reflection;

public class LoadInvoke
    public static void Main(string[] args)
        Assembly a = Assembly.ReflectionOnlyLoadFrom(args[0]);
        string s = a.ImageRuntimeVersion;
        Console.WriteLine("{0}: {1}", args[0], s);

2. Compile with csc

(located in %Windir%\Microsoft.NET\Framework\[version])

3. Run from cmd

How to identify which .NET framework version DLL was created with