Rename a set of files in Power Shell

Hello Scripting Guys,
I am trying to rename a group of files in a given directory.  The files all start with a number and a dash (such as "1 - " or "24 - ") when I first get them. Sometimes there are files that do not start with a number or a dash in
the same directory, but I don't want to bother with those.  Of the files that do have a number and a dash, they should all be .SQL text files (have a .SQL extension).  
I want to loop through all files that meet these criteria and then rename them to the same name, but without the number and the dash.  For example a file may have a name like "1 - cust_sp_Get_Last_Order.sql"  I want to just rename this
to "cust_sp_Get_last_order.sql" and be done with it.  
I would be done by now in VBScrpt, but I am trying to learn the bloody PowerShell and it is driving me crazy.
Here is what I came up with, but it chokes on the substring piece.  If I test the substring bit by itself with variables it seems to work fine.  it just does not work in this script.  Please help.
$depfiles = gci c:\Temp -filter *.txt              
$depfiles | %{ [int]$dash_pos = $_.name.indexof("-"); 
               [int]$start = $dash_pos+2;
               [int]$dot = $_.name.indexof(".");
               [int]$end = $dot+3;
               $start; $dot; $end;
               [string]$nameonly = $_.name;
               $new_name = $nameonly.substring($start, $end);
               write "Name:" $nameonly; write "New Name:" $new_name
And this is what I get in return....
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within 
the string.
Parameter name: length"
At C:\Users\Tom\Desktop\3rd try.ps1:9 char:47
+                $new_name = $nameonly.substring <<<< ($start, $end);
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
Thank you.

Thank you both very much.
This was very helpful. The problem was I was passing the wrong value to Substring's second parameter.  The value was too high.  The value should be calucated as Brian noted: $length = $_.name.Length - $Start is correct.  I was counting spaces
from start of the string and not after the dash.
I had put "*.txt" to test it out on some test files but forgot to change it back.
Here's a semi-working version.   
$destination = "c:\deployed\"
$depfiles = gci c:\Temp -filter *.sql
cd c:\temp
$depfiles | %{ [string]$nameonly = $_.name;
               [int]$dash_pos = $_.name.indexof("-"); 
               [int]$start = $dash_pos+2;
               [int]$end = $nameonly.length;
               $end = $end-$start;
               $new_name = $nameonly.substring($start, $end);
               write ""; 
               write "";
               if ($dash_pos -gt 0) {
                    write "Name:" $nameonly; write "New Name:" ($destination + $new_name);
                    rename-item -Path $_.fullname -NewName ($destingation + $new_name);    
The rename-item cmdlet is only renaming them in the current directory, and not moving them to the deployed folder, but I need to play with it some more.  
The variables all look right however.  Any ideas?
Output:
Name:
100 - some data.sql
New Name:
c:\deployed\some data.sql
Name:
2 - big data.sql
New Name:
c:\deployed\big data.sql
Name:
99 - this is a test.sql
New Name:
c:\deployed\this is a test.sql

Similar Messages

  • Scan a Excel file via power Shell

    Hi;
    I have in input a Excel File (3 colunms) to create automatically the sites collections (CS) and thier sites (SITES) :
    INUPUT :
    DECC    CS       SITES
    dec1    paris     site1
    dec1    paris     site2
    dec1    paris     site3
    dec1    nice      site1
    dec1    nice      site2
    dec1    nimes   site1
    dec2   ales       site1
    dec2   ales       site2
    dec2   sete       site1
    etc...
    How scan the Excel file via power shell to create the sites + collections in reading like this :
    dec 1 -- paris
                         -- site1 & site2 & site3
             --  nice
                         -- site1 & site 2
             -- nimes
                        -- site1
    dec 2 -- ales
                      -- site1 & site2
             -- sete
                      -- site1
    Regards;

    Hello soussou97,
    My approach is to save the values of your first and second column (the columns you want to sort your values with) in ArrayLists and then use dynamic variables to save the actual content. Look at the following code. It should be able to display the information
    you need. 
    #Specify the path of the excel file
    $FilePath = 'Path\file.xlsx'
    #Specify the Sheet name
    $SheetName = "Sheet"
    # Create an Object Excel.Application using Com interface
    $objExcel = New-Object -ComObject Excel.Application
    # Disable the 'visible' property so the document won't open in excel
    $objExcel.Visible = $false
    # Open the Excel file and save it in $WorkBook
    $WorkBook = $objExcel.Workbooks.Open($FilePath)
    # Load the WorkSheet 'BuildSpecs'
    $WorkSheet = $objExcel.sheets.item($SheetName)
    # I am taking row count as 2, because the first row in my case is header
    $intRow = 2
    [System.Collections.ArrayList]$farr = @()
    [System.Collections.ArrayList]$sarr = @()
    Do {
    # Reading the first column of the current row
    $First = $WorkSheet.Cells.Item($intRow, 1).Value()
    # Reading the second column of the current row
    $Second = $WorkSheet.Cells.Item($intRow, 2).Value()
    # Reading the third column of the current row
    $Third = $WorkSheet.Cells.Item($intRow, 3).Value()
    "First: " + $First
    "Second: " + $Second
    "Third :" + $Third
    if($farr -notcontains $First){
    $farr.Add($First)
    if($sarr -notcontains $Second){
    $sarr.Add($Second)
    $variable = Get-Variable -Name "$First-$Second" -Scope Global -ErrorAction SilentlyContinue
    if ($variable -eq $null)
    Write-Host "$First-$Second does not exist"
    New-Variable -Name "$First-$Second" -Value $Third
    else{
    $val = Get-Variable -Name "$First-$Second" -ValueOnly
    Set-Variable -Name "$First-$Second" -Value $val","$Third
    $intRow++
    }While ($WorkSheet.Cells.Item($intRow,1).Value() -ne $null)
    foreach($dec in $farr){
    foreach($city in $sarr){
    $variable = Get-Variable -Name "$dec-$city" -Scope Global -ErrorAction SilentlyContinue
    if ($variable -ne $null){
    $dec+"--"+$city+"--"+$variable.Value;
    my sample data looks like this
    col1 | col2 | col3
    abc | qwe | poi
    abc | jhg | dfg
    de | wer | rew
    de | iuz | mnb
    abc | qwe | iop
    de | wer | asd
    Regards,
    Hristo Valev
    Developer-Hotline for MSDN Online Germany
    Disclaimer:
    Please take into consideration, that further inquiries cannot or will be answered with delay.
    For further information please contact us per telephone through the MSDN-Entwickler-Hotline:
    http://www.msdn-online.de/Hotline
    For this post by the MSDN-Entwickler-Hotline the following terms and conditions apply:
    Trademarks,
    Privacy
    as well as the separate
    terms of use for the MSDN-Entwickler-Hotline.

  • Faster way to read XML files using power shell !!

    At the moment i have about 1000 XML files (ranging from size 15kb to 120kb), I have a powershell script which extracts information and writes all extracts to the same LOG file!!
    It works well but am only concerned with the time it takes!! it took about 1.5 hrs to finish the script! Is this normal?
    How can i speed it up, your inputs and thoughts helps!!
    Reading XML using the following syntax!
    $Inputfile=[xml](Get-Content $XFILE)
    Script has only foreach loop!  and no other conditions.
    cheers!

    For a small file it is about twice as fast.  It gets faster as the file size gets bigger.
    PS C:\scripts> Measure-Command {$xml=[xml](cat FooProx.xml -raw)}
    Days : 0
    Hours : 0
    Minutes : 0
    Seconds : 0
    Milliseconds : 275
    Ticks : 2758195
    TotalDays : 3.19235532407407E-06
    TotalHours : 7.66165277777778E-05
    TotalMinutes : 0.00459699166666667
    TotalSeconds : 0.2758195
    TotalMilliseconds : 275.8195
    PS C:\scripts> Measure-Command {$xml.Load("$pwd\FooProx.xml")}
    Days : 0
    Hours : 0
    Minutes : 0
    Seconds : 0
    Milliseconds : 108
    Ticks : 1081647
    TotalDays : 1.25190625E-06
    TotalHours : 3.004575E-05
    TotalMinutes : 0.001802745
    TotalSeconds : 0.1081647
    TotalMilliseconds : 108.1647
    ¯\_(ツ)_/¯

  • How to execute power shell script file inside DSC script resource

    Hi,
    How to execute /call powershell scirpt file inside DSC script resource , some thing like below and capture the status of execution.
    Node $AllNodes.NodeName
    Script ExecuteSQLDeploy
    #SetScript = {powershell.exe .\SQLDeploy.ps1  "param1" "param2" "param3" "param4" "param5" }
    #TestScript= {powershell.exe .\SQLDeploy.ps1  "param1" "param2" "param3" "param4" "param5 }
    #GetScript= { return $true;}
    Basawaraj

    Thanks for reply. 
     Now i am able to execute the power shell script with DSC. I  am getting no error when i run , but the script logic wrote inside  ( deploying sql incremental changes ) not working . I am using SQLCMD in the powershell script to deploy sql
    changes . Can you please elaborate on "script is compatible with DSC" , the script
    should not contain write-host cmdlet.... etc something like that.
    Copying recursively from ****************************** to ************************** succeeded.
    Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = root/Microsoft/Windows/DesiredStateConfiguration'.
    An LCM method call arrived from computer ************ with user sid **********************************************
    [V-BAKANT]: LCM:  [ Start  Set      ]
    [V-BAKANT]: LCM:  [ Start  Resource ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ Start  Test     ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ End    Test     ]  [[Script]ExecuteSQLDeploy]  in 0.1110 seconds.
    [V-BAKANT]: LCM:  [ Start  Set      ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ End    Set      ]  [[Script]ExecuteSQLDeploy]  in 0.3010 seconds.
    [V-BAKANT]: LCM:  [ End    Resource ]  [[Script]ExecuteSQLDeploy]
    [V-BAKANT]: LCM:  [ End    Set      ]
    [V-BAKANT]: LCM:  [ End    Set      ]    in  0.8810 seconds.
    Operation 'Invoke CimMethod' complete.
    Time taken for configuration job to complete is 0.923 seconds
    Basawaraj

  • How to run 'Get-AssignedAccess' or 'Set-AssignedAccess' power shell commands in c# Application

    Hi,
    I have console application using which i am trying to run power shell command  like 'Get-AssignedAccess' or 'Set-AssignedAccess'.
    i am using below code for this it is throwing exception 'Get-AssignedAccess' doesn't exist in cmdlet which is correct because these commands belongs to function category.
    using (PowerShell pwInstance = PowerShell.Create())
                            pwInstance .AddScript("Get-AssignedAccess");
                            var result = pwInstance .Invoke();
    How can we execute this kind of command using c#?
    Thanks,

    Hi prakashlight,
    Thank you for comming back and tell us the result. For more information about how to run PowerShell script in C# language, you can refer to this blogpost here:
    Executing PowerShell scripts from C#
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Setting the locale dynamically in .shell file

    Hi ,
    I am using <netuix:locale language="en"/> in .shell file for the header in Weblogic Portal 9.2 application.
    How i can set the language attribute dynamically as currently it is set to English that's why my header area always displays the text in English language for the first time when I login into my application.
    Looking forwar for the response
    Thanks in Advance
    Regards
    Gaurav

    Hi Guarav,
    The <netuix:locale> control is used within Portal Framework markup (.shell, .portlet, .portal, etc.) to specify the local for that resource's title and description. For example: if you have a file named headerFooter.shell, its English title might be "The Header-Footer Shell", and that's how you would identify the shell in the Portal Admin Tools. If you had users who spoke/read Spanish, you'd create a <netuix:locale> element for headerFooter.shell that had the title as "El Cabeza-Pata Shell" (or something :). What I'm saying is: that control only affects the localization of the title and description of that WLP resource itself, not its content.
    To change what language the text of your header uses, check out the i18n JSP tag library: http://download.oracle.com/docs/cd/E13155_01/wlp/docs103/javadocjsp/p13n/i18n/tld-summary.html.
    Hope that helps,
    George

  • Code for put attache file ? on power shell

    please help :  code for put attache file ? on power shell 

    #Send-MailMessage works in PS 2.0 +
    #To identify your PowerShell version - If nothing returns you are in Vesion 1.0
    $PSVersionTable
    #help command to know about Send-MailMessage
    help Send-MailMessage -Detailed
    $parameters = @{
    FROM = "From Address"
    TO= "To Address"
    SMTP = "SMTP"
    SUBJECT = "Testing"
    ATTACHMENT = "C:\Temp\Book1.csv"
    BODY = "Refer attached file"
    Send-MailMessage @parameters
    #help Link
    https://technet.microsoft.com/en-us/library/796227f5-c9ff-402d-8a04-cde9e0c180ee(v=wps.620).aspx
    Regards Chen V [MCTS SharePoint 2010]

  • Set the column order in document library using power shell

    hi all,
     am looking for a power shell script which set the column order in the document  library, when i try to upload a  document.
     ie; i am  uploading a  doc to the doc lib. which has the below columns:
     columnA -   [choice field  - mandatory ]
     columnB -   [lookup field  - mandatory ]
     columnC -   [single line of text  - optional ]
     columnD -   [choice field  - optional ]
     columnE -   [choice field  - mandatory ]
    now when  the end user uploads a   document in my doc lib, i would like to see the mandatory columns takes up the top order and then optional fields.
     columnA
     columnB
     columnE
     columnC
     columnD
    so, is there any script, through which i can set the mandatory columns which will be coming in top and the optional fields as next order

    This is sample PowerShell code to reorder fields in a content type of a list.
    $web = Get-SPWeb http://aissp2013/sites/TestSite
    $list = $web.Lists["MyList"]
    $contentType = $list.ContentTypes | where {$_.Name –eq "MyTestCT"}
    $ctArray = "Title","ColumnA","ColumnB","ColumnD","ColumnC"
    $contentType.FieldLinks.Reorder($ctArray)
    $contentType.Update()
    Blog | SharePoint Learnings CodePlex Tools |
    Export Version History To Excel |
    Autocomplete Lookup Field

  • Shell set up file getting hanged

    I am running a java application to read a file from remote machine using SSH API but the console waits for the read statement and my application is waiting for a response and that too I am in a while loop
    so I need to break the application and throw some sort of exception so that the user knows the status.Actually the shell set up file is getting hanged.
    How do I overcomethis problem?
    How can I know that the shell set up file is hanged?
    Is there anyway to find out the same?
    I will b thankful if someone could answer my point.

    Please stop creating new threads for the same subject. All of your threads seem to be on exactly the same thing.
    That said, I don't know how to help you with your problem.

  • Tagging in MMS and set the default search center url through power shell

    Hi,
     Would like to know below things are psosiblke through Power Shell.
    Check the checkbox from the term store management tool [ for Managed Metadata Serv.]'s navigation section and for the tagging feature.
    2) In the search setting section of site collection administration, i  need to enter the  default search center  url, [ i have created search center sub site in al of my site collections.] my site collectons in the farm is  more
    than 50. so i  cant enter the url of search center url [/sites/site1/sc/pages/results.aspx ] manually.

    can someone pls help...

  • Activate design manager (sandbox) solution using power shell - SP2013

    Hi All,
    I have a  design manager (sandbox) solution and deployed in site collection. I am trying to upload the new version using power shell.
    Uninstall-SPUserSolution , Remove-SPUserSolution, Add-SPUserSolution and finally doing Install-SPUserSolution on that time i am getting the following error " Install-SPUserSolution : This file may not be moved, deleted,
    renamed, or otherwise edited." kindly help me for this issue.
    Regards,
    Santhosh

    Can you please provide more details on your solution package? Did you use SharePoint Design Manager to create design package? If that is the case then if you read the following article it reads and 
    "In SharePoint 2013 you cannot uninstall an imported design package, and you should never attempt to deactivate a design package through the solution gallery." 
    I think if you read the article it might be helpful.
    http://msdn.microsoft.com/en-us/library/jj862342.aspx
    Amit

  • Trying to run Power shell Script on task schedule

    My case is i'm trying to run a power shell script through the task schedule.
    Note if i run the script locally it is working fine but from the task schedule it is not working.
    More information: 
    script function: Password Change Notification
    Task name : test3
    Time to do the task: 9:08 am every day
    the status : running 
    .ps1 file location: under C\windows\system32\
    some actions in the task history after the dated time to run:
    1 Task Scheduler launched "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}"  instance of task "\test3" due to a time trigger condition
    2 Task Engine "S-1-5-21-60622444-1628707926-2526327935-500: enviroment\Admin:S4U:LUA"  received a message from Task Scheduler service requesting to launch task "\test3" .
    3 Task Scheduler started "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}" instance of the "\test3" task for user "enviroment\admin
    4 Task Scheduler launched action ""C:\Windows\System32\Password Change Notification\Password Change Notification.ps1"" in instance "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}" of task "\test3
    5 Task Scheduler launch task "\test3" , instance "C:\Windows\System32\notepad.exe"  with process ID 5052

    Hi MeipoXu,
    First of all i would like to thank you for your answer, i followed the URL that you posted already in the previous comment and unfortunately it didn't work, and please find my ps1 file
    content as typed below and give me your feedback on that.
    #  # Version 1.1 May 2014
    # Robert Pearman (WSSMB MVP) # TitleRequired.com
    # Script to Automated Email Reminders when Users Passwords due to Expire.
    # # Requires: Windows PowerShell Module for Active Directory
    # # For assistance and ideas, visit the TechNet Gallery Q&A Page. http://gallery.technet.microsoft.com/Password-Expiry-Email-177c3e27/view/Discussions#content
    # Please Configure the following variables....
    $smtpServer="outlook. myDomain " $expireindays = 7
    $from = "الدعم الفني
    <ITHelpDesk@myDomain>"
    $logging = "Enabled" # Set to Disabled to Disable Logging
    $logFile = "PassExpireNotlog.csv" # ie. c:\mylog.csv
    $testing = "Enabled" ## "Enabled" # Set to Disabled to Email Users
    $testRecipient = "MyEmail@MyDomain"
    $encoding = [System.Text.Encoding]::Unicode $date = Get-Date -format ddMMyyyy
    # Check Logging Settings if (($logging) -eq "Enabled")
    {     # Test Log File Path
        $logfilePath = (Test-Path $logFile)     if (($logFilePath) -ne "True")
        {         # Create CSV File and Headers
            New-Item $logfile -ItemType File
            Add-Content $logfile "Date,Name,EmailAddress,DaystoExpire,ExpiresOn,MsgBody"
        } } # End Logging Check
    # Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired
    Import-Module ActiveDirectory $users = get-aduser -filter * -SearchScope Subtree -SearchBase "OU=UsersOU,DC=MyDomain,DC=MyrootDomain,DC=MYrootNS" -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet,
    EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }
    $maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
    # Process Each User for Password Expiry foreach ($user in $users)
    {     $Name = (Get-ADUser $user | foreach { $_.Name})
        $emailaddress = $user.emailaddress
        $passwordSetDate = (get-aduser $user -properties * | foreach { $_.PasswordLastSet })
        $PasswordPol = (Get-AduserResultantPasswordPolicy $user)
        # Check for Fine Grained Password
        if (($PasswordPol) -ne $null)     {
            $maxPasswordAge = ($PasswordPol).MaxPasswordAge
        $expireson = $passwordsetdate + $maxPasswordAge
        $today = (get-date)     $daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days
                 # Set Greeting based on Number of Days to Expiry.
        # Check Number of Days to Expiry
        $messageDays = $daystoexpire     if (($messageDays) -ge "2")
        {         $messageDays = "خلال
    " + "$daystoexpire" + " ايام"
        }     elseif (($messageDays) -eq "2")
        {         $messageDays = "خلال يومين
        }     else
        {         $messageDays = "اليوم."
        }     # Email Subject Set Here
        $subject="كلمة المرور الخاصة بك ستنتهي
    $messageDays"
           # Email Body Set Here, Note You can use HTML, including Images.
        $body =     "<P style='font-family: Arial; font-size: 16pt' />
        <center> الاستاذ/ $name
    </center> 
        <br>     <center>
    كلمة المرور الخاصة بك ستنتهي $messageDays </center>
        <br>     <center>
    نأمل تغييرها في أقرب فرصة حتي تتمكن من الدخول على النظام
    </center>
        <br>     <center>
    مع تحيات الادارة العامة لتقنية المعلومات
    </center> 
        <br>     </P>"
            # If Testing Is Enabled - Email Administrator
        if (($testing) -eq "Enabled")
        {         $emailaddress = $testRecipient
        } # End Testing     # If a user has no email address listed
        if (($emailaddress) -eq $null)
        {         $emailaddress = $testRecipient    
        }# End No Valid Email     # Send Email Message
        if (($daystoexpire -ge "0") -and ($daystoexpire -lt $expireindays))
        {          # If Logging is Enabled Log Details
            if (($logging) -eq "Enabled")
            {             Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$body" 
            }         # Send Email Message
            Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $encoding
                    } # End Send Message
      } # End User Processing
    # End

  • Remote managment Exchange 2013 SP1 from C# code using Power-Shell.

    Hello,
    Sorry if I am describing something wrong, but it is first time I am using Microsoft development forum.
    I am trying to built library that will manage Exchange remotely using  C# code (VS 2012) and Power-Shell ver.4.0. My workstation and the actual Exchange server physically placed in different domains. In order to test functionalities I am using
    user that is member of all administrating and management groups in the appropriative domain. Remote Power-Shell is enabled on Exchange.
    In order to connect to the Service I am using that part of code :
    internal static bool RedirectionUrlValidationCallback(string redirectionUrl)
    bool result = false;
    var redirectionUri = new Uri(redirectionUrl);
    if (redirectionUri.Scheme.Equals("https"))
    result = true;
    return result;
    internal static ExchangeService ConnectToService(ExchangeVersion version,
    string userName,
    string emailAddress,
    string password,
    string domainName,
    ref Uri autodiscoverUrl)
    ExchangeService service;
    try
    service = new ExchangeService(version);
    service.Credentials = new WebCredentials(userName, password, domainName);
    if (autodiscoverUrl.IsNull())
    var ads = new AutodiscoverService();
    // Enable tracing.
    ads.TraceEnabled = true;
    // Set the credentials.
    ads.Credentials = service.Credentials;
    // Prevent the AutodiscoverService from looking in the local Active Directory
    // for the Exchange Web Services Services SCP.
    ads.EnableScpLookup = false;
    // Specify a redirection URL validation
    //callback that returns true for valid URLs.
    ads.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
    // Get the Exchange Web Services URL for the user’s mailbox.
    var response = ads.GetUserSettings(emailAddress, UserSettingName.InternalEwsUrl);
    // Extract the Exchange Web Services URL from the response.
    autodiscoverUrl = new Uri(response.Settings[UserSettingName.InternalEwsUrl].ToString());
    // Update Service Url
    service.Url = autodiscoverUrl;
    else
    service.Url = autodiscoverUrl;
    catch (FormatException fe) // The user principal name(email) is in a bad format. UPN format is needed.
    LoggingFactory.LogException(fe);
    return null;
    catch (AutodiscoverLocalException ale)
    LoggingFactory.LogException(ale);
    return null;
    catch (Exception e)
    LoggingFactory.LogException(e);
    return null;
    return service;
    Then I am trying to reach existing mailbox of that user, using this part of code :
    try
    var runSpace = getRunspace();
    var pwShell = PowerShell.Create();
    pwShell.Runspace = runSpace;
    var command = new PSCommand();
    command.AddCommand("Get-Mailbox");
    command.AddParameter("Identity", userPrincipalName);
    command.AddParameter("RecipientTypeDetails", recipientType);
    pwShell.Commands = command;
    var result = pwShell.Invoke();
    if (result.IsNotNull() && result.Any())
    // TODO : fill appropriative DTO and return it.
    else
    // TODO : send back appropriative error.
    closeRunSpace(runSpace);
    catch (Exception e)
    // TODO : log the exception and send back appropriative error.
    private Runspace getRunspace()
    var runSpaceConfig = RunspaceConfiguration.Create();
    var runSpace = RunspaceFactory.CreateRunspace(runSpaceConfig);
    PSSnapInException snapEx;
    var psInfo = runSpaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapEx);
    runSpace.Open();
    return runSpace;
    private void closeRunSpace(Runspace runSpace)
    runSpace.Close();
    runSpace.Dispose();
    With this part I had problem. I received exception that appropriative Snap-in is not installed on my computer. I had no installation disk of Exchange in order to install Management Tool (as I understand this is the way to add needed part) so I changed run
    space activation to that part of code :
    private Runspace getRunspace()
    var newCredentials = (PSCredential)null;
    var connectionInfo = new WSManConnectionInfo(new Uri("http://exchange.domainname.local/powershell?serializationLevel=Full"),
    "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
    newCredentials);
    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
    var runSpace = RunspaceFactory.CreateRunspace(connectionInfo);
    runSpace.Open();
    return runSpace;
    Now I am receiving exception :
    "Connecting to remote server exchange.domainname.local failed with the following error message :
    [ClientAccessServer=exchange,BackEndServer=exchange.domainname.local,RequestId=....,TimeStamp=...]
    Access is denied. For more information, see the about_Remote_Troubleshooting Help topic."
    Please help me to understand what I am doing wrong.
    Thank you.
    Alexander.

    In Exchange 2010 you should be using Remote Powershell not local powershell and the snap-in.  Here is a sample that may help you:
    http://blogs.msdn.com/b/dvespa/archive/2009/10/22/how-to-call-exchange-2010-cmdlet-s-using-remote-powershell-in-code.aspx

  • Rename the current active file?

    I'm wanting a script to be able to rename open Photoshop files, if possible.
    I cobbled this together from an existing script:
    tell application "Adobe Photoshop CS5"
      activate
              set old_name to name of current document
              set dialog_result to display dialog ¬
                        "Rename active document:" default answer (old_name) ¬
                        buttons {"Cancel", "Rename"} default button 2 ¬
      with icon note
              if button returned of dialog_result = "Rename" then
                        set new_name to text returned of dialog_result
                        set d to properties of current document
                        if path of d is equal to missing value then
                                  set name of current document to new_name
                        else
                                  tell me to set the_file to POSIX file (d's path as text) as alias
                                  tell application "Finder"
                                            set name of the_file to new_name
                                  end tell
                        end if
              end if
    end tell
    If I run it it shows the dialogue window, but when I enter the new name and hit Return it throws out lots of errors.
    Is something like this possible?

    As Chris wrote Photoshop is not a File Editor. Photoshop edits Photoshop Documents the current Document may or may not have a file on the system created fron the active document.  If if does have a file assocatation I sure with scripting you can perform file operations on the file  like delete, rename, move etc.  However the will not change the active document name. Basicly document name is read only.... well sort of read only for if the current document does not have a file assocation and you save it into you file system The docoument becomes assocated with a file and Photoshop will change the active document name.  Aslo when you open a RAW file through ACR the inage image window or tab may show something like imagename.cr2 there is not actually a file associated with the document for Photoshop can not save a Camera RAW file so if you save it as PSD or TiFF the window or tab will now show the file assocation imagename.psd|tif  not .cr2. The document name does not always change with a save for if you save the PSD as a jpeg after the jpeg images is saved the document reverts back to its layered and color depth state  and is still imagename.psd.  There is no active document associated with that saved jpeg file. You can open it and have two document open that look the same one being layered a and perhaps 16bit and the other flat and 8bit.

  • Trying to run program off network location using GPO with Power shell script.

    Hello All,
    Not much of a script writer. I am giving it a shot.  My issue is that I need to run a application update across our network and I am trying to do it with as little hands on as possible. So I was planning to push a GPO with a power shell script in it
    to run the program with elevated privileges. 
    Little background:
    We are running on a domain and end users do not have admin rights.
    The application is stored on a share on our network that is open to all domain users.
    The installer user name and password is a temp one and will only be valid for the 30 min window when everyone logs in at the beginning of the day.
    So this is what I have so far.
    $username = "USER"
    $password = "PASSWORD"
    $credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
    Start-Process PSQLv11Patch_Client_x86.msp -Credential ($credentials) -WorkingDirectory \\Server\Folder\Folder1\Folder2\filder3\PSQLv11sp3_x32\
    But for some reason I keep getting :
    Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
    At line:10 char:1
    + Start-Process PSQLv11Patch_Client_x86.msp -Credential ($credentials) -WorkingDir ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
        + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
    Any help you could give would be great.
    Thanks,
    jdfmonkey

    Hi jdfmonkey,
    Has anyone provided an answer to your original question?  I am trying to use Start-Process to launch a process using another logged in user's credentials, and am not able to get it working:
    $cred=Get-Credential
    start-process Process.exe-WorkingDirectoryC:\Scripts-Credential$cred
    I get the same error that you mentioned:
    start-process : This command cannot be run due to the error: The system cannot find the file specified.
    At C:\Scripts\Process.ps1:2 char:1
    + start-process Process.exe -WorkingDirectory C:\Scripts -Credential ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
        + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
    When I leave off the credentials:
    start-processProcess.exe-WorkingDirectoryC:\Scripts
    It works correctly.  Does anyone have a solution to make this work correctly?
    Please ask your own question.  You issue is nothing like the current thread.  You clearly are using a user account that has no access to the folder.  It is a permissions issue.  It is not a scripting issue.
    If you need further help please start your own question.
    ¯\_(ツ)_/¯

Maybe you are looking for

  • Can not send email from this house

    I cannot send an email from any computer, laptop or phone (connected via wifi) from this house. However, if I take the laptop or phone to another place I can send with no problem. Oh, I can receive just fine. Here's the problem. I am not using Verizo

  • How to echo the SQL command in JDBC?

    When we use a PreparedStatement and execute query, is there a way to get the exact SQL command sent to the server without any '?' marks? That would be an aid in debugging. Or is such a facility server-pecific? I am using MySQL with JDBC. Thank you.

  • How to deploy a war file into websphere appserver? error !!!

    Hello expert, I build one very simple war file, simpletest.war, using build tool 'ant', I did not have any tools available at this moment: D:\Projects\E-form\simpletest\build>jar.exe -tvf simpletest.war 0 Fri Nov 11 12:06:52 CST 2005 META-INF/ 106 Fr

  • Select-options Problem in module pool

    Hi,      I have created select-options in a seperate program and i have called the subscreen in module pool program. I dont have any problem with the display of select-options but whatever the value given is not getting in to the program. Hw to solve

  • Delivery Note/Pack List

    Can somebody post, or send me, the print program for the SmartForm Delivery note/Pack List (output type LD00)? Regards, Davis