Showing posts with label Windows Tools. Show all posts
Showing posts with label Windows Tools. Show all posts

Tuesday, December 18, 2012

Get Folder Permissions by Scripts (3)

In terms of getting folder permissions by using PS script, the first two blogs are just good enough. As a bonus and my personal reference, here are simple helper function and entry point. That completes my blog about my script.

The help function is a very simple one which prints out the usage of the script. The same practice can be applied to other scripts.

# FUNCTION LISTINGS
# =============================================================================
# Function: HelpInfo
# Created: [11/25/2009]
# Author: David Chu
# Arguments:
#   $p_scriptApp: script application
# -------------------------------------------
# Purpose: display usage message
# -------------------------------------------
function HelpInfo($p_scriptApp)
{
 Write-Output ""
 Write-Output "Description: Get permissions for a folder."
 Write-Output "Parameters: folderPath [outFile] [/s]"
 Write-Output "Where"
 Write-Output "      folderPath: a path for a folder"
 Write-Output "      outFile: output file"
 Write-Output "      /s: recursive to get sub folders"
 Write-Output "Examples:"
 Write-Output "This one running from PowerShell:"
 Write-Output ("  PS: {0} C:\MyData" -f $p_scriptApp)
 Write-Output "The following example running from cmd console:"
 Write-Output ("  cmd> PowerShell {0} C:\MyData myFile /s" -f $p_scriptApp)
}

PS entry section is the place to get all the parameters from command line.

# Example to run this script:
# @powershell d:\Scripts\GetPerm.ps1 'D:\Displays\Public' /s
# Result:
D:\Displays\Users Everyone:(OI)(CI)F
                 BUILTIN\Administrators:(OI)(CI)F
                 NT AUTHORITY\SYSTEM:(OI)(CI)F
                 CREATOR OWNER:(OI)(CI)(IO)F
                 BUILTIN\Users:(OI)(CI)R
                 BUILTIN\Users:(CI)(special access:)

                                   FILE_APPEND_DATA

                 BUILTIN\Users:(CI)(special access:)

                                   FILE_WRITE_DATA
#*=============================================================================
#* SCRIPT BODY
#*=============================================================================
# example parameter values for this script. Add the parameter to PowerGUI Script
# Editor's Input toolbar:
# C:\Users /s
$scriptApp = "GetPerm.ps1"

# check input arguments
if ( $args.length -eq 0 -or $args.length -gt 3 )
{
 HelpInfo $scriptApp
 return
}
# Get the first input parameter
$i = 0
$folderPath = $args[$i++
$outFile = "outFile.txt"]
$recursive = $false
if ($args.length -gt 1)
{
 if ( $args[$i++].ToLower() -eq "/s")
 {
   $recursive = $true
   if ($args.length -gt 2)
   {
     $outFile = $args[$i++]
   }
 }
 else
 {
   $outFile = $args[$i++]
   if ($args[$i++] -eq "/s")
   {
     $recursive = $true
   }
 }
}
# check if source and dest pathes exist
if ( Test-Path -Path $folderPath | where {!$_PSIsContainer} )
{
 GetFolderPermission $folderPath $recursive $outFile
} else {
 Write-Output ("Invalid path: {0}" -f $folderPath)
}

#*=============================================================================
#* END OF SCRIPT BODY
#*=============================================================================

In PS, command line argument can be obtained from $args[] collection, and the number of arguments is the property of length of $args.  Each argument can be enclosed by single quote ' char, not double " char.

Read More...

Tuesday, December 11, 2012

Get Folder Permissions by Scripts (2)

I created a simple function in PowerShell script to get folder permissions. As I mentioned in my previous blog, a DOS command is used to get folder permissions: Calcs. If there is subfolder within a folder, the function provides recursive option to get subfolder permissions. In addition to that, the folder can contain wild characters such as "*data".

To get all the containers as a collection in PS, the command is Get-Item with option $_.PSIsContainer:

$fs = Get-Item -Path $p_Path | Where-Object {$_.PSIsContainer }

The following is the function

# Function: GetFolderPermission
# Created: [10/02/2012]
# Author: David Chu
# Arguments:
#   $p_Path: folder
#   $p_recursive:    true for recursive, false for not
# -------------------------------------------
# Purpose: get folder permissions
# -------------------------------------------
function GetFolderPermission(
 $p_Path,
 $p_outFile,
 $p_recursive)
{
 # get all the files matched and timestamp > comparing date
 $fs = Get-Item -Path $p_Path | Where-Object {$_.PSIsContainer }
 if ( $fs -ne $null )
 {
   foreach ($folder in $fs)
   {
     $fullDir = $folder.FullName
     Write-Output $fullDir
     $cmd =  'cacls "{0}"' -f $fullDir
     Invoke-Expression $cmd | out-File -Append $p_outFile
     if ( $p_recursive )

     {
       $fsSub = Get-ChildItem -Path $fullDir |Where-Object {$_.PSIsContainer}
       if ( $fsSub -ne $null)
       {
         foreach ($subDir in $fsSub)
         {
           $fullDir = $subDir.FullName
           GetFolderPermission $fullDir $p_recursive $p_outFile
         }
       }
     }
   }
 }
}

The above codes are very straightforward, therefore, no need to explain.

Read More...

Monday, October 15, 2012

VIM Tips: Multiple Commands

This tip may be too simple and not not the best way to do it. However, it saves my tremendous time. Last week, I was going to bring my Visual Studio solution to my work. This solution contains a lots of projects. I realized that there are some namespaces and copy right issues to be updated. I could use VS to do it. But the VS at work is a new one, without tools like Refactory tool, CodRush Express, Resharper.

I did not like the native Find & Replace in VS. I decided to use VIM to do the job. The challenge I faced was that, first, I had to find all the files contains the strings I would like to replace, and secondly, do the find and replace for each file.

I used TotalCommander tool to do the search. It has built-in find feature and it is very powerful. I can easily get the search result files in one panel. Then I added a tool bar associated with VIM (set parameter %P%N). It is a very cool tool.

Next, I tried to use VIM to do replacement manually. I had too many .cs files. It was just to tedious. Then I searched for a way to do replacement, then save the changes and quit. Can I do three commands in one line? Soon I found a way to do it:

:%s/searchpattern/replacement/g | write | q

In VIM the pipe char is used to link a list of commands. This made my job much quicker. Afterward, I found that this could be done on command line like this:

gvim -c "%s/searchpattern/replacement/g | write | q" test.cs

I think that there must be a better way to run a chained command in a Windows command console: first finding all the files containing expected strings, and next using gvim to do the replacement.

Reference




Read More...

Thursday, June 02, 2011

Use NET USE Command to Map Network Drive

Here is one senario about using network shared folders. One application requires a configuration file. The application has been used in our intranet environment with many users. Many users use the same configuration. It is preferable to put the configuration file on a shared network folder. I need to find a efficient way to let user be able to access to the file.

I use the following DOS command NET USE to dynamically allocate a network drive for the share one:

@IF EXIST \\remoteMachine\sharedFolder GOTO EXIT
@NET USE * \\remotemachine\sharedFolder pwd /user:userName /PERSISTENT:NO
:EXIT


In above codes, * is used to get next available drive letter for mapping. The key option is /PERSISTENT:NO. With this setting, the mapped drive will be released or not persistent after logout or reboot.

The main reason I use dynamic mapping is that I am not sure what network drive is available. It hard to find one no body in use. Since my application does accept UNC network full name, I don't care what network letter being assigned. In the configuration file, I use UNC network full name. Since the UNC name has been authenticated, it is as same as a drive letter for fast access.

Read More...

Saturday, September 11, 2010

Old Windows Tool: XCOPY

XCOPY is an old Windows Tool. I remember that I first used this tool to copy files with sub-directiories when my computer was DOS based one. It is a nice tool to copy files. At my current work, this tool is also used to copy only most recently changed files as a way to back files. The option is /D/Y.

XCOPY source [destination] /D /Y


In the past week, I was working on a project to migrate services and scheduled jobs to a new Windows Server 2008 box. One simple task was to move a XCOPY job, copying files from a mapped Windows box to an imported UNIX based network drive. To my surprise, the same command does not work any more. It always copy whole files again, about several GBs. Somehow, XCOPY does not work for CIFS type network drive.

It is possible that the file date time stamp retrieved from the network drive might be truncated after seconds, while the full date time stamp are available in Windows file system. As a result, this may lead to always copy new files to the destination. I got this explaining from my SF question.

I also tried to use ROBOCOPY. It did not work neither. Finally, one of my network team member suggested me back to the old tool XCOPY with different options. It works again! Here is the command:

XCOPY source [destination] /M /Y /C

/M for copying only archived files and clear archive flag after the copy. I added /C option to let copy process to continue regardless of any failure.

The reason I like to use XCOPY is that it is more tolerance or not so aggressive. Even a file is hold by another process, it still does the copy. I tried SyncToy tool and it does not work with files being accessed by another process. My backup job is doing realtime file backup and those files are constantly updated by realtime process. Therefore, /C option lets me to continue the backup process and try it again on the next day.

I am happy with the alternative solution.

Read More...

Saturday, January 02, 2010

Notification Application: Growl

toolsI have used Growl, notification application, on my Mac for quite long time. It was recommended as one of must-have applications. Growl is a Growl Notification Protocol (GNTP) based messaging application, which displays any messages from other applications. Growl is an open source based project and it is free.

Recently, I have been working on a project to backup SQL server databases, history data files based on SCADA field sites, and other important files from various Windows based PC to a central place. The file transfers are running daily. When the project was close to final stage, I had to check backups and files every day to the central PC. It was very tedious. Growl comes to my mind. If there is any way I can use Growl in Windows. Quickly I found Growl for Windows.

I immediately downloaded the application and give it a try. I was worried about network firewalls and our internal security policies. To my surprise, Growl works like a charm without any issues. I used groiwlnotify.com to send out notifications from a remote PC, another client PC with Growl installed receives the messages.

There are some settings to do, but it is very straightforward. First, the network notification has to be enabled. Then I set up password for a receiver as security gate to verify any notification request. I think the password is optional but I like it. This will prevent any other network GNTP based services to send notifications unless password is verified.

It looks like that Growl for Mac and Growl for Windows are two different teams. The application appearances of both are almost the same, but there are some differences in features. For example, Growl for Windows has History setting, but for Mac. I like this feature. Since notification is displayed once with a quick time span, users may miss some important ones. With History, at least users can review all the past messages. For example, I set up the notification service on the central PC right after the jobs are finished, when is about 2:00AM. Nobody will be able to see them. Off couse, I could use Sticky feature to make the notification displayed until they are clicked. However, Growl for Windows seems have problem to display the message. One user told me that his notification window was black when he logged in a morning.

Mac Growl has more style than Windows Growl. I could not find some styles I use in Mac in Windows. I don't know why the styles cannot be ported to Windows. That's not a big deal.

In general Growl is a really good tool to send notifications between applications. My team likes this tool to make health monitor check much easy. The only concern is the stability of OS. Mac OS is much beter in this respect than Windows. I told my colloquies that I normally reboot my work Windows on daily base.

Read More...

Saturday, December 12, 2009

PsExec.exe Access Denied

I thought PsExec.exe would never fail to start a process on remote. I got my first failure last week when I was working on a project to do a similar remote execution call as I did before for a Windows XP Prof box. I had not problem running PsExec.exe to zip a file on Windows XP box before. However, this time for that Windows XP box, I got a failure: Access denied.

I did notice a different file sharing property window when I tried to share a a folder. I thought that there must be some Windows settings difference between this one and the one I worked before. Here is the file sharing property:



I googled "PsExec Access Denied" and found some resolutions. Basically, PsExec.EXE uses SCM API (OpenSCManager, CreateService, StartService), where SCM is Service Control Manager. It is similar as Process class in .Net, or the core might be the same. Those APIs are very much based on Window security settings. Anything is not correct, then PsExec.exe may fail.

The box I run PsExec.exe successfully has the following folder sharing property:



Simple File Sharing

This difference confirms that the box I got failure has some setting issues, as indicated in this discussion in Sysinternals Forums. The first setting is easy to change. From File Explorer's menu Tools|Folder Options..., in the View Tab, clear the setting for "Use simple file sharing":



Turn off "network users identify as guests"

The second change is a security setting. From Control Panel, find the Administrative Tools snap-in, open Local Security Settings. Then find Local Policies->Security Options. Look for the line "Network Access:Sharing and security model for local accounts". The value for this "key" was the default value of "Guest only - local users authenticate as Guest". Change it back to "Classic - local users authenticate as themselves".



After all those changes. I did not reboot the box. Just waited for a while. Then I got my PsExec.exe working, remotely zip files on the remote by using 7-zip tool!

Read More...

Sunday, December 06, 2009

SysInternals Tool: PsExec.exe

PS supports remote process. That means you may run a process on a remote Windows. Recently I was working on a project which requires to run a process on a remote Windows box. I tried to use WMI process to start a process on remote. It works on one box (Windows XP), but the same codes do not work on a Windows 2008 server.

Quickly I found a solution: a SysInternals tool, PsExec.exe. It is very small and it works well. To start a process and wait it terminated, there is the code:

PsExec.exe \\computerName -u userName -p pwd -i program args...

the option -i is used to start the program in an interactive way.

Read More...

Saturday, November 21, 2009

VIM Syntax Settings

Recently I started to learn and working on Windows PowerShell scripts. PowerGUI is a nice tool as script IDE or editor. However, when I wanted to write a blog on PowerShell with some example script codes, I have to use VIM or MacVim to convert codes to HTML. By default, my VIM does not have syntax vim file for PowerShell, since it is a new script language. Then I searched for the ps1.vim on web. It does not take much time to find out one at vim.org's syntax library.

This is first time for me to add syntax file to VIM. It was challenge for me and I took about 2 hours in last evening to figure it out. VIM is an excellent editor for programmers. It provides configuration settings for adding syntax files. Basically, the settings are in two different areas. The first one is to add syntax file to a specified directory. Most cases, syntax files can be found on web by many VIM fans and gurus. I don't need to write one even there are detail information about writing syntax files. Taking PowerShell script as example, the syntax file should be ps1.vim.

Add Syntax File

In case of my Mac OS(UNIX system), there are two places I can place the file. One is for all users and another one is a login user. All the syntax files come with VIM are installed in my Mac at /usr/share/vim/vim72/syntax/ folder. I found this location by using the following command in Terminal:


[Home] $ find / -name "html.vim" -print


Since I have never added any syntax file by myself before, there is no syntax files specific for my login name. I have to create the following folder for my syntax files.


[Home] $ mdkdir ~/.vim/syntax
[Home] $ cp ~/Downloads/ps1.vim ~/.vim/syntax/ps1.vim


After that, I thought I should be able to test a ps1 file in VIM with syntax colors. I did not see any syntax colour when I opened a test file: test.ps1. It took a while to figure out a way to manually load or test the syntax file by using the command in vim:


:source ~/.vim/syntax/ps1.vim



The loading process was failed because there are some syntax errors in the ps1.vim file. I think that actually is the line break problems when I downloaded the file from web: some line breaks are actually ^M chars. Then I found another updated ps1.vim from tomsr. I copied the source codes from web page and replaced ps1.vim's whole content. After that, the loading process was OK.

NOTE on September 16, 2010: for Windows XP, the vim.ps1 from VIM syntax library is OK. I have to copy this file to my VIM\vimfiles\syntax folder.

Define File Types

Still I could not see syntax colour. This is because VIM requires another setting to define file types. This second setting is called as *new-filetype*. I choose C option to define my new file type. I copied the following codes to a file at ~/.vim/filetype.vim:

if exists("did_load_filetypes")
  finish
endif
augroup filetypedetect
  au! BufRead,BufNewFile *.ps1    setfiletype ps1
augroup END


Then I restarted my VIM. Finally I can see my test.ps1 file in VIM with syntax colours.



NOTE on September 16, 2010: for Windows XP, the file filetype.vim should be copied to VIM\vimfiles.

Read More...

Sunday, November 08, 2009

SyncToy 2.0 - A Windows 7 Tool by Microsoft Home Server Team

toolsLast week, I was asked to investigate an issue of backup some files from remote network drives. I thought the basic concept is to find out if a file has been changed or not. This could be file name, modified date. It can go further complicated such as file name changes, deleting, as well as content change. This must be a very common issue in Windows platform, I thought, and there must be something available such as libraries or tools.

Soon I found out SyncToy 2.0, a free Windows utility application offered by Microsoft. It was actually for Windows 7. The tool is based on Microsoft Sync Framework File Synchronization Provider. In other words, you can use the tool or use the library in .Net. The tool provides three basic actions:

  • Sync: bi-directional sync, any change in either left or right will synced to opposite side. New and updated files are copied both ways. Renames and deletes on either side are repeated on the other.
  • Echo: any change on the left side will be echoed to the right side, but any changes on the right side will not be on right side or reload to right side. New and updated files are copied left to right. Renames and deletes on the left are repeated on the right.
  • Contribute: only new files on left side will be added to the right side. New and updated files are copied left to right. Renames on the left are repeated on the right. No deletions.



For my case, Contribute is the right action for me. I tried this tool and it works well. If there are a lots of files on the left side, the first time may take long time since all the files will be copied to the right side. The later sync process may be much faster if there is a few files changed or no change. It can be used against network drive and the sync process can be done as a scheduled job with sync name. Each sync is defined as a pair of left and right, with additional options such as file exclusion, hidden files and more.

The tool provides log under current user profile. I think the log file is saved at %userprofile%Local Settings/Application Data/Microsoft/SyncToy 2.0. The left and right sides, there are some hidden dat files, which store sync information for the next sync.

There are also some examples of how to use the Sync Framework. I think this provides more more control over how to sync and realtime sync.

Reference: a blog on SyncToy 2.0 by Microsoft Home Server Team.

Read More...

Tuesday, January 20, 2009

Live Mesh Devices Beta Available

Yesterday I learned from .Net Rocks audio talk on this new release from Microsoft. It is a tool to sync almost anything based on Web services or Cloud. I just tried this from iMac machine; unfortunately, it does not support Mac yet.

I have been used Dropbox to sync files between computers including Mac. Dropbox is only for file sharing with 2GB space for free. This tool is similar as Foxmarks, which is used to sync Firefox bookmarks.

Based on the information from the .Net Rocks talk, the Live Mesh is even bigger than those. It provides a framework for .Net developers to write services for various usages.

From my Mac, what I can do is to create folders on my Live Mesh Desktop. I think I can update or sync files with my local PC folders just like Dropbox.

Here is the picture of my Live Mesh:



I had my Firefox crashed when I browsing Live Mesh on my iMac.

Then I connected to my Windows though Remote Desktop Connection. I can view Live Mesh there and install Application Live Mesh, which is similar as Dropbox to sync files if I have files defined for sync. There is no more other features like services right now.

Read More...

Friday, May 30, 2008

Tools and Utilities

Tools and utility programs are essential helpers for programming. I learned a lots of tools from web, blogs and other people. I remembered that when I was working at one SCADA company about 7 years ago. One developer showed me Total Commander tool with his passion. He told me it is much better than Windows File Explorer and he cannot work without it.

Since then, I tried this tool and I fall in love with it. It helps a lot for file exploring, management, and software development. When I work any where, I always bring it with me.

Many other tools are also very good. Here is a list of tools Jean-Paul and Scott Handselman recommend:



I like to read JP's blog. Some of his blogs recommended some really good tools.

Read More...

Saturday, September 29, 2007

Installation of Windows PowerShell

I just watched dnrTV show #82 Scott Hanselman on Windows PowerShell. This shell is really very cool one. I followed the instruction to install the PowerShell and PowerTab.

The installation of PowerShell is straightforward. After the installation, I added a shortcut of this program to my desktop.

PowerTab installation is very clear. The downloaded file is a zip file. Fortunately, the show explained the steps of installation. In the PowerShell console, type the following command to get the profile location:

$PROFILE
C:\Documents and Settings\[user name]\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1


The folder of "WindowsPowerShell" and the profile do not exist. I had to create the folder first. Then I unzip the PowerTAB to a folder called as PowerTAB there:

md WindowsPowerShell
cd WindowsPowerShell
md PowserTAB
cd PowerTAB


After dumping the zip file there, run the following command to set execution policy(first getting command usage):


Get-Help Set-ExecutionPolicy
Set-ExecutionPolicy Unrestricted


Then run the script to install the PowerTAB:


.\Setup.Cmd


Accept all the default settings, the PowerTAB is installed.

I am very impressed by the tool of PowerShell and the plugin PowerTAB. I think this is a must-have tool for .Net developers or programmers.

Read More...