Powershell Loop

Guys,
I would like to create a script which does the following.
Search a file in d:\folder\test\
If it finds it, send-email and finish.
If it doesn't find the file, retry again every 10 minutes for an hour or retry for a fixed number of times before finishing.
I understand how to do the initial stuff ( search file send email etc), but i require some help with setting up the loop to keep retrying until it is successful or finishes.
Thanks in advance

Hi,
Here's an example you can build from:
$count = 0
Do {
Write-Host "Counter is $count"
$count++
Start-Sleep -Seconds 5
} Until ($count -eq 5)
EDIT: Slow on the submit button, see clayman2's post above.
Don't retire TechNet! -
(Don't give up yet - 12,950+ strong and growing)
Also, please keep in mind that with my example, if the file never exists, you will run the loop indefinitely, so you may also want to look at Mike's example, where he uses the Until rather than the While, and has a counter, that is incremented each run, and
if that counter reachers a specific number, the loop will stop. My Do While loop will only stop when that file actually exists.
If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.
Don't Retire Technet

Similar Messages

  • Powershell loop? newbie in powershell logic.

    Hi All.
    I have a challenge regarding a script.
    I want to chech if a file exists on a remote virtual server(this works).
    if the file exists i want to close down the vm(this works) and remove a legagy adapter from the virtual machine.
    so what i need is the logic, to determine if the file is on the VM, if not the powershell script should sleep for 5 minutes, and then try again, and again until the file is there(this is part of a deployment scenario).
    Hope someone can help me.

    does not Work for me.
    $fileToCheck="\\dl420\c$\finished.txt"
    $fileFound
    =$false
    Do
    If(Test-Path-Path$fileToCheck)
    {$fileFound=$test}
    Else{
    Start-Sleep-Seconds30}
    write-hoststillsleeping
    Until
    ($fileFound)
     is did not Work for me, the script keeps looping even though my file is there?
    please help me.

  • How can we show a custom column to all libraries in the default view without creating that for all libraries everytime

    Hi,
    Any help?
    Thanks
    srabon

    You can use powershell script below which loops through each libraries and sets view.You can modify the script to user it for single library as well.
    Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
    $siteURL = "<YOURSITEURL>"
    $site = Get-SPSite($siteURL)
    foreach($web in $site.AllWebs) {
    foreach($list in $web.Lists) {
    if($list.BaseType -eq "DocumentLibrary") {
    // the variables `$web` and `$list` already reference the objects you need
    //$site = New-Object Microsoft.SharePoint.SPSite($SiteURL) ;
    //$web = $site.OpenWeb($SiteURL);
    // new instance of the list is necessary to avoid the error "Collection was modified"
    $newList = $web.Lists.item($list.ID);
    $viewfields = New-Object System.Collections.Specialized.StringCollection
    $viewfields.Add("DocIcon")
    $viewfields.Add("LinkFilename")
    $viewfields.Add("_UIVersionString")
    $viewfields.Add("FileSizeDisplay")
    $viewfields.Add("Created")
    $viewfields.Add("Modified")
    $viewfields.Add("Editor")
    [void]$newList.Views.Add(<VIEWNAME>, $viewfields, "", 100, $true, $true)
    $newList.Update();
    // setting the default view
    $view=$newList.Views["<VIEWNAME>"]
    $view.DefaultView = $true
    $view.Update()
    $web.Dispose();
    $site.Dispose();
    Ref: http://stackoverflow.com/questions/10015311/part2-sharepoint-2010-powershell-loop-through-all-document-libraries-creat
    Hope that helps!
    Avni Bhatt

  • Command to call Multiple Databases

    I have command that runs that removes admin rights for users in a database then I run another script that adds admin rights afterwards.
    The script to remove admin rights is:
    Get-Mailbox -ResultSize Unlimited -Database "MailboxDatabase4" | Remove-MailboxPermission -user "admin" -AccessRights FullAccess -InheritanceType All
    The script to add admin rights is:
    Get-Mailbox -ResultSize Unlimited -Database "MailboxDatabase4" | Add-MailboxPermission -user "admin" -AccessRights FullAccess -InheritanceType All
    I Have 6 databases, therefore I have to run the scripts 12 times each day. is there any way of calling all the databases in one script so that I only have to run one script for all the databases to remove admin rights, then another script to add admin rights.
    therefore not having to do it for each individual database.

    Hi Tobias,
    To run script on bulk objects, please refer to the script below to start:
    $database="MailboxDatabase1","MailboxDatabase2","MailboxDatabase3","MailboxDatabase4"
    Foreach($data in $database){
    Get-Mailbox -ResultSize Unlimited -Database $data | Remove-MailboxPermission -user "admin" -AccessRights FullAccess -InheritanceType All
    To use loop in powershell, please refer to this article:
    Basics of PowerShell Looping: Foreach
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • PowerShell 3.0 stuck in infinite loop resolving members internally (is this a PS bug??)

    Sorry for long post... I have this scenario:
    - Issue is on PS3, PS2 works fine
    - I create a new object via "$myObj = New-Object PSObject"
    - I append a number of PSMembers to it via something similar to:
    "if (-not (Get-Member -InputObject $myObj -Name MyProperty))
     Add-Member -InputObject $myObj -MemberType ScriptProperty -Name MyProperty -Value { return MyFunction }
    I am seeing situations where what I believe is the call to "Get-Member" causes a huge number of invocations that appear to be calling the equivalent of the "MyFunction" in the above sample. I have debug statements in the MyFunction
    function and nested functions and can see they are called by what appears to be the PS framework itself. Even running a "Get-PSCallstack" call from one of these functions seems to also trigger the debug statements to be hit (midway through the callstack
    output??!) - bit confused by that but it's like PS is invoking the member in order to reflect it or something.
    I used Trace-Command and could see that the "MemberResolution" trace source is repeatedly/infinitely called with the output:
    MemberResolution Information: 0 :         Matching "*"
    MemberResolution Information: 0 :             Generating the total list of members
    MemberResolution Information: 0 :                 Type table members: 0.
    MemberResolution Information: 0 :                 Adapted members: 0.
    MemberResolution Information: 0 :             21 total matches.
    This appears to be in an infinite loop. Therefore I added "-ListenerOption Callstack" to the Trace-Command call and captured the following and more (notice the call to PSObject.ToStringEmptyBaseObject()):
    at System.Management.Automation.PSObject.AdapterGetMembersDelegate[T](PSObject msjObj)
       at System.Management.Automation.PSMemberInfoIntegratingCollection`1.GetIntegratedMembers(MshMemberMatchOptions matchOptions)
       at System.Management.Automation.PSMemberInfoIntegratingCollection`1.Match(String name, PSMemberTypes memberTypes, MshMemberMatchOptions matchOptions)
       at System.Management.Automation.PSObject.ToStringEmptyBaseObject(ExecutionContext context, PSObject mshObj, String separator, String format, IFormatProvider formatProvider)
       at System.Management.Automation.PSObject.ToString(ExecutionContext context, Object obj, String separator, String format, IFormatProvider formatProvider, Boolean recurse, Boolean unravelEnumeratorOnRecurse)
       at System.Management.Automation.PSObject.ToString()
       at System.String.Join(String separator, Object[] values)
       at System.Management.Automation.ParameterBinderBase.BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
    I then disassembled the relevant code in Reflector and could see that the ToString() method of PSObject has a check for "if obj.immediateBaseObjectIsEmpty" then to call the ToStringEmptyBaseObject() function. I could also see that the immediateBaseObjectIsEmpty
    field is set in the CommonInitialization internal method if "obj is PSCustomObject" (which is the actual object type you get when you New-Object PSObject).
    I then updated my code to create "$myObj = New-Object Object" (i.e. System.Object instead) and the issue goes away.
    Can anyone explain what I may have done wrong here or is this looking like a bug in PowerShell?
    Cheers!

    Hi Matt,
    I'm not sure if we are on the same page? Getting the list of (i.e. metadata of) the members shouldn't invoke the member.  I have used this technique in many places and it's never been an issue whereby you "wrap" a utility function with
    a ScriptProperty or ScriptMethod to provide OO semantics on a PS object. The member isn't invoked by Get-Member, only when it's called explicitly.
    Here's a small example:
    function TestFunction
     Write-Host "TestFunction called"
     return "TestFunction return value"
    $myObj = New-Object PSObject
    Add-Member -InputObject $myObj -MemberType ScriptProperty -Name TestScriptProperty -Value `
     Write-Host "TestScriptProperty called"
     return TestFunction
    Write-Host "Getting members"
    Get-Member -InputObject $myObj -Name TestScriptProperty | Select *
    Write-Host "Invoking property"
    $myObj.TestScriptProperty
    Here's the output (Get-Member output a bit mangled due to the text wrapping):
    Getting members
    TypeName                                   Name                                                                      
    MemberType Definition                               
    System.Management.Automation.PSCustomOb... TestScriptProperty                                                    
    ScriptProperty System.Object TestScriptProperty {get=...
    Invoking property
    TestScriptProperty called
    TestFunction called
    TestFunction return value
    Yup I see your point, but when you run your original code with this example object you can see there is no loop. There must either be a loop in the function or in the body of the script itself. This is very tough to troubleshoot without seeing the code you
    are actually running.
    You said you are adding several members to the custom object. Is this done in a loop?

  • Powershell - Daily disk and folder usage; trouble with code to loop through the individual folders

    Hi,
    I'm very new to Powershell but through the help of this forum and the help on the internet I have scraped together a script that will loop through the disks of a set of servers listed in a text document, and give the capacity statistics in html
    format.
    I have two questions. I've tried modifying this to also loop though the individual folders on each disk and give the amount of space used to no avail. does any one have any suggestions?
    Secondly, how do I get this to append? all I want to do is set up a scheduled task that runs this report daily. I know I will need to add a date column, but I just want the data to append to the previous set of results.
    Thanks for any advice in advance.
    # Continue even if there are errors
    $ErrorActionPreference = "Continue";
    # Set your warning and critical thresholds
    $percentWarning = 100;
    $percentCritcal = 15;
    # REPORT PROPERTIES
    # Path to the report
    $reportPath = "C:\";
    # Report name
    $reportName = "DiskSpaceReport_$(get-date -format ddMMyyyy).html";
    # Path and Report name together
    $diskReport = $reportPath + $reportName
    #Set colors for table cell backgrounds
    $redColor = "#FF0000"
    $orangeColor = "#FBB917"
    $whiteColor = "#FFFFFF"
    # Count if any computers have low disk space. Do not send report if less than 1.
    $i = 0;
    # Get computer list to check disk space
    $computers = Get-Content "C:\serverlist.txt";
    $datetime = Get-Date -Format "dd-MM-yyyy_HHmmss";
    # Create and write HTML Header of report
    $titleDate = get-date -uformat "%d-%m-%Y - %A"
    $header = "
    <html>
    <head>
    <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
    <title>DiskSpace Report</title>
    <STYLE TYPE='text/css'>
    <!--
    td {
    font-family: Calibri;
    font-size: 12px;
    border-top: 1px solid #999999;
    border-right: 1px solid #999999;
    border-bottom: 1px solid #999999;
    border-left: 1px solid #999999;
    padding-top: 0px;
    padding-right: 0px;
    padding-bottom: 0px;
    padding-left: 0px;
    body {
    margin-left: 5px;
    margin-top: 5px;
    margin-right: 0px;
    margin-bottom: 10px;
    table {
    border: thin solid #000000;
    -->
    </style>
    </head>
    <body>
    <table width='100%'>
    <tr bgcolor='#0B6121'>
    <td colspan='7' height='30' align='center'>
    <font face='calibri' color='#E0F8F7' size='4'><strong>Daily Disk Utilization Report for $titledate</strong></font>
    </td>
    </tr>
    </table>
    Add-Content $diskReport $header
    # Create and write Table header for report
    $tableHeader = "
    <table width='100%'><tbody>
    <tr bgcolor=#E0F8F7>
    <td width='10%' align='center'>Server</td>
    <td width='5%' align='center'>Drive</td>
    <td width='15%' align='center'>Drive Label</td>
    <td width='10%' align='center'>Total Capacity(GB)</td>
    <td width='10%' align='center'>Used Capacity(GB)</td>
    <td width='10%' align='center'>Free Space(GB)</td>
    <td width='5%' align='center'>Freespace %</td>
    <td width='5%' align='center'>RAM %</td>
    <td width='5%' align='center'>CPU %</td>
    </tr>
    Add-Content $diskReport $tableHeader
    # Start processing disk space
    foreach($computer in $computers)
    $disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk -Filter #"DriveType = 3"
    $computer = $computer.toupper()
    foreach($disk in $disks)
    $deviceID = $disk.DeviceID;
    $volName = $disk.VolumeName;
    [float]$size = $disk.Size;
    [float]$freespace = $disk.FreeSpace;
    $percentFree = [Math]::Round(($freespace / $size) * 100);
    $sizeGB = [Math]::Round($size / 1073741824, 2);
    $freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);
    $usedSpaceGB = $sizeGB - $freeSpaceGB;
    $color = $whiteColor;
    # Start processing RAM
    $RAM = Get-WmiObject -ComputerName $computer -Class Win32_OperatingSystem
    $RAMtotal = $RAM.TotalVisibleMemorySize;
    $RAMAvail = $RAM.FreePhysicalMemory;
    $RAMpercent = [Math]::Round(($RAMavail / $RAMTotal) * 100);
    # Set background color to Orange if just a warning
    if($percentFree -lt $percentWarning)
    $color = $orangeColor
    # Set background color to Orange if space is Critical
    if($percentFree -lt $percentCritcal)
    $color = $redColor
    # Create table data rows
    $dataRow = "
    <tr>
    <td width='10%'>$computer</td>
    <td width='5%' align='center'>$deviceID</td>
    <td width='10%' >$volName</td>
    <td width='10%' align='center'>$sizeGB</td>
    <td width='10%' align='center'>$usedSpaceGB</td>
    <td width='10%' align='center'>$freeSpaceGB</td>
    <td width='5%' bgcolor=`'$color`' align='center'>$percentFree</td>
    <td width='5%' align='center'>$RAMpercent</td>
    <td width='5%' align='center'>$CPUpercent</td>
    </tr>
    Add-Content $diskReport $dataRow;
    Write-Host -ForegroundColor DarkYellow "$computer $deviceID percentage free space = $percentFree";
    $i++
    # Create table at end of report showing legend of colors for the critical and warning
    $tableDescription = "
    </table><br><table width='20%'>
    <tr bgcolor='White'>
    <td width='10%' align='center' bgcolor='#FBB917'>No Warning</td>
    <td width='10%' align='center' bgcolor='#FF0000'>Critical less than 10% free space</td>
    </tr>
    Add-Content $diskReport $tableDescription
    Add-Content $diskReport "</body></html>"

    The only easy way to create a report like this that accumulates is to design it so the data is output to a CSV file or a database.  YOu can then generate the HTML from the persist6ed data.
    If you store as XML you can use XSLT (transform) to convert to an HTML report.
    I also recommend uing Excel as an HTML report generator.  It is much easier and more flexible.  PowerShell is not intended to do what you want without designing a whole custom reporting system.
    Use the right tool for the right task.
    Just because you own a hammer does not mean that the solution to every problem includes a nail.
    ¯\_(ツ)_/¯

  • Powershell schedule task and infnity loop

    Hello guys,
    Plase help me resolve why my infinity loop "While ($true)" stops after couple days of work. Task scheduler shows envent - Task scheduler sucessfully end up job "\audit" ,instance "{d6156b36-0168-4b0c-8ac7-9d45aa0941dd}" , C:\Windows\System32\WindowsPowerShell\v1.0\powershell.EXE"
    with return code 1.

    $adid = 5136..5139 + 5141
    $userid = 4722..4726 + 4780..4781 + 5376..5377 + 4720 + 4738 + 4740 + 4767 + 4794
    $cpuid = 4741..4743
    $secgrpid = (4727..4735) + 4737 + (4754..4758) + 4764
    $distgrpid = (4744..4753) + (4759..4763)
    $ids = $userid + $cpuid + $secgrpid + $distgrpid
    if (Test-Path C:\LastRecordID.txt)
    $idx = Get-Content C:\LastRecordID.txt
    else
    $idx  = (Get-WinEvent -LogName Security -max 1).RecordID
    while ($true)
            start-sleep -Seconds 1
            $idx2  = (Get-WinEvent -LogName Security -max 1).RecordId
            if ($idx2 -gt $idx) 
                $events = Get-WinEvent -LogName Security -MaxEvents ($idx2 - $idx) | sort recordid | where {$userid + $cpuid + $secgrpid + $distgrpid -contains $_.id}
                foreach ($event in $events)
                Send-MailMessage -Encoding UTF8 -SmtpServer ex1.domain.local -From [email protected] -To [email protected]  `
                -Subject "Аудит" -Body "Время создания:   $($event.TimeCreated)   Сервер: $Env:COMPUTERNAME `nНомер события:   $($event.RecordID) `nEventID:   $($event.ID) `nСообщение:
      $($event.Message)"
            $idx = $idx2
            $idx | Out-File C:\LastRecordID.txt

  • Missing statement body foreach loop in powershell

    I am working on powershell script mentioned below
    $filename= $arg[0]
    $includePath = "$(Split-Path -Path $MyInvocation.MyCommand.Path -Parent | Split-Path -Parent)\include" .
     $includePath\utils.ps1; 
    $AmisysConnectionStringName;
     Run-Job -JobName 'ucmu073'
     { $files = @{ ICD10 = @{$Edit_Function = $params[1], $Table_Function = $params[2], $Code_Function = $params[3]}
     foreach($file in dir $UCMCSVLoadLocation2 -Recurse -Include @("*.csv")) #$files.GetEnumerator()) #$filename = $file_desc.Key $params[1] $params[2] $params[3]}
     #$filePath = "C:\jobs\AA\DEV6\UCM\${filename}.csv" $importFile = Import-CSV $filePath foreach($item in $importFile) 
    { $proc1 = $item.DIAG_NBR 
    $proc2 = $item.DIAG_NBR # $ymdeff = $item.YMDEFF #$ymdend = $item.YMDEND #$ymdtrans = $item.YMDTRANS
     Write-Verbose "$proc1, $proc2" $currentDate = Get-Date -Format yyyyMMdd # 
    # * Insert codes and fees into the su_edit_detail.
    '{0,-60}{1,20}' -f "Insert TEEN PREGNANCY ICD9 AND ICD10 CODES into the su_edit_detail ",(Get-Date -Format yyyyMMdd:hhmmss); $myQuery = @" SET PAGES 600; SET LINES 4000; SET ECHO ON; SET serveroutput on; WHENEVER sqlerror exit sql.sqlcode; insert
    into SU_EDIT_DETAIL(EDIT_FUNCTION, TABLE_FUNCTION, CODE_FUNCTION, CODE_TYPE,CODE_BEGIN, CODE_END, EXCLUDE, INCLUDE_X, OP_NBR, TRANSCODE, VOID, YMDEFF, YMDEND, YMDTRANS) select '$edit_func','$table_func','$code_func','DIAG','$proc1','$proc2',' ',' ','MIS',
    'C',' ',20141001, 99991231, 20131120 from dual where not exists(select * from SU_EDIT_DETAIL where (EDIT_FUNCTION = '$edit_func' and TABLE_FUNCTION = '$table_func' and CODE_BEGIN='$proc1' and CODE_END='$proc2')); commit; "@ 
    $null = Invoke-SqlPlus -MessageOnFail 'Insert into su_edit_detail failed' -Query $myQuery; } } } 
    In this script I am passing variable on line # 6 and prioor to this I hard code following code but decide to use variable or PARAMETER in case I need to do changes
     I have csv file is located in C Drive which is mentioned in folowing code:
     foreach($file in dir $UCMCSVLoadLocation2 -Recurse -Include @("*.csv")) 
    Once I execute this powershell Insert statement get executed and dump all the data in table mentioned in code reside as follow:
     '{0,-60}{1,20}' -f "Insert TEEN PREGNANCY ICD9 AND ICD10 CODES into the su_edit_detail ",(Get-Date -Format yyyyMMdd:hhmmss); 
    $myQuery = @" SET PAGES 600; SET LINES 4000; SET ECHO ON; SET serveroutput on; WHENEVER sqlerror exit sql.sqlcode; 
    insert into SU_EDIT_DETAIL(EDIT_FUNCTION, TABLE_FUNCTION, CODE_FUNCTION, CODE_TYPE,CODE_BEGIN, CODE_END, EXCLUDE, INCLUDE_X, OP_NBR, TRANSCODE, VOID, YMDEFF, YMDEND, YMDTRANS) 
    select '$edit_func','$table_func','$code_func','DIAG','$proc1','$proc2',' ',' ','MIS', 'C',' ',20141001, 99991231, 20131120 from dual where not exists(select * from SU_EDIT_DETAIL where (EDIT_FUNCTION = '$edit_func' and TABLE_FUNCTION = '$table_func' and CODE_BEGIN='$proc1'
    and CODE_END='$proc2')); commit; 
    $null = Invoke-SqlPlus -MessageOnFail 'Insert into su_edit_detail
    Snapshot you are looking at failed at : "$params[1]"
    I am working on powershell script mentioned below $filename= $arg[0] $includePath = "$(Split-Path -Path $MyInvocation.MyCommand.Path -Parent | Split-Path -Parent)\include" . $includePath\utils.ps1; $AmisysConnectionStringName; Run-Job -JobName
    'ucmu073' { $files = @{ ICD10 = @{$Edit_Function = $params[1], $Table_Function = $params[2], $Code_Function = $params[3]}} } foreach($file in dir $UCMCSVLoadLocation2 -Recurse -Include @("*.csv")) #$files.GetEnumerator()) #$filename = $file_desc.Key
    $params[1] $params[2] $params[3] #$filePath = "C:\jobs\AA\DEV6\UCM\${filename}.csv" $importFile = Import-CSV $filePath foreach($item in $importFile) { $proc1 = $item.DIAG_NBR $proc2 = $item.DIAG_NBR # $ymdeff = $item.YMDEFF #$ymdend = $item.YMDEND
    #$ymdtrans = $item.YMDTRANS Write-Verbose "$proc1, $proc2" $currentDate = Get-Date -Format yyyyMMdd # ******************************************************************************* # * Insert codes and fees into the su_edit_detail. # *******************************************************************************
    '{0,-60}{1,20}' -f "Insert TEEN PREGNANCY ICD9 AND ICD10 CODES into the su_edit_detail ",(Get-Date -Format yyyyMMdd:hhmmss); $myQuery = @" SET PAGES 600; SET LINES 4000; SET ECHO ON; SET serveroutput on; WHENEVER sqlerror exit sql.sqlcode; insert
    into SU_EDIT_DETAIL(EDIT_FUNCTION, TABLE_FUNCTION, CODE_FUNCTION, CODE_TYPE,CODE_BEGIN, CODE_END, EXCLUDE, INCLUDE_X, OP_NBR, TRANSCODE, VOID, YMDEFF, YMDEND, YMDTRANS) select '$edit_func','$table_func','$code_func','DIAG','$proc1','$proc2',' ',' ','MIS',
    'C',' ',20141001, 99991231, 20131120 from dual where not exists(select * from SU_EDIT_DETAIL where (EDIT_FUNCTION = '$edit_func' and TABLE_FUNCTION = '$table_func' and CODE_BEGIN='$proc1' and CODE_END='$proc2')); commit; "@ $null = Invoke-SqlPlus -MessageOnFail
    'Insert into su_edit_detail failed' -Query $myQuery; } } } In this script I am passing variable on line # 6 and prioor to this I hard code following code but decide to use variable or PARAMETER in case I need to do changes I have csv file is located in C Drive
    which is mentioned in folowing code: foreach($file in dir $UCMCSVLoadLocation2 -Recurse -Include @("*.csv")) Once I execute this powershell Insert statement get executed and dump all the data in table mentioned in code reside as follow: '{0,-60}{1,20}'
    -f "Insert TEEN PREGNANCY ICD9 AND ICD10 CODES into the su_edit_detail ",(Get-Date -Format yyyyMMdd:hhmmss); $myQuery = @" SET PAGES 600; SET LINES 4000; SET ECHO ON; SET serveroutput on; WHENEVER sqlerror exit sql.sqlcode; insert into SU_EDIT_DETAIL(EDIT_FUNCTION,
    TABLE_FUNCTION, CODE_FUNCTION, CODE_TYPE,CODE_BEGIN, CODE_END, EXCLUDE, INCLUDE_X, OP_NBR, TRANSCODE, VOID, YMDEFF, YMDEND, YMDTRANS) select '$edit_func','$table_func','$code_func','DIAG','$proc1','$proc2',' ',' ','MIS', 'C',' ',20141001, 99991231, 20131120
    from dual where not exists(select * from SU_EDIT_DETAIL where (EDIT_FUNCTION = '$edit_func' and TABLE_FUNCTION = '$table_func' and CODE_BEGIN='$proc1' and CODE_END='$proc2')); commit; "@ $null = Invoke-SqlPlus -MessageOnFail 'Insert into su_edit_detail
    Snapshot you are looking at failed at : "$params[1]"
    failed' -Query $myQuery; ANY GREAT IDEA>>>>>>>>>>>>>>
    Vijay Patel
    I am new to this and try to  make difference
    I am getting error because I am not setting variable properly  can somebody help me with this.
    Thank you very much
    $filename= $args[0]
    $includePath = "$(Split-Path -Path $MyInvocation.MyCommand.Path -Parent | Split-Path -Parent)\include"
    . $includePath\utils.ps1;
    $AmisysConnectionStringName;
    Run-Job -JobName 'ucmu073' {
    foreach($file in dir $CodesetBulkLoadLocation -Recurse -Include @("*.csv"))
    #$files = @{
    #'ICD10' = @{ 'EDIT_FUNCTION'='UCM-REPT-TEEN-PREG-DIAG'; 'TABLE_FUNCTION'='UCM-REPT'; 'CODE_FUNCTION' = 'I0' }
    #foreach($file_desc in $files.GetEnumerator())
    $filename = $file_desc.Key
    $edit_func = $file_desc.Value.EDIT_FUNCTION
    $table_func = $file_desc.Value.TABLE_FUNCTION
    $code_func = $file_desc.Value.CODE_FUNCTION
    $filePath = "C:\jobs\AA\DEV6\UCM\${filename}.csv"
    $importFile = Import-CSV $filePath
    foreach($item in $importFile)
    $proc1 = $item.DIAG_NBR
    $proc2 = $item.DIAG_NBR
    # $ymdeff = $item.YMDEFF
    #$ymdend = $item.YMDEND
    #$ymdtrans = $item.YMDTRANS
    Write-Verbose "$proc1, $proc2"
    $currentDate = Get-Date -Format yyyyMMdd
    # * Insert codes and fees into the su_edit_detail.
    '{0,-60}{1,20}' -f "Insert TEEN PREGNANCY ICD9 AND ICD10 CODES into the su_edit_detail ",(Get-Date -Format yyyyMMdd:hhmmss);
    $myQuery = @"
    SET PAGES 600;
    SET LINES 4000;
    SET ECHO ON;
    SET serveroutput on;
    WHENEVER sqlerror exit sql.sqlcode;
    insert into SU_EDIT_DETAIL(EDIT_FUNCTION, TABLE_FUNCTION, CODE_FUNCTION, CODE_TYPE,CODE_BEGIN, CODE_END, EXCLUDE, INCLUDE_X, OP_NBR, TRANSCODE, VOID, YMDEFF, YMDEND, YMDTRANS)
    select '$edit_func','$table_func','$code_func','DIAG','$proc1','$proc2',' ',' ','MIS', 'C',' ',20141001, 99991231, 20131120
    from dual where not exists(select * from SU_EDIT_DETAIL where (EDIT_FUNCTION = '$edit_func' and TABLE_FUNCTION = '$table_func' and CODE_BEGIN='$proc1' and CODE_END='$proc2'));
    commit;
    $null = Invoke-SqlPlus -MessageOnFail 'Insert into su_edit_detail failed' -Query $myQuery;

    Here is what it appears you are trying to do but, unfortunately, PowerShell does not work like this.
    $currentDate = Get-Date -Format yyyyMMdd
    function BuildQuery{
    SET PAGES 600;
    SET LINES 4000;
    SET ECHO ON;
    SET serveroutput on;
    WHENEVER sqlerror exit sql.sqlcode;
    '{0,-60}{1,20}' -f "Insert TEEN PREGNANCY ICD9 AND ICD10 CODES into the su_edit_detail ",(Get-Date -Format yyyyMMdd:hhmmss);
    insert into SU_EDIT_DETAIL(EDIT_FUNCTION, TABLE_FUNCTION, CODE_FUNCTION, CODE_TYPE,CODE_BEGIN, CODE_END, EXCLUDE, INCLUDE_X, OP_NBR, TRANSCODE, VOID, YMDEFF, YMDEND, YMDTRANS)
    select '$edit_func','$table_func','$code_func','DIAG','$proc1','$proc2',' ',' ','MIS', 'C',' ',20141001, 99991231, 20131120
    from dual where not exists(select * from SU_EDIT_DETAIL where (EDIT_FUNCTION = '$edit_func' and TABLE_FUNCTION = '$table_func' and CODE_BEGIN='$proc1' and CODE_END='$proc2'));
    commit;
    $filename= $args[0]
    $includePath = "$(Split-Path -Path $MyInvocation.MyCommand.Path -Parent | Split-Path -Parent)\include"
    . $includePath\utils.ps1;
    $AmisysConnectionStringName;
    Run-Job -JobName 'ucmu073' {
    foreach($file in (dir $CodesetBulkLoadLocation -Recurse -Include *.csv){
    $filename = $file_desc.Key
    $edit_func = $file_desc.Value.EDIT_FUNCTION
    $table_func = $file_desc.Value.TABLE_FUNCTION
    $code_func = $file_desc.Value.CODE_FUNCTION
    $filePath = "C:\jobs\AA\DEV6\UCM\${filename}.csv"
    $importFile = Import-CSV $filePath
    foreach($item in $importFile){
    $proc1 = $item.DIAG_NBR
    $proc2 = $item.DIAG_NBR
    Write-Verbose "$proc1, $proc2"
    Invoke-SqlPlus -MessageOnFail 'Insert into su_edit_detail failed' -Query BuildQuery
    ¯\_(ツ)_/¯

  • Trouble looping thru SR to mark as completed with powershell

    Not sure this is actually a SCSM question, but I only seem to have trouble doing this in SCSM PowerShell.
    PS D:\ps1\Management Scripts> gc D:\ps1\SRs2Close_6.23.2014.txt
    SR6172
    SR6411
    SR6159
    SR6284
    SR6280
    SR6298
    SR6226
    SR6262
    SR6307
    SR6223
    SR6264
    SR6285
    SR6334
    SR6255
    SR6251
    SR6247
    SR6238
    SR6234
    SR6231
    SR6200
    SR6165
    $SRs = gc D:\ps1\SRs2Close_6.23.2014.txt
    Errors:
    ERRORS:
    PS D:\ps1\Management Scripts> $SRs | foreach-object {"D:\PS1\Management Scripts\Set-SRStatus.ps1" $_ "Completed"}
    Unexpected token '_' in expression or statement.
    At line:1 char:71
    + $SRs | foreach-object {"D:\PS1\Management Scripts\Set-SRStatus.ps1" $_ <<<< "Completed"}
    + CategoryInfo : ParserError: (_:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
    PS D:\ps1\Management Scripts> $SRs | foreach-object {"D:\PS1\Management Scripts\Set-SRStatus.ps1" $_.name.tostring() "Completed"}
    Unexpected token '_' in expression or statement.
    At line:1 char:71
    + $SRs | foreach-object {"D:\PS1\Management Scripts\Set-SRStatus.ps1" $_ <<<< .name.tostring() "Completed"}
    + CategoryInfo : ParserError: (_:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
    PS D:\ps1\Management Scripts> foreach ($SR in $SRs) {"D:\PS1\Management Scripts\Set-SRStatus.ps1" $SR.tostring() "Completed"}
    Unexpected token 'SR' in expression or statement.
    At line:1 char:72
    + foreach ($SR in $SRs) {"D:\PS1\Management Scripts\Set-SRStatus.ps1" $SR <<<< .tostring() "Completed"}
    + CategoryInfo : ParserError: (SR:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
    Script:
    param([string]$SRID,[string]$Status)
    $a = (get-module|%{$_.name}) -join " "
    if(!$a.Contains("SMLets")){Import-Module 'smlets' -ErrorVariable err -Force}
    $SRobj = Get-SCSMObject -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "ID -eq $SRID"
    Set-SCSMObject -SMObject $SRobj -Property Status -Value $Status
    PS D:\ps1\Management Scripts> Get-SCSMObject -Class $SRClass -Filter "ID -eq SR6172" | select status
    Status
    In Progress
    PS D:\ps1\Management Scripts> $SRobj = Get-SCSMObject -Class $SRClass -Filter "ID -eq SR6172"
    PS D:\ps1\Management Scripts> Set-SCSMObject -SMObject $SRobj -Property status -Value Completed
    PS D:\ps1\Management Scripts> Get-SCSMObject -Class $SRClass -Filter "ID -eq SR6172" | select status
    Status
    Completed
    PS D:\ps1\Management Scripts> $SRs = gc D:\ps1\SRs2Close_6.23.2014.txt
    PS D:\ps1\Management Scripts> $SRs | ForEach-Object {& 'D:\ps1\Management Scripts\Set-SRStatus.ps1' "$_" "Completed"}
    Get-SCSMObject : Id='SR6411' -- Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
    At D:\ps1\Management Scripts\Set-SRStatus.ps1:6 char:24
    + $SRobj = Get-SCSMObject <<<< -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "ID -eq $SRID"
    + CategoryInfo : NotSpecified: (:) [Get-SCSMObject], UnknownDatabaseException
    + FullyQualifiedErrorId : Microsoft.EnterpriseManagement.Common.UnknownDatabaseException,SMLets.GetSMObjectCommand
    Get-SCSMObject : Id='SR6159' -- Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
    At D:\ps1\Management Scripts\Set-SRStatus.ps1:6 char:24
    + $SRobj = Get-SCSMObject <<<< -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "ID -eq $SRID"
    + CategoryInfo : NotSpecified: (:) [Get-SCSMObject], UnknownDatabaseException
    + FullyQualifiedErrorId : Microsoft.EnterpriseManagement.Common.UnknownDatabaseException,SMLets.GetSMObjectCommand
    Get-SCSMObject : Id='SR6284' -- Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
    At D:\ps1\Management Scripts\Set-SRStatus.ps1:6 char:24
    + $SRobj = Get-SCSMObject <<<< -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "ID -eq $SRID"
    + CategoryInfo : NotSpecified: (:) [Get-SCSMObject], UnknownDatabaseException
    + FullyQualifiedErrorId : Microsoft.EnterpriseManagement.Common.UnknownDatabaseException,SMLets.GetSMObjectCommand
    Get-SCSMObject : Id='SR6280' -- Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
    At D:\ps1\Management Scripts\Set-SRStatus.ps1:6 char:24
    + $SRobj = Get-SCSMObject <<<< -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "ID -eq $SRID"
    + CategoryInfo : NotSpecified: (:) [Get-SCSMObject], UnknownDatabaseException
    + FullyQualifiedErrorId : Microsoft.EnterpriseManagement.Common.UnknownDatabaseException,SMLets.GetSMObjectCommand
    Get-SCSMObject : Id='SR6298' -- Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
    At D:\ps1\Management Scripts\Set-SRStatus.ps1:6 char:24
    + $SRobj = Get-SCSMObject <<<< -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "ID -eq $SRID"
    + CategoryInfo : NotSpecified: (:) [Get-SCSMObject], UnknownDatabaseException
    + FullyQualifiedErrorId : Microsoft.EnterpriseManagement.Common.UnknownDatabaseException,SMLets.GetSMObjectCommand
    PS D:\ps1\Management Scripts>
    I got this to work previously, I just can't remember how...?
    Joshua Fuente

    That's whats driving me "batty".
    It works from the console.
    PS D:\ps1\Management Scripts> Get-SCSMObject -Class $SRClass -Filter "ID -eq SR6172" | select status
    Status
    Completed
    I tried changing the script to a function, but didn't have any luck.
    I will try with the name param and see if that helps.
    Like I said, I have done this before, it just seems like it different every time.
    So I changed the script to this,
    param([string]$SRID,[string]$Status)
    $a = (get-module|%{$_.name}) -join " "
    if(!$a.Contains("SMLets")){Import-Module 'smlets' -ErrorVariable err -Force}
    Get-SCSMObject -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "Id -eq $SRID" | Select ID, Name, Status
    And it works fine
    PS D:\ps1\Management Scripts> $SRs | ForEach-Object {.\Set-SRStatus.ps1 $_}
    Id Name Status
    SR6172 SR6172 Completed
    SR6411 SR6411 In Progress
    SR6159 SR6159 In Progress
    SR6284 SR6284 In Progress
    SR6280 SR6280 In Progress
    SR6298 SR6298 In Progress
    SR6226 SR6226 In Progress
    SR6262 SR6262 In Progress
    SR6307 SR6307 In Progress
    SR6223 SR6223 In Progress
    SR6264 SR6264 In Progress
    SR6285 SR6285 In Progress
    SR6334 SR6334 In Progress
    SR6255 SR6255 In Progress
    SR6251 SR6251 In Progress
    SR6247 SR6247 In Progress
    PS D:\ps1\Management Scripts>
    And add on the Set-SCSMobj
    param([string]$SRID,[string]$Status)
    $a = (get-module|%{$_.name}) -join " "
    if(!$a.Contains("SMLets")){Import-Module 'smlets' -ErrorVariable err -Force}
    Get-SCSMObject -Class (Get-SCSMClass -name System.WorkItem.ServiceRequest$) -Filter "Id -eq $SRID" | Set-SCSMObject -Property Status -Value $Status
    And now it works...
    PS D:\ps1\Management Scripts> $SRs | ForEach-Object {.\Set-SRStatus.ps1 $_ completed}
    No errors, and all SRs show completed.

  • Parse Excel File via PowerShell for a loop

    Hello everyone,
    I would like to parse a column of one of my Excel file to retrieve the string that each of its cell can contain.
    This will be used to set the appropriate value of the UPN of users in a specific OU in Active Directory.
    The first column being the SAMAccountName and the second column the email address, I would like a loop that for each match of SAMAccountName it finds in the first column, it sets the value of associated row in the second column as its UPN.
    I know already the Active Directory cmdlets I would have to use, they works but I do not succeed retrieving data  like I would like from the Excel file.
    If someone could help me out on this that will be appreciated :)
    Thanks a lot.

    Hi,
    This might help:
    http://gallery.technet.microsoft.com/scriptcenter/7b2fdc8f-a528-4f19-b9ef-f5af349dc906
    I haven't used this module myself, so I'm not sure how well it works.
    Don't retire TechNet! -
    (Don't give up yet - 12,700+ strong and growing)

  • Append string to variable in each iteration of for loop in Powershell.

    Thanks so much I was able to get it working with the following command!
    PowershellGet-Mailbox | where {$_.Name -eq "admin"} | foreach-object {Set-Mailbox -Identity $_.Name -DisplayName "$($_.DisplayName) ABBREVIATION"}
    As for their reasoning behind wanting multiple mailboxes, they seem to be wanting to operate as 2 separate entities still. So their old clients still work with them under the old company name and they are paranoid about having names crossover mistakenly. We did try to get them to switch over to 1 mailbox and demonstrated it for them, but this is what they requested.

    I have to ask - why keep two separate mailboxes for each user rather than just have one mailbox with multiple addresses?But yes, you can concatenate just like other languages. You have two problems currently -
    1. You aren't referencing anything with "$.DisplayName". You need to use "$_.DisplayName" and you need to use it in a Foreach-Object script block.2. You need to pass the concatenated string as a single argument to the -DisplayName parameter. There are several ways to do this but the problem you're having is because there is whitespace in your argument.
    PowershellGet-Mailbox | where {$_.Name -eq "admin"} | foreach-object {Set-Mailbox -DisplayName ($_.DisplayName + ' ABBREVIATION')}#ORGet-Mailbox | where {$_.Name -eq "admin"} | foreach-object {Set-Mailbox -DisplayName "$($_.DisplayName)ABBREVIATION"}

  • Powershell Patching Information: Problems using Export-CSV / looping

    I've made a simple script that obtains patching information from a series of servers.
    The csv file I use to reference my servers is called patchlevels.csv and just contains some basic information.
    ServerName,OS,ServicePack,Patches,,,,,,,
    SERVER1,Server 2003 R2 Enterprise,SP2,,,,,,,,
    SERVER2,Server 2003 R2 Enterprise X64 Edition,SP2,,,,,,,,
    Yup, that's exactly as its formatted ^
    The problem I am having is updating the Patches column with a link to the server-specific htm file (I figure I can always save as xlsx within Excel to get clickable hyperlinks). I have failed multiple times over the last few hours using
    export-csv to try and update the Patches cell(s).
    Here is my script minus any failed export-csv references for clarity's sake:
    $currentPath = "$pwd\"
    $HostFileName = "patchlevels.csv"
    $CSVLoc = $currentPath + $HostFileName
    Import-Csv "$CSVLoc" | ForEach-Object {
    Write-Host "Processing..."
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    $ServerName=$_.ServerName
    $ServerFile = "$ServerName.htm"
    $OS=$_.OS
    $ServicePack=$_.ServicePack
    $_.Patches = $_.Patches.replace("[","$ServerFile")
    Write-Host "Server Name: $ServerName"
    Write-Host "Operating System: $OS"
    Write-Host "Service Pack: $ServicePack"
    Write-Host "Processing Patch List"
    wmic /node:$ServerName /output:$ServerName.htm qfe list
    Write-Host "Patch List generated for $ServerName"
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    Write-Host "END PROCESSING"
    I can see two things that may be wrong:
    1) Formatting of my CSV file (,,,,,,)
    2) I am not sure about the formatting of $_.Patches = $_.Patches.replace("[","$ServerFile")
    And obviously, I'm missing the export-csv commands to update the patchlevels.csv file with the htm file location (which is what this entire post is about).
    Where would I put export-csv in this code to update my original csv as the script runs?
    Thanks in advance for any help with this.
    Kind Regards,
    Stephen

    I've modified the script so that it now actually works as I want it to (more-or-less).
    I will look into using Get-Hotfix instead of WMIC to check that I am happy with the returned data.
    Modified CSV (I changed the Patch column to a known value to simplify replace operation, I couldn't figure out how to replace " "):
    ServerName,OS,ServicePack,Patches,,,,,,,
    SERVER1,Server 2003 R2 Enterprise,SP2,None,,,,,,,
    SERVER2,Server 2003 R2 Enterprise X64 Edition,SP2,None,,,,,,,
    Working code.
    $currentPath = "$pwd\"
    $HostFileName = "patchlevels.csv"
    $CSVLoc = @()
    $CSVLoc = $currentPath + $HostFileName
    Import-Csv "$CSVLoc" | ForEach-Object {
    Write-Host "Processing..."
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    $ServerName=$_.ServerName
    $ServerFile = "$ServerName.htm"
    $OS=$_.OS
    $ServicePack=$_.ServicePack
    Write-Host "Server Name: $ServerName"
    Write-Host "Operating System: $OS"
    Write-Host "Service Pack: $ServicePack"
    Write-Host "Processing Patch List"
    wmic /node:$ServerName /output:$ServerFile qfe list
    Write-Host "Patch List generated for $ServerName"
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    Write-Host "END DATA GATHERING"
    Write-Host "Updating CSV File"
    $update = Import-Csv "$CSVLoc"
    $update | ForEach-Object {
    $ServerName=$_.ServerName
    $ServerFile = "$ServerName.htm"
    $_.Patches = $_.Patches.replace("None",$currentpath + $ServerFile)
    $update | Export-Csv $CSVLoc -NoTypeInformation -Force
    Write-Host "OPERATION COMPLETE"
    Thanks,
    Stephen

  • How can I display a SP 2010 out of the box workflow's task assignees via powershell?

    There are days where one of the 250+ workflows at the site has attempted to send email to someone no longer at the company.
    I would like to find a way to go through the farm and display all the list URLs that have workflows, and the mail addresses associated to the workflows.
    This way I can track down the workflows that need to be updated to remove the missing users.
    I have started a bit of script to do this. In my script, I just had a site collection - I figured that if I can get that to work, then surely wrapping another loop for the rest of the farm won't be bad. 
    However, for some reason, I am not seeing the output that I expected to show the mail addresses.
    I am hoping a different set of eyes might see what I am missing. It was my understanding that the AssociationData property was XML that contained information about the assignees for tasks, the carbon copy list, etc.
    Maybe I misunderstood something that I read?
    $outLoc = "d:\temp\wfdata.txt"
    $web = Get-SPWeb -Identity "http://myfarm/sites/it/"
    foreach ($list in $web.Lists)
     $associationColl=$list.WorkflowAssociations
     foreach ($association in $associationColl)
           $association.AssociationData | Out-File $outLoc
    $web.Dispose()
    I want to thank you for the helpful tips that so often appear on this list. They help me when I am reading over old threads to figure out what to do. I am hoping that tips on this thread will likewise be helpful.

    Hi,
    With
    SPWorkflowAssociation.AssociationData property, we can get the assignees’ information. Your script can
    be able to retrieve a XML format data which contains the user name we need:
    So the next step would be getting the user name by parsing the XML data we got.
    The two links below will show how to parse XML with PowerShell:
    http://stackoverflow.com/questions/18032147/parsing-xml-using-powershell
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/03/26/use-powershell-to-parse-an-xml-file-and-sort-the-data.aspx
    With the user name, we can get the
    Email property of an user with the scripts as the link below provided:
    http://davidlozzi.com/2012/03/07/using-powershell-to-access-sharepoint-sites/  
    Best regards
    Patrick Liang
    TechNet Community Support

  • Powershell Script Send-zip not working when running in cmd

    I found there is powershell send-zip script available in technet.  I tested it and found that it works when the script is running under powershell env, but when it is calling in cmd env, I can see the zip file, but there is nothing in it.  If
    I add the "-noexit" switch it runs normally.  Anyone have ideas what might be happening?
    The orig codes is as following:
    function global:SEND-ZIP ($zipfilename, $filename) { 
    # The $zipHeader variable contains all the data that needs to sit on the top of the 
    # Binary file for a standard .ZIP file
    $zipHeader=[char]80 + [char]75 + [char]5 + [char]6 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0 + [char]0
    # Check to see if the Zip file exists, if not create a blank one
    If ( (TEST-PATH $zipfilename) -eq $FALSE ) { Add-Content $zipfilename -value $zipHeader }
    # Create an instance to Windows Explorer's Shell comObject
    $ExplorerShell=NEW-OBJECT -comobject 'Shell.Application'
    # Send whatever file / Folder is specified in $filename to the Zipped folder $zipfilename
    $SendToZip=$ExplorerShell.Namespace($zipfilename.tostring()).CopyHere($filename.ToString())
    SEND-ZIP C:\abc\a.ZIP C:\a\a.bak

    I've had the same problem with similar code found on another web site.
    The reason the zip file ends up being empty is that the temporary $ExplorerShell object you created is deleted when the send-zip function returns,
    and any incomplete copy operation that may still be ongoing at that time is aborted. (The copy operation is asynchronous, and continues after the CopyHere() function returns.)
    To work around this, you need to add a delay loop before you return, waiting for the copied object to appear in the zip.
    (Note that adding a fixed delay, like I've seen on other web sites, does not work: Small files appear almost immediately, whereas large file or worse still large subdirectory trees can take a long time to appear.)
    Try changing the end of your routine to something like...
    # Create an instance to Windows Explorer's Shell comObject 
    $ExplorerShell=NEW-OBJECT -comobject 'Shell.Application' 
    # Open the zip file object
    $zipFile = $ExplorerShell.Namespace($zipfilename.tostring())
    # Count how many objects were in the zip file initially
    $count = $zipFile.Items().Count
    # Send whatever file / Folder is specified in $filename to the Zipped folder $zipfilename 
    $SendToZip=$zipFile.CopyHere($filename.ToString())
    # Wait until the file / folder appears in the zip file
    $count += 1 # We expect one more object to be there eventually
    while ($zipFile.Items().Count -lt $count) {
        Write-Debug "$filename not in the zip file yet. Sleeping 100ms"
        Start-Sleep -milliseconds 100
    # Return deletes the $zipFile object, and aborts incomplete copy operations.

  • Powershell: There is no file with URL error during file upload.

    I am trying to put together a PowerShell script that I could use to upload files from a local directory, into a Document Library in a Record Center Site. Here is what my script looks like...
    #Open web and library
    $web = Get-SPWeb $webUrl
    $docLibrary = $web.Lists[$docLibraryName]
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    Write-Host "Local Directory:" $localFolderPath
    ForEach($file in $files)
    Write-Host "Looping through files"
    Write-Host "Current file:" $file
    ElseIf ($contentType = "MyContentType")
    #Open file
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
    # Gather the file name
    $FileName = $File.Name
    #remove file extension
    $NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    #split the file name by the "-" character
    $FileNameArray = $NewName.split("_")
    $check = $FileNameArray.Length
    #Add file
    $folder = $web.getfolder($docLibraryUrlName)
    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    $spItem = $spFile.Item
    write-host "Success"
    #populate columns
    $spItem["Application Number"] = $FileNameArray[0].ToString()
    $spItem["Site Number"] = $FileNameArray[1].ToString()
    $spItem.Update()
    $fileStream.Close();
    Each time I run my script, I get this error message 
    Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://myRecordLibrarySite/myRecord Library/12587_B2317.PDF' in this Web."
    At C:\powershellscripts\Upload-FilesIntoSharePoint.ps1:72 char:6
    +                     $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stre ...
    +    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DirectoryNotFoundException
    I have not been able to nail down why the script is failing. Any ideas why? Thanks for the help.

    I just figured out the issue with adding the file. I went in this direction, and my code has progressed forward.
    $folder = $web.getfolder($docLibrary.rootFolder.URL)

Maybe you are looking for

  • Pop Up Menu HELP!

    i am new in using Dreamweaver, but i know the basics. i've been working on this site for a few months, and am not trying to find the best way to create a pop-up/drop down menu for my site. i found out that Dreamweaver should be able to do this, and a

  • 11g: treeTable child record selection

    Hi, I have a (pseudo) model, where entity A is self-referenced and also parent of B, so: A 1 - * A A 1 - * B I'd like to load all As into treeTable, which is not a ploblem. When a record in the treeTable is selected, I need to load detail Bs in a sep

  • Satellite A50-112: F1 key not work for entering Bios

    my toshiba Satellite SA50-112 not entering into BIOS or CMOS setup because of F1 key is not functioning what i can do for changing the boot sequence to CDROM by alternative way. please help us to work better

  • Can we make one query to get same results from 3 tables

    CREATE TABLE TABLE1 (NODEID VARCHAR2(4)); CREATE TABLE TABLE2 (NODEID VARCHAR2(4)); CREATE TABLE TABLE3 (NODEID VARCHAR2(4)); INSERT INTO TABLE1 VALUE('1004'); INSERT INTO TABLE1 VALUE('1004'); INSERT INTO TABLE1 VALUE('1002'); INSERT INTO TABLE1 VAL

  • What is the best tool to use if I want to quickly create and learn SQL?

    I have downloaded and installed: http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html instantclient-sqlplus-win32-10.2.0.3-20061115.zip (722,059 bytes) instantclient-basic-win32-10.2.0.3-20061115.zip (34,469,920 bytes)