Automator or Applescript to Rename Subfolders and Files

I have 200 Gigs of files that need to be moved from a Mac's internal drive onto an external non-mac formatted drive for storage (Buffalo TeraStation). Obviously there is an issue with illegal characters in some of my filenames and folder names. I was able to create a workflow in Automator to replace illegal characters in the Filenamnes and nested filenames with the characters of my choice however it did not work for the Sub Folder names. Does anyone know if this is possible in Automator? If not, is there someone out there who can write a script for such a process?
Thank you in advance.

Scott,
Here is an AppleScript which can be placed in an Automator "Run AppleScript" action to do what you are want.
Click on the link to move the script into Script Editor. Then select all, copy and paste into a "Run AppleScript" action in Automator. Make sure to completely replace all of the text in the action i.e., don't just replace the (* Your script goes here *).
The find and replace characters are found in the properties at the top of the script so they can be adjusted to what you need. I also have a routine that will replace multiple illegal characters with a single legal character if you need that type of flexibility.
This action should be proceeded by an action that will supply an alias such as "Get Specified Finder Items".
click here to open this script in your editor<pre style="font-family: 'Monaco', 'Courier New', Courier, monospace; overflow:auto; color: #222; background: #DDD; padding: 0.2em; font-size: 10px; width:400px">property theIllegalCharacter : "/"
property theReplacementCharacter : "_"
on run {input, parameters}
tell application "Finder"
set theFinderWindow to make new Finder window
set current view of theFinderWindow to column view
set target of theFinderWindow to item 1 of input
set theIllegallyNamedSubFolders to folders of entire contents of target of theFinderWindow whose name contains theIllegalCharacter
set theIllegallyNamedFiles to files of entire contents of target of theFinderWindow whose name contains theIllegalCharacter
repeat with thisFile in theIllegallyNamedFiles
set (name of thisFile) to my RemoveIllegalNamingCharacters(name of thisFile, theIllegalCharacter, theReplacementCharacter)
end repeat
repeat with thisFolder in theIllegallyNamedSubFolders
set (name of thisFolder) to my RemoveIllegalNamingCharacters(name of thisFolder, theIllegalCharacter, theReplacementCharacter)
end repeat
end tell
return input
end run
to RemoveIllegalNamingCharacters(theName, IllegalCharacter, ReplacementCharacter)
set theNewName to ""
set theCharacterCount to (length of theName)
repeat with i from 1 to (length of theName)
if (character i of theName) is equal to IllegalCharacter then
set theNewName to theNewName & ReplacementCharacter
else
set theNewName to theNewName & character i of theName
end if
end repeat
return theNewName
end RemoveIllegalNamingCharacters
</pre>
PowerBook 12"   Mac OS X (10.4.7)  

Similar Messages

  • Delete subfolders and files

    On Mac OS X Lion i'm  setting the permission for a share point to a user. under "Write" submenu when i uncheck the two checkboxes "Delete" and "Delete Subfolders and file" so that the user won't be able to delete data from the server. the issue is that with this setting the user won't be able to create folders and subfolders and also rename.
    "Inheritance" boxes are all checked.
    Any suggestions on how to fix that will bve greatly appreciated.
    thanks.

    Do you mean the SMSAdminUI.log file from E:\Program Files\Microsoft Configuration Manager\AdminConsole\AdminUILog ? If so the file hasn't been modified since 3/14. It has some items highlited in red that I have listed below.  That is the only AdminUI.log
    I could find.  Thanks.
    [14, PID:2232][03/14/2013 13:37:11] :Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryException\r\nThe SMS Provider reported an error.\r\n   at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlResultObject.Get(ReportProgress
    progressReport)
       at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlResultObject.Get()
       at Microsoft.ConfigurationManagement.AdminConsole.Conditions.MenuUtilityClass.EnableDisableCloseAlertMenuStatus(Object sender, ScopeNode scopeNode, ActionDescription action, ResultObjectBase selectedResultObject)\r\nConfigMgr Error Object:
    instance of SMS_ExtendedStatus
    Description = "Error retrieving object ID=16777224";
    ErrorCode = 2151811598;
    Über Random

  • Does MacOS recognize Windows directory structure? Can I move an entire folder (consisting of subfolders and files) from Windows to Mac?

    Can I move an entire folder (consisting of subfolders and files) from Windows to Mac?

    Mustafafromnc,
    if you’re talking about a USB drive, then it will probably have an exFAT filesystem. Modern versions of OS X can read from and write to exFAT filesystems without problems, so you would be able to move Windows folders, subfolders, and files from an exFAT filesystem to an OS X filesystem.

  • Finding Folder Size including subfolders and files

    Hi Friends,
    Could you please Help in getting a Folder size through pure java.The folder contains subfolders and files.I have done rest of the things related to file operation and i can help in other things if you could please help in this regard.
    thanks and regards
    Avanish
    Avanish Kumar Singh
    Software Engineer
    Samsung SDS India Development Center
    Bangalore-560 001
    [email protected]
    [email protected]

    thanks bbrita !
    I too did the way it has given in reply but thats taking huge resource so if you know any direct way to find the directory size please let me know.
    thanks and regards
    avanish

  • Unable to rename folders and files on SharePoint mapped drive.

    I just installed a fresh copy of Windows 7 and have mapped a drive to my SharePoint "Shared Documents" folder.  I am able to open, save, and delete files and folders.  However, I am unable to rename files and folders.  No matter how long of
    short of a name I use I get the following error:
    "The file name you specified is not valid or too long.  Specify a different file name."
    I've mapped the "S" drive to http://hostname.domain.com/Shared Documents/
    I am a SharePoint Admin, and have confirmed that if I do not have this problem if I log into SharePoint with IE.  I have also confirmed that others are not experiencing this issue. Also, this issue did not exist on my previous installation of Windows
    7.  Therefore I assume this is a config issue.
    Also, in "My Computer" it shows the mapped SharePoint drive as a "FAT" filesystem.

    Did some more testing. From my mapped drive, I can create new folders and files, and delete them.  I created a folder in Windows Explorer, when I tried to give a name it gave me the above error and saved the folder as "New Folder".  No matter when
    I try, I cannot rename this folder unless I log into the SharePoint interface.
    Next, I tried this from the command line.  I moved to my S drive, and did a "mkdir test" and was able to create a folder named test.  Next I tried to "rename test testing" and received the following error:
    The filename, directory name, or volume label syntax is incorrect.
    The full path is S:\test.  If I do a "mkdir testing" I am able to create the folder.  If I try to rename the folder in Explorer, it gives me the "file name not valid or too long".  I'm obviously well under the 260 character limit, so there
    has to be something wrong with the fiel name, or drive mapping.
    Also, when I "dir" the S drive it tells me the drive has no label.  "Volume in drive S has no label."
    I'm having the same issue with files. I can create a file, modify it, delete it, but can't rename it.

  • Droplet to Rename Folders and Files

    I am an AS newbie and I need some help. Our accounting software creates a folder structure on our server when a job is created with a 6 digit job number. Enclosed in this folder is a set of sub-folders which are generated with a generic name: 0000_Art, 0000_Final, 0000_Fonts etc. It also places a generic rtf file named 0000_Readme. When work begins on a job we currently have to replace the "0000" with the last four digits of the job number: "140662" = "0662_Art" etc.
    I found a script to do this with some manual intervention but wanted to take this one step further by creating a droplet and making it drag and drop. This droplet works, but the problem comes in that it still wants you to choose the target folder from a dialog and I would like to just auto process the dropped folder and it's contents. Also, is there a way to tell AS to use characters 3-6 of the dropped folder's name to replace any instances of "0000" in sub-folder or document names enclosed? Is there any uneccessary code which can be stripped out?
    Here is the script as it stands now:
    on open of finderObjects
    set the source_folder to (choose folder with prompt "Folder containing items to edit:") as Unicode text
    display dialog "Search and replace in:" buttons {"File Names", "Folder Names", "Both"} default button 3
    set the search_parameter to the button returned of the result
    repeat
    display dialog "Enter text to find in the item names:" default answer "0000" buttons {"Cancel", "OK"} default button 2
    set the search_string to the text returned of the result
    if the search_string is not "" then exit repeat
    end repeat
    repeat
    display dialog "Enter replacement text:" default answer "" buttons {"Cancel", "OK"} default button 2
    set the replacement_string to the text returned of the result
    if the replacement_string contains ":" then
    beep
    display dialog "A file or folder name cannot contain a colon (:)." buttons {"Cancel", "OK"} default button 2
    else if the replacement_string contains "/" then
    beep
    display dialog "A file or folder name cannot contain a forward slash (/)." buttons {"Cancel", "OK"} default button 2
    else
    exit repeat
    end if
    end repeat
    display dialog "Replace “" & the search_string & "” with “" & the replacement_string & "” in every item name?" buttons {"Cancel", "OK"} default button 2
    tell application "Finder"
    -- Get a Finder reference to the relvant items.
    if (search_parameter is "Folder Names") then
    set item_reference to a reference to (folders of entire contents of folder source_folder whose name contains search_string)
    else if (search_parameter is "File Names") then
    set item_reference to a reference to (files of entire contents of folder source_folder whose name contains search_string)
    else
    set item_reference to a reference to (items of entire contents of folder source_folder whose name contains search_string)
    end if
    -- Get a list of aliases to the items.
    -- (Individual Finder references might fail when renaming items within renamed folders.)
    try
    set item_list to item_reference as alias list
    on error
    set item_list to item_reference as alias as list
    end try
    if item_list is not {} then
    -- If there are any relevant items, get their names.
    set current_names to name of item_reference
    -- Doctor each name...
    repeat with i from 1 to (count current_names)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to search_string
    set text_items to text items of (item i of current_names)
    set AppleScript's text item delimiters to replacement_string
    set newitemname to text_items as Unicode text
    set AppleScript's text item delimiters to astid
    -- ... and rename the associated item.
    my setitemname(item i of item_list, newitemname)
    end repeat
    end if
    end tell
    end open
    beep 2
    on setitem_name(thisitem, newitemname)
    tell application "Finder"
    --activate
    set the parent_container to (the container of this_item)
    if not (exists item newitemname of the parent_container) then
    try
    set the name of this_item to newitemname
    on error the error_message number the error_number
    if the error_number is -59 then
    set the error_message to "This name contains improper characters, such as a colon (:)."
    else --the suggested name is too long
    --set the error_message to error_message -- "The name is more than 31 characters long."
    end if
    --beep
    set newitemname to my getnew_name(errormessage, newitemname)
    if (newitemname is 0) then return 0
    my setitem_name(thisitem, newitemname)
    end try
    else --the name already exists
    --beep
    set newitemname to my getnewname("This name is already taken, please rename.", newitemname)
    if (newitemname is 0) then return 0
    my setitem_name(thisitem, newitemname)
    end if
    end tell
    end setitemname
    on getnewname(msg, default_answer)
    tell application (path to frontmost application as Unicode text)
    set {text returned:newitemname, button returned:button_pressed} to (display dialog msg default answer default_answer buttons {"Cancel", "Skip", "OK"} default button 3)
    if (button_pressed is "OK") then
    return newitemname
    else if (button_pressed is "Skip") then
    return 0
    else
    error number -128 -- only necessary on non-English systems.
    end if
    end tell
    end getnewname
    Various Mixed Macs   Mac OS X (10.4.3)  
    Various Mixed Macs   Mac OS X (10.4.3)  

    Hi lunarlandr and welcome to Apple Discussions!
    Without going through the script in detail, there's a lot that can be stripped out, and a few goodies that can be added.
    Droplets work best when iterating through lists (even one-item lists) of Finder items. As a brief example:
    on open (these_objects)
    repeat with each_object in these_objects
    --do something with each object in turn
    end repeat
    end open
    You need to remove the line beginning "choose folder" and let each_object become your source folder.
    The code below is rough and may need some amendment, but it should answer most of your questions. Test it and see.
    --begin script
    on run
    display dialog "I'm a droplet! Drop things on me!" buttons {"OK"} default button 1 with icon note
    --although you could incorporate a choose folder here
    end run
    on open (these_objects) -- a list of aliases
    repeat with each_object in these_objects
    set item_info to info for each_item
    set folder_contents to (list folder item_info)
    if kind of item_info is "Folder" and folder_contents contains "0000_Readme" then -- only process job folders
    set job_number to text 3 thru 6 of name of item_info
    process (eachobject,jobnumber)
    else --not a job folder
    display dialog "I only work with proper job folders." buttons {"OK"} with icon note giving up after 3 -- move on to next item in list
    end if
    end open
    on process (topfolder,jobnumber)
    tell application "Finder"
    set folder_contents to every item of top_folder
    repeat with each_item in folder_contents
    set generic_name to name of each_item
    if generic_name begins with "0000_" then
    set name of each_item to job_number & text 5 thru -1 of generic_name --everything from the underscore to the end
    end if
    end repeat
    end tell
    end process
    --end script
    The droplet will process multiple folders with different job numbers, without any user interaction. The name of the internal files and folders is derived from the name of the dropped folder.
    Hope it helps,
    (Although I don't see why the accounting software shouldn't do all of this for you...)
    H

  • Stopping Automator "Run Applescript" if file not found.

    Hi all,
    I'm creating a folder action that, when a file is added to the folder, will search the folder to see if the file is of a certain type (by the extension) and then run an Applescript that will open the file in the appropriate program. The problem is that not all files that go into the folder are of the correct type. Is there any way to tell Automator or Applescript to stop if no file is found (essentially "input" should be empty)?
    Thanks,
    Stuart

    Thank you for a helpful answer. I recently wrote an Automator application that opens several web pages in tabs and checks my email. It is set to run at login. Using a modification of your code and a line I pick up elsewhere I was able to make the Automator application end when I press command+. keys.
    Perhaps you can answer a different question for me. I am new to Automator but catching on quickly. I am not very good at AppleScript however. I have three automator-based workflows saved as applications. One needs to run every day and then trigger one of the other two depending upon the day or date.
    The branching seems to work OK but once the appropriate workflow starts to run I get an error. I think it is -1708. Any help you can provide would be appreciated.
    2 Gig G5   Mac OS X (10.4.7)  

  • Searching Directories and Files in Application Server

    Hi All,
    I need a function module that will give me all FOLDERS, SUBFOLDERS and FILES in an application server.
    So far function modules like RZL_READ_DIR_LOCAl, SUBST_GET_FILE_LIST and EPS_GET_DIRECTORY_LISTING can only work if I specify at least one folder name after the server IP.
    I wanted the folder names to be searched dynamically by passing only server IP.
    This is for a background program.
    Please help
    Thanks in advance.
    Regards,
    Lily

    Done.

  • Using Powershell to get current permissions of folders/sub-folders and files

    Hi Team
    Need assistance here.
    Need a powershell script to get and list current AD groups and users having permissions to folders/its subfolders and files
    Cheers

    Hello,
    The TechNet Wiki Discussion Forum is a place for the TechNet Wiki Community to engage, question, organize, debate, help, influence and foster the TechNet Wiki content, platform and Community.
    Please note that this forum exists to discuss TechNet Wiki as a technology/application.
    As it's off-topic here, I am moving the question to the
    Where is the forum for... forum.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • Taking Ownership of folders and files

    So I am doing what sure seems like way too much work to do something rather simple in GUI. There seem to be many topics on this and I base my code off of their results, but it isn't working entirely. Hopefully an easy one for you folks!  I am trying
    to take ownership of a path, be it a file or folder.  I DO NOT want to use a separate module like PSCX as not all machines will have the module.
    I created a function based off the code I found at the end of
    http://social.technet.microsoft.com/Forums/en-US/87679d43-04d5-4894-b35b-f37a6f5558cb/ that I can pass a path to singularly or I was hoping to be able to pipe Get-ChildItem to it.  When I do "Get-ChildItem -Path D:\Permissions\TopFolder -Recurse
    -Force | Take-Ownership" it seemed to work, but then I noticed it only seems to work going one layer deep. The text output for troubleshooting shows it recursing all the way through, but yet Owner is not being set all the way down.
    Folder layout:
    D:\Permissions\TopFolder
    D:\Permissions\TopFolder\FirstFolder
    D:\Permissions\TopFolder\FirstFile.txt
    D:\Permissions\TopFolder\FirstFolder\SecondFolder
    D:\Permissions\TopFolder\FirstFolder\SecondFile.txt
    D:\Permissions\TopFolder\FirstFolder\SecondFolder\ThirdFolder
    D:\Permissions\TopFolder\FirstFolder\SecondFolder\ThirdFile.txt
    Function Take-Ownership {
    [CmdletBinding(DefaultParameterSetName=”Set01”)]
    Param(
    [parameter(Mandatory=$true,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,Position=1,ParameterSetName='Set01')]
    [string]$Path,
    [parameter(Mandatory=$true,ValueFromPipelinebyPropertyName=$True,ParameterSetName='Set02')]
    [Alias('FullName')][string]$FullPath
    ) # End of Param()
    Begin {
    # Check that script was Run as Administrator
    If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host -ForegroundColor Red -BackgroundColor Black "`n ERROR: You MUST have Administrator rights to run this script!"
    Write-Host -ForegroundColor Red -BackgroundColor Black " Re-run this script as an Administrator!`n"
    Break
    #P/Invoke'd C# code to enable required privileges to take ownership and make changes when NTFS permissions are lacking
    $AdjustTokenPrivileges = @"
    using System;
    using System.Runtime.InteropServices;
    public class TokenManipulator
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
    ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
    [DllImport("kernel32.dll", ExactSpelling = true)]
    internal static extern IntPtr GetCurrentProcess();
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr
    phtok);
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool LookupPrivilegeValue(string host, string name,
    ref long pluid);
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    internal struct TokPriv1Luid
    public int Count;
    public long Luid;
    public int Attr;
    internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
    internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
    internal const int TOKEN_QUERY = 0x00000008;
    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
    public static bool AddPrivilege(string privilege)
    try
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_ENABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
    catch (Exception ex)
    throw ex;
    public static bool RemovePrivilege(string privilege)
    try
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_DISABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
    catch (Exception ex)
    throw ex;
    Add-Type $AdjustTokenPrivileges
    # Activate necessary admin privileges to make changes without NTFS perms on the folder
    [void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") # Necessary to set Owner Permissions
    [void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") # Necessary to bypass Traverse Checking
    [void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") # Necessary to override File Permissions
    $Admin = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")
    $NewDirACL = New-Object System.Security.AccessControl.DirectorySecurity
    $NewFileACL = New-Object System.Security.AccessControl.FileSecurity
    $NewDirACL.SetOwner($Admin)
    $NewFileACL.SetOwner($Admin)
    } # End of Begin {}
    Process {
    if( $FullPath.Length -gt 0 ) {
    if( Test-Path $FullPath ) {
    $Path = $FullPath
    if( Test-Path $Path -PathType Container ) {
    "Take Ownership: $Path"
    $Folder = Get-Item $Path -Force
    $Folder.SetAccessControl($NewDirACL)
    } elseif( Test-Path $Path -PathType Leaf ) {
    "Take Ownership: $Path"
    $File = Get-Item $Path -Force
    $File.SetAccessControl($NewFileACL)
    } else {
    Write-Host -ForegroundColor Red -BackgroundColor Black "ERROR: Path does not exist: $Path"
    } # End of Process {}
    End { } # End of End {}
    } # End of Function Take-Ownership
    To run this I have been doing:
    PS D:\> $Folder = 'D:\Permissions\TopFolder'
    PS D:\> Get-Item $Folder | Get-Acl
    Directory: D:\Permissions
    Path Owner
    TopFolder DOMAIN\user1
    PS D:\> Get-ChildItem $Folder -Force -Recurse | Get-Acl
    Directory: D:\Permissions\TopFolder
    Path Owner
    FirstFolder DOMAIN\user1
    FirstFile.txt DOMAIN\user1
    Directory: D:\Permissions\TopFolder\FirstFolder
    Path Owner
    SecondFolder DOMAIN\user1
    SecondFile.txt DOMAIN\user1
    Directory: D:\Permissions\TopFolder\FirstFolder\SecondFolder
    Path Owner
    ThirdFolder DOMAIN\user1
    ThirdFile.txt DOMAIN\user1
    PS D:\>
    PS D:\> Get-Item $Folder | Take-Ownership
    Take Ownership: D:\Permissions\TopFolder
    PS D:\> Get-ChildItem $Folder -Force -Recurse | Take-Ownership
    Take Ownership: D:\Permissions\TopFolder\FirstFolder
    Take Ownership: D:\Permissions\TopFolder\FirstFile.txt
    Take Ownership: D:\Permissions\TopFolder\FirstFolder\SecondFolder
    Take Ownership: D:\Permissions\TopFolder\FirstFolder\SecondFile.txt
    Take Ownership: D:\Permissions\TopFolder\FirstFolder\SecondFolder\ThirdFolder
    Take Ownership: D:\Permissions\TopFolder\FirstFolder\SecondFolder\ThirdFile.txt
    PS D:\>
    PS D:\>
    PS D:\> Get-Item $Folder | Get-Acl
    Directory: D:\Permissions
    Path Owner
    TopFolder BUILTIN\Administrators
    PS D:\> Get-ChildItem $Folder -Force -Recurse | Get-Acl
    Directory: D:\Permissions\TopFolder
    Path Owner
    FirstFolder BUILTIN\Administrators
    FirstFile.txt BUILTIN\Administrators
    Directory: D:\Permissions\TopFolder\FirstFolder
    Path Owner
    SecondFolder DOMAIN\user1
    SecondFile.txt DOMAIN\user1
    Directory: D:\Permissions\TopFolder\FirstFolder\SecondFolder
    Path Owner
    ThirdFolder DOMAIN\user1
    ThirdFile.txt DOMAIN\user1
    PS D:\>
    I don't know why this isn't working.  The output text shows I went through the subfolders and files...HELP!
    Find this post helpful? Does this post answer your question? Be sure to mark it appropriately to help others find answers to their searches.

    Here is the end result. I am looking to add a '-Recurse'/'-Force' switches to give another option to not have to Get-ChildItem and pipe it to the function and possibly a '-User' parameter to be able to specify who to set as owner, but both of those ideas
    are untested.
    Here is the code.  Hope it helps someone else.
    Function Take-Ownership {
    <#
    .SYNOPSIS
    This function takes ownership of a file or folder and sets it back to 'BUILTIN\Administrators'.
    .DESCRIPTION
    This function takes ownership of a file or folder and sets it back to 'BUILTIN\Administrators'.
    This will work even when the user does not have ownership or existing permissions on the file or folder.
    .EXAMPLE
    PS C:\> Take-Ownership -Path $Path
    Takes ownership of the individual folder or file. The -Path is optional as long as $Path
    is the first parameter.
    .EXAMPLE
    PS C:\> Get-Item $Path | Take-Ownership
    Takes ownership of the individual folder or file.
    .EXAMPLE
    PS C:\> Get-ChildItem $Path -Recurse -Force | Take-Ownership
    Recurse through all folders and files, including hidden, and takes ownership.
    #>
    [CmdletBinding()]
    Param(
    [parameter(Mandatory = $true, ValueFromPipeline = $True, ValueFromPipelinebyPropertyName = $True, Position = 0)]
    [Alias('FullName')]
    [string]$Path
    ) # End of Param()
    Begin {
    # Check that script was Run as Administrator
    If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host -ForegroundColor Red -BackgroundColor Black "`n ERROR: You MUST have Administrator rights to run this script!"
    Write-Host -ForegroundColor Red -BackgroundColor Black " Re-run this script as an Administrator!`n"
    Return
    #P/Invoke'd C# code to enable required privileges to take ownership and make changes when NTFS permissions are lacking
    $AdjustTokenPrivileges = @"
    using System;
    using System.Runtime.InteropServices;
    public class TokenManipulator
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
    ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
    [DllImport("kernel32.dll", ExactSpelling = true)]
    internal static extern IntPtr GetCurrentProcess();
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr
    phtok);
    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool LookupPrivilegeValue(string host, string name,
    ref long pluid);
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    internal struct TokPriv1Luid
    public int Count;
    public long Luid;
    public int Attr;
    internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
    internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
    internal const int TOKEN_QUERY = 0x00000008;
    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
    public static bool AddPrivilege(string privilege)
    try
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_ENABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
    catch (Exception ex)
    throw ex;
    public static bool RemovePrivilege(string privilege)
    try
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_DISABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
    catch (Exception ex)
    throw ex;
    Add-Type $AdjustTokenPrivileges
    # Activate necessary admin privileges to make changes without NTFS perms on the folder
    [void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") # Necessary to set Owner Permissions
    [void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") # Necessary to bypass Traverse Checking
    [void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") # Necessary to override File Permissions
    } # End of Begin {}
    Process {
    # Process for taking Ownership of the folder
    # - Specify the NT Account user to set as Owner (BUILTIN\Administrators)
    # - Create a new ACL object for the sole purpose of defining a new owner
    # - Establish the new ACL as owned by BUILTIN\Administrators, thus
    # guaranteeing the following ACL changes can be applied.
    # - Then apply that update to the existing folder's ACL which merges
    # the proposed changes (new owner) into the folder's actual ACL
    # - - IN OUR CASE OVERWRITING THE OWNER
    # - Additional Documentation:
    # http://msdn.microsoft.com/en-us/library/System.Security.AccessControl(v=vs.110).aspx
    $Admin = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")
    $NewDirACL = New-Object System.Security.AccessControl.DirectorySecurity
    $NewFileACL = New-Object System.Security.AccessControl.FileSecurity
    $NewDirACL.SetOwner($Admin)
    $NewFileACL.SetOwner($Admin)
    if( Test-Path $Path -PathType Container ) {
    $Folder = Get-Item $Path -Force
    $Folder.SetAccessControl($NewDirACL)
    } elseif( Test-Path $Path -PathType Leaf ) {
    $File = Get-Item $Path -Force
    $File.SetAccessControl($NewFileACL)
    } else {
    Write-Host -ForegroundColor Red -BackgroundColor Black "ERROR: Path does not exist: $Path"
    } # End of Process {}
    End { } # End of End {}
    } # End of Function Take-Ownership
    Find this post helpful? Does this post answer your question? Be sure to mark it appropriately to help others find answers to their searches.

  • Use AppleScript or Automator (or both) to get Mail and add to a text file?

    Hello all,
    I'm sorry if this is a duplicate of a well-known topic, I tried searching and couldn't see anything.
    I'm behind a proxy at work that blocks any kind of webmail access, but I'd like to be able to check my email while on a break or something.
    I had the idea that I could use Automator or Applescript to check my mail, get the new messages and add the text to a textfile that I could host on my personal webserver that I use for family stuff.
    I've tried an automator workflow that seems to work while in Automator, but when I save it as an application, it won't even start Mail to check.
    I also thought of just leaving mail running, and have a rule that starts a script when new mail arrives, but I don't know enough about Applescript to do it.
    I don't want to confuse anyone with the details of my convoluted ideas, so I'll leave it at that.
    Is there a way to do this? I want mail to check the server, download the messages, new messages get their text appended to a text file that's stored in my webserver's directory (same computer) that I can access from the web, and have it repeat every 5 minutes or so.
    If I've left out a detail, let me know, and if I'm just stupid and there's an easy way to do this... be kind.
    Thanks!
    aeix
    iMac G5 2.0 GHz   Mac OS X (10.4.6)  

    It certainly is going in the right direction. I'm not all that versed in AppleScript, but it looks like that particular script is creating a new text file for every message processed.
    I would like to either create a specific text file if it doesn't exist, or append the text to the end of the file if it does exist.
    But like I said, definitely heading in the right direction!
    iMac G5 2.0 GHz Mac OS X (10.4.6)

  • Automator or Applescript using png files with alpha channel

    I have hundred of png files with alpha channel.
    I want to suppress alpha channel.
    How can i do it using Automator or Applescript ?
    Thank you very much.

    You can use the free command line image processing tool ImageMagick in your Applescripts or Automator workflows, as well as from a Terminal shell.
    You can download ImageMagick from http://www.imagemagick.org, but Cactuslab has simplified installation by putting together an installer package. It’s available at  http://cactuslab.com/imagemagick/. Download the package and double-click on it. Follow the instructions to install. It will install ImageMagick into /opt/ImageMagick and add it to your $PATH by creating a file in /etc/paths.d/. Restart your computer for the changes to take effect.
    The two ImageMagick commands we’re concerned with are “convert” and “mogrify”. Convert is more efficient for multiple and piped operations on the same image file, and mogrify is more efficient for batch processing. Generally speaking, convert will output a file separate from the input file. Unless a path is specified, mogrify will overwrite the input file with the output file. An important distinction.
    You can perform various operations on the alpha channel using arguments after either the convert or mogrify command. Two of the available arguments are:
    -alpha off - Disables the image's transparency channel. Does not delete or change the existing data, just turns off the use of that data.
    -alpha remove - Composite the image over the background color.
    Also of use are the -flatten and -background options:
    -flatten - overlay all the image layers into a final image and may be used to underlay an opaque color to remove transparency from an image.
    -background - sets the background color.
    Start off using the convert command with a single image to see the effect and adjust to your liking. Once you’ve achieved the desired outcome, then use the mogrify command to batch process the chosen images.
    Before getting into how to use Automator or Applescript in your workflow, use Terminal and the command line to see the effect on a single image. Copy one image to your ~/Desktop. In Terminal change the directory to ~/Desktop by typing the following command and pressing the Enter key:
    cd ~/Desktop
    Then choose the option you are looking for, -alpha remove for instance, type the following command and press the Enter key:
    convert input-photo.png -alpha remove output-photo.png
    You can check the alpha channel (transparency) and background in the Preview app, go View > Show Image Background from the menu bar.
    Once you’re ready to batch proces, place all the photos you want to convert with the same command into one folder. Copy the folder to your ~/Desktop. Let’s assume you’ve labeled the folder “InPhotos”. It’s prudent to manipulate copies in case something goes amiss. In that event you can copy the folder with the originals again and start over. Create a new empty folder on your ~/Desktop and call it “OutPhotos”. Let’s also assume your home directory is called “Me”. The following command will process the photos from the InPhotos folder and put them in the OutPhotos folder:
    mogrify -alpha remove -path /Users/me/Desktop/OutPhotos/ /Users/me/Desktop/InPhotos/*png
    According to Apple Technical Note TN2065:
    "when you use just a command name instead of a complete path, the shell uses a list of directories (known as your PATH) to try and find the complete path to the command. For security and portability reasons, do shell script ignores the configuration files that an interactive shell would read"
    So, you need to use the full path to to ImageMagick commands, unlike in the shell where you can just use the command name.
    To batch process using Automator, use the “Run Shell Script” action (note: retain the single space at the beginning of the last line):
    /opt/ImageMagick/bin/mogrify \
    -alpha remove \
    -path /Users/Me/Desktop/OutPhotos/ \
    /Users/Me/Desktop/InPhotos/*png
    To batch process using Script Editor (Applescript), use the “do shell script” command:
    do shell script "/opt/ImageMagick/bin/mogrify -alpha remove -path /Users/pd/Desktop/OutPhotos/ /Users/pd/Desktop/InPhotos/*png"
    Further info on ImageMagick:
    http://www.imagemagick.org/script/command-line-options.php#alpha
    http://www.imagemagick.org/Usage/masking/#remove
    http://www.imagemagick.org/index.php
    http://www.imagemagick.org/script/command-line-tools.php
    http://www.imagemagick.org/script/command-line-options.php
    Examples:
    The original PNG image:
    -alpha off:
    -alpha remove:
    -background black -flatten:
    -background blue -flatten:
    -channel alpha -evaluate Divide 2:
    -channel alpha -evaluate Divide 2 -background black -flatten:

  • Getting Automator or AppleScript to start up QuickTime and play a radio sta

    I am new to Automator and have never tried AppleScript.
    I would like my Mac to start up and play a radio station. I have been successful in getting the link to work in QuickTime or play directly in Safari. However, when I try to use Automator to start QuickTime and play the link, uh, nothing happens. When I save the workflow to the desktop and click on it, it opens up Automator.
    I would have expected that running the workflow would open up QuickTime and then load the link and play it.
    I am missing something here and getting frustrated with the documentation.
    I could use AppleScript, but know nothing about it and have not been able to find a already made AppleScript online.

    When I save the workflow to the desktop and click on it, it opens up Automator.
    It would appear that you're saving the workflow as a workflow rather than saving it as an application. In Automator's Save dialog, look for the File Format drop-down and select Application instead.
    Beyond that, without knowing the stream's URL or the stream's referring web page it would be difficult to say with certainty what the best approach might be. If you could post the URL that would help. A few questions that come to mind: Is the radio station a live streaming AM or FM station? A podcast? What file format is used? Does a .qtl file or some other file get downloaded to your desktop when you click on the "listen live" link from the referring radio station's web page?
    For example, when I click on "Click to listen with Quicktime" at kgoam810.com a listenlive.qtl file is downloaded to my desktop. In this case the Automator workflow would be easy to set up, using these two Finder library actions:
    1) *Get Specified Finder Items* -- click on the "+" sign, navigate to the listenlive.qtl file and select it.
    2) *Open Finder Items* -- set it to open with the default application.
    Save the workflow as an application and add to your Login Items.
    If no file is downloaded and you have only the stream's URL, you may be able to cobble together a workflow which makes use of a GUI type applescript. I've had success using the following actions:
    1) *Get Specified Text* -- from Automator's TextEdit library. Simply type in or paste the URL into the text box.
    2) *Copy to Clipboard* -- from Automator's System library.
    3) *Run AppleScript* -- from the Automator library. The script shown below has worked for me. Copy the code and paste it into the Run AppleScript box, overwriting what's pre-populated there:
    *on run {input, parameters}*
    *tell application "QuickTime Player"*
    activate
    *tell application "System Events"*
    *tell process "QuickTime Player"*
    *keystroke "u" using command down*
    *keystroke "v" using command down*
    *delay 1*
    *keystroke return*
    *end tell*
    *end tell*
    *end tell*
    *return input*
    *end run*
    Compile the script by clicking on the hammer icon in the Run AppleScript box and save the workflow as an application. Add it to your Login Items.
    Note that as a GUI applescript is being used here, you should have "Enable access for assistive devices" checked under System Preferences > Universal Access. Also, under the QuickTime Player's Preferences > Other, make sure that "Show Content Guide automatically" is unchecked.
    Your mileage may vary... Good luck!
    Andrew99

  • Automator: Create 3 folders resize images and move .mov files?

    Hi there,
    I am new to automator but would like to learn how to use it.
    On daily basis I get a bunch of pictures and videos in high resolution.
    I would like to automate the following process:
    1. Create 3 folders: HQ, LQ, video
    2. Move the original high resulution .jpeg files to HQ folder
    3. Resize the files to 800x600px (landscape) or 600x800px (portrait) and save them in LQ
    4. Move the .mov video files into video folder
    5. Rename all JPEG files in LQ to a value that I can enter at this time (for example I type "3 bedroom apartment munich" and it will rename it to "3 bedroom apartment munich-1.jpg, ...-2.jpg, ...3.jpg, ...)
    Is this even possible with automator or do I have to use additional tools like "A Better Finder Rename 9"?
    Looking forward for some input to get started. Thanks for all who help me to get my daily job done much faster.
    Cheers,
    Chris

    You can start with this workflow. Download it (below) so you can see how it works. This is a workflow to handle the HQ and LQ options. On the video, that would be a separate workflow but easier -- you would just not combine it with this process.
    Let me know what you think and if we need to tweak it, then post back.
    Here is the workflow for you to download

  • Advanced applescript to rename files

    Hi Everybody,
    I am trying to do some applescript to rename files.
    I know some tips to do that, but I try to write an advanced script with many options
    For example : A file to rename :
    "project-test.info.jpg"
    1st :
    I would like the script to find every symbols in the name(without the extension), like here : "-" or "_"
    and repace these symbols with another one like "_"
    then the new name will be :
    "project_test_info.jpg"
    2nd :
    if the file is named in a "wrong way", like :
    test.jpg
    or
    "test-info.jpg"
    or
    "project.test.jpg"
    etc
    then the script will rename in the better way :
    "project_test_information.jpg"
    (information will be data I will enter by myself)
    And many other or examples with all the possibilities to rename...
    I succeed to rename some parts of the name, but I don't find the solution to replace symbols, and how to count the number of text parts and replace the good ones...
    I dont know even if it's a good way to do like that in fact, an maybe it's possible in another way ?
    Thank you very much for your answers !

    Hi Everybody,
    I am trying to do some applescript to rename files.
    I know some tips to do that, but I try to write an advanced script with many options
    For example : A file to rename :
    "project-test.info.jpg"
    1st :
    I would like the script to find every symbols in the name(without the extension), like here : "-" or "_"
    and repace these symbols with another one like "_"
    then the new name will be :
    "project_test_info.jpg"
    2nd :
    if the file is named in a "wrong way", like :
    test.jpg
    or
    "test-info.jpg"
    or
    "project.test.jpg"
    etc
    then the script will rename in the better way :
    "project_test_information.jpg"
    (information will be data I will enter by myself)
    And many other or examples with all the possibilities to rename...
    I succeed to rename some parts of the name, but I don't find the solution to replace symbols, and how to count the number of text parts and replace the good ones...
    I dont know even if it's a good way to do like that in fact, an maybe it's possible in another way ?
    Thank you very much for your answers !

Maybe you are looking for

  • Geforce 4Ti4800SE Questions

    Hello, About a month ago I purchased the Geforce 4 Ti4800Se, it's fantastic, and just recently I've been getting urges to overclock it's core speed of 275Mhz, and it's 554Mhz DDR RAM Speed. So first I researched if it'd be a smart thing to do, I came

  • Dropped my phone and now my display is white

    I dropped my phone (the one and only time!) and now the display is white.  I took the battery out, waited a little while and popped it back it.  Usually, you have to then turn the phone on and wait for it to boot up, but it just goes back to being a

  • Table updation for J2IUN available balance

    Hi Experts !!   I have my "available balance" in J2IUN is wrong. So I want to correct this balance through table level. Please let me know the procedure & table names for updating this balance. Thanks & Regards,        Aruna.

  • Error running create expense page from jsp

    Hi, I am getting the following exception while running the create expense page from Jdev using a jsp. I have FTPed all the files from OA_JAVA and AP_TOP to my local machine. Created a new project and imported the files to this project. To run the cre

  • Trying to upgrade CS4 to CS5.5

    I am currently trying to upgrade CS4 Design Standard to CS5.5 Design Premium on PC. When I entrer serial number for CS4, the setup program says it is not a qualifying product. (even though it is say it is on menu). I had the same issue when I upgrade