Suppress file deletion confirmation on remote server in Invoke-Command

Hi!
I try create function used for removing folders (and all content) on remote servers .
$FullPathToDelete="\\"+("$Computername\$BasePath\$FolderToDelete").Replace("\\","\")
if (Test-Path $FullPathToDelete -pathType container ) {
$ScriptBlockContent = {
paramater($FullPathToDeleteLocal)
Get-ChildItem -Path $FullPathToDeleteLocal -Recurse | Remove-Item -Force $true -Recurse $true -Confirm:$false | Out-Null
Invoke-Command -Computername $Computername -ScriptBlock $ScriptBlockContent -ArgumentList $FullPathToDelete -AsJob
Remove-Item -Path $FullPathToDelete -Force | Out-Null
Example values for variables
$Computername = "SPPL09281"$BasePath="D$"$FolderToDelete="FolderName"
All work but for every computer (I use this code in a loop) I receive additional prompt for confirmation
Id Name State HasMoreData Location Command
11 Job11 Running True SPPL09281 ...Confirm
The item at Microsoft.PowerShell.Core\FileSystem::\\SPPL09281\D$\FolderName has children and the Recurse
parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to
continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
How I can avoid these confirmation prompts?
Thank you in advance.
Wojciech Sciesinski

Hi Wojciech,
In addition, The original confirm is reminding the folder you want to delete has subfiles, please try to add -recurse parameter:
$FullPathToDelete="\\"+("$Computername\$BasePath\$FolderToDelete").Replace("\\","\")
if (Test-Path $FullPathToDelete -pathType container ) {
 $ScriptBlockContent = {
  paramater($FullPathToDeleteLocal)
  Get-ChildItem -Path $FullPathToDeleteLocal -Recurse | Remove-Item -Force -Recurse -Confirm:$false | Out-Null
 Invoke-Command -Computername $Computername -ScriptBlock $ScriptBlockContent -ArgumentList $FullPathToDelete -AsJob
 Remove-Item -Path $FullPathToDelete -Recurse -Force
If there is anything else regarding this issue, please feel free to post back.
If you have any feedback on our support, please click here.
Best Regards,
Anna Wang
TechNet Community Support

Similar Messages

  • How can you run a command with elevated rights on a remote server with invoke-command ?

    I am trying to run a script on a remote server with invoke-command.  The script is starting and is running fine, but the problem is that it should be running with elevated rights on the remote server.  On the server where I start the invoke-command, my account has the necessary rights.
    The server were I launch the invoke-command is a W2K8 R2.  The remote box is a W2K3 with powershell v2.0 installed.
    When I launch the script on the remote-box from the command line, I don't get the access denied's.
    Is there a way to do this ?
    Thanks in advance

    The script that I want to run is to install the windows updates.  I get an access denied on the download of the updates.
    When I execute the script on an W2K8 box, (not remotely) and I run it with non-elevated rights, I get the same error.
    The script is running fine when it is launched on W2K3 box locally with a domain account that has local admin rights, or on a W2K8 R2 server with a domain account that has local admin rights, but with elevated rights.
    Thanks in advance for your help.
    #=== start script ====
    param($installOption="TESTINSTALL",$rebootOption="NOREBOOT")
    Function Show-Help
    Write-Host ""
    Write-Host "SCRIPT: $scriptName <installOption> <RebootOption>"
    Write-Host ""
    Write-Host "DESCRIPTION: Installatie van WSUS updates op de lokale server"
    Write-Host ""
    Write-Host "PARAMETERS"
    Write-Host " -installOption <[INSTALL|TESTINSTALL]>"
    Write-Host " -rebootOption <[REBOOT|NOREBOOT|REBOOT_IF_UPDATED]>"
    Write-Host ""
    Write-Host "EXAMPLE:"
    Write-Host "$ScriptName -installOption INSTALL -rebootOption REBOOT_IF_UPDATED"
    Write-Host "$ScriptNAme INSTALL NOREBOOT"
    Write-Host ""
    Write-Host "Indien beide parameter weggelaten worden zijn de defaultwaarden :"
    Write-Host " installOption=TESTINSTALL "
    Write-Host " RebootOption=NOREBOOT"
    Write-Host ""
    Exit
    #Include alle globale variablen
    $CEIF_WIN_PATH = (get-content env:CEIF_WIN_PATH)
    $includeFile=$CEIF_WIN_PATH + "\Scripts\include_win.ps1"
    . $includeFile
    #initialiseer error count
    $errcnt=0
    $scriptName=$MyInvocation.MyCommand.Name
    #argumenten controleren
    $arrInstallOption= "TESTINSTALL", "INSTALL" # Mandatory variable with predefined values
    If (!($arrInstallOption –contains $installOption)){ Show-Help }
    $arrRebootOption = "REBOOT", "NOREBOOT","REBOOT_IF_UPDATED" # Mandatory variable with predefined values
    If (!($arrRebootOption –contains $rebootOption)){ Show-Help }
    #Logfile opbouwen
    $logfile = get-logfileName($MyInvocation.MyCommand.Name)
    Log-scriptStart $MyInvocation.MyCommand.Name $logfile
    function Get-WIAStatusValue($value)
    switch -exact ($value)
    0 {"NotStarted"}
    1 {"InProgress"}
    2 {"Succeeded"}
    3 {"SucceededWithErrors"}
    4 {"Failed"}
    5 {"Aborted"}
    function boot-server()
    if ($installOption -eq "TESTINSTALL")
    logger "TESTINSTALL : - Reboot local Server" $logfile
    else
    logger " - Reboot local Server" $logfile
    $thisServer = gwmi win32_operatingsystem
    $thisServer.psbase.Scope.Options.EnablePrivileges = $true
    $thisServer.Reboot()
    $logmsg="Install option = " + $installOption + ", RebootOption = $rebootOption"
    logger "$logmsg" $logfile
    logger "" $logfile
    logger " - Creating WU COM object" $logfile
    $UpdateSession = New-Object -ComObject Microsoft.Update.Session
    $UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
    logger " - Searching for Updates" $logfile
    $SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
    logger " - Found [$($SearchResult.Updates.count)] Updates to Download and install" $logfile
    $Updates=$($SearchResult.Updates.count)
    logger "" $logfile
    foreach($Update in $SearchResult.Updates)
    if ($Update.EulaAccepted -eq 0)
    $Update.AcceptEula()
    # Add Update to Collection
    $UpdatesCollection = New-Object -ComObject Microsoft.Update.UpdateColl
    $UpdatesCollection.Add($Update) | out-null
    if ($installOption -eq "TESTINSTALL")
    else
    # Download
    logger " + Downloading Update $($Update.Title)" $logfile
    $UpdatesDownloader = $UpdateSession.CreateUpdateDownloader()
    $UpdatesDownloader.Updates = $UpdatesCollection
    $DownloadResult = $UpdatesDownloader.Download()
    $Message = " - Download {0}" -f (Get-WIAStatusValue $DownloadResult.ResultCode)
    if ($DownloadResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    # Install
    logger " - Installing Update" $logfile
    $UpdatesInstaller = $UpdateSession.CreateUpdateInstaller()
    $UpdatesInstaller.Updates = $UpdatesCollection
    $InstallResult = $UpdatesInstaller.Install()
    $Message = " - Install {0}" -f (Get-WIAStatusValue $InstallResult.ResultCode)
    if ($InstallResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    logger "" $logfile
    #Indien er een fout gebeurde tijdens download/installatie -> stuur mail naar windowsteam
    if ( $errcnt -gt 0 )
    logger " - Fout tijdens de uitvoering van script -> send mail" $logfile
    $mailSubject=$MyInvocation.MyCommand.Name
    $msg = new-object Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($logfile)
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = $mailFrom
    $msg.To.Add($mailTo)
    $msg.Subject = $mailSubject
    $msg.Body = “Meer details in attachement”
    $msg.Attachments.Add($att)
    $smtp.Send($msg)
    #Moet de server herstart worden ?
    if ($rebootOption -eq "REBOOT_IF_UPDATED" )
    if ($Updates -gt 0)
    #Reboot the server when updates are installed
    boot-server
    elseif ($rebootOption -eq "REBOOT")
    #reboot the server always
    boot-server
    else
    #Do not reboot the server
    logger "Do not reboot the server" $logfile
    Log-scriptEnd $MyInvocation.MyCommand.Name $logfile
    exit 0

  • Sql loader issue(How to specify a file that exists on remote server)

    In sqlldr infile parameter I'd like to give a data file that exists on remote server.How can I specify???Please help me in the syntax.
    Any help would be greatly appreciated.
    Edited by: 792353 on Sep 24, 2010 7:22 AM

    sqlldr can accept any path that is VALID and it can be any type of share as long as the OS supports the share.
    so INFILE can be anything you want as sqlldr will simply attempt to access it via the OS.
    if you are on a linux box going to another linux box with an NSF mount point on the box running sqlldr simply reference:
    INFILE '/mountpoint/fname'
    Now I have never tried a UNC path before but I would guess that if you are on a windows box, going to another winddows box and the box running sqlldr was logged in with the right permissions it would simply be:
    INFILE '\\server\directory\file'
    I doubt that it will accept a URL as in:
    INFILE '//servername.com/directory/file'
    I don't think that sqlldr does anonymous ftp or htp file transfer protocol, but I could be wrong.
    NOTE: I have found that it is best to ALWAYS surround your INFILE parameter with single quotes.

  • C# Run VB Script file remotely thriugh PowerShell Invoke Command

    I have a requirement where need to run vbscript remotely through PowerShell Invoke command. I can run the VB Script locally but not remotely as the vbscript file is not present on the remote machine. I don't want to copy the script file on remote machine.
    Please let me know how to run vb script on remote machine. Below is the code.
    Collection<PSObject> output
    = null;
            using
    (Runspace runSpace =
    RunspaceFactory.CreateRunspace())
                runSpace.Open();
                using
    (Pipeline pipeline = runSpace.CreatePipeline())
    RunspaceInvoke invoke =
    new RunspaceInvoke();
    PowerShell ps = PowerShell.Create();
                    ps.Runspace
    = runSpace;
                    ps.AddCommand("invoke-command");
                    ps.AddParameter("ComputerName",
    "RemoteServerName");
    ScriptBlock sb = ScriptBlock.Create("cscript E:\\Test\\DeleteFiles.vbs");
                    ps.AddParameter("ScriptBlock", sb);
                    output
    = ps.Invoke();
    Regards, Parveen

    Hello Parveen,
    Please refer to the following thread
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/7562eefb-7fba-4bf6-834e-82256f159155/run-script-on-remote-macine?forum=csharpgeneral
    See his code:
    You can use WMI to create processes on a remote machine. In C#, use the ManagementClass.
    using System;
    using System.Management;
    using System.Collections.Generic;
    public class MyClass
    public static void RunNotepad()
    ManagementPath p = new ManagementPath(@"\\targetMachine\root\cimv2:Win32_process");
    ManagementClass m = new ManagementClass(p);
    m.InvokeMethod("Create", new Object[] {"notepad.exe"});
    See: Creating Processes Remotely
    Note that the the scrpt file is not executable so you have to create script like this:
     cscript.exe "\\yourmachine\script\test.vbs".
    Best regards,
    Barry
    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.

  • Access a file physically on a remote server

    Hi,
    Is there any way we can access a file using the physical path on a remote server? I need to read and delete content of a remote directory on the LAN. All I got so far is access denied so I wonder if it's possible.
    Here's the situation:
    On a web server using IIS and Tomcat, my JSP page tries to read a distant file using a path like \\172.31.3.3\reports\file.html. Once it's read, I have to delete it.
    What windows user is accessing the file? What permissions does he need?
    I could access it using HTTP but the problem would be to delete it. I don't know any way to delete a file using HTTP. Any idea?
    Thanks for any help,
    Stephane

    You can also use jcif. If the file is on a windows based computer you'll need to share the directory. If it is on a Unix/Linux based computer you'll have to install/enable samba. In either case you'll probably need a user name/password. Check out http://jcifs.samba.org/

  • Write records to a Flat file & Ftp to a remote server

    I know this would be a basic question for most of the ppl in this forum, but I am stuck in here.
    There is a "Orders" table, and when new orders are made , I need to build a file with relevant information(extracted from tables) and FTP to a remote server.There should be a SQL job that would run for every 30 mins to see if there are any new orders made , and if so, Write them to a file and FTP back to a remote server.
    The orders that were written to a file previously shouldn't appear when new files are created.
    How can this be done..?
    Thanks in advance..

    You'd need 3 basic components here
    1) Something to identify new orders
    2) Something to write whatever data you want to a flat file
    3) Something to FTP that file
    #2 is going to be the UTL_FILE package
    #3 is going to require a third-party PL/SQL (or Java) FTP library. If you do a Google search on UTL_FTP, you'll find a few such PL/SQL packages or you can download an appropriate Java class and load that into the database.
    #1 can be as simple as a Status column that gets set to NEW initially and PROCESSED when the file is generated. Or it could get a lot more complicated with something like Streams capturing changes to the table and sending those change records to a separate consumer process that would then generate the file and FTP it.
    Justin

  • How can I delete messages from the local Sent folder without deleting from the remote server?

    I am running out of disk space on my local machine. Analysing this, I can see that a large amount of space is being taken up by local storage of Sent emails from my IMAP synchronised account.
    I do not see how I can delete the local copies from my PC without them being deleted from the Server as well. There is an account setting option under Synchronisation and Storage to delete messages, but it says they will be deleted from both the local machine and the remote server.
    I need to keep the server versions as these are business accounts and it is important I have all my old messages stored somewhere.

    Short answer: get a bigger hard disk.
    You could disable synchronization and free up the space on your local disk without loosing the messages. However, this would eliminate the possibility to create backups of your messages.<br>
    Since you mentioned this is important business mail, you shouldn't take chances.

  • How do I copy and paste files from a windows remote server to my mac?

    How can i copy and paste files from a remote server (windows) to my mac? i have installed cord to connect to the server but now i can´t cpy the files to my mac!

    Hi Sara.  Tanks for responding.  If I cannot figure this out (I  was up
    until 2am last night), I want to cancel my subscription.
    Here are two files you can check on/help me with.  When I try again,  it
    comes up 'an error has occurred when trying to access the service.'
    Please advise.
    Pat Tomassi
    In a message dated 11/1/2014 12:55:23 A.M. Eastern Daylight Time, 
    [email protected] writes:
    How  do I copy and paste text from a converted Word document?
    created by Sara.Forsberg (https://forums.adobe.com/people/Sara.Forsberg) 
    in Adobe Acrobat.com Services - View the full  discussion
    (https://forums.adobe.com/message/6888908#6888908)

  • Using a servlet to read a pdf file that is in remote server

    Hi,
    I read some topics about how to read a pdf file using a servlet...but my issue is that my pdf files are on a remote Sun solaris server (intranet) and my servlet will be in a public network (internet), so my question is, still be possible to use this solution to read my remote file ? how i can access the remote file ??
    any idea from where I can start ??
    best regards,
    carlos.

    You may use a FTP client component to connect with your servlet to the Sun server, retrieve the bytes and serve them to the browser. Instead of reading the stream from a local file, you will be reading from a network socket, but the code -if well written and designed- may be very similar.
    There are many good ftp client components for java, you may also use other protocols like HTTP or SCP (ssh file transfer).
    Regards,
    Martin Cordova
    http://www.martincordova.com
    Dinamica framework for J2EE
    - the easiest way to Java webapps...

  • Absolute URLs  not working when file is on a remote server.

    My client has asked me to provide a template for an investor relations section of their website. The HTML page or template for this page will be at the service providers site, but all the images etc. for the page will be linked to files on my clients server. Everything looks fine, but the absolute URL's in the .swf file back to my clients site aren't working.
    This is what the service provider's guidlines say, but I'm not sure where the code is supposed to go:
    Similarly, newer versions of the Flash Media Player installed by most users have a high level of security enabled by default. This is done to prevent Flash movies from playing on web pages that are hosted on different domains than the movie itself (again, to combat “phishing” or “spoofing”).
    You do have the ability to overwrite this feature by proactively developing your Flash file so that it contains the following lines of code:
    System.security.allowDomain(“*”)
    stem.security.allowInsecureDomain(“*”)
    Sy
    You should also add the following line of HTML within the embedded Flash call in your HTML template:
    <param name=”AllowScriptAccess” value=”always” />
    This solution requires edits to the ActionScript of the pre-compiled Flash file, and is not something we can edit. For further guidance and more information, please speak with the developer of your Flash file.
    Thanks

    the easiest way to deal with security issues is to avoid them.  if all files are on the same server, use relative urls.
    otherwise, you may have to deal with security issues.  whether you do or not, and if you do, how you deal with them, depends on what you're trying to do.
    you may be able to use System properties but you may need cross-domain security files.

  • Don't print files which came from remote server software

    I have  HP LaserJet Pro M1132 and in local network it works fine but if i try to print files over remote desktop connection via terminal services easy print it send files to printer Que but don't print them.
    please help

    How do I delete them?
    These:
    /Library/Frameworks/GenieoExtra.Framework
    /Library/PrivilegedHelperTools/com.genieoinnovation.macextension.client
    /Library/LaunchAgents/com.genieoinnovation.macextension.plist
    /Library/LaunchDaemons/com.genieoinnovation.macextension.client.plist

  • Disable file deletion confirmation in Lion

    How do I do this?

    I have (4) Macs running Lion, including a new MacBook Air purchased today. On the MBA, when I want to delete a file, I'm getting a dialog box asking me to confirm the deletion and reminding me that the operation cannot be undone. I never saw this before on the other Macs. It appears nothing is going into the trash which may explain the problem. Can I unblock the trash?

  • Use of policy file to connect to remote server

    I am trying to use the socket.connect(serverURL, portNumber)
    to connect to a server through telnet port 23. I am unable to
    connect through port 23. please advise

    I am trying to use the socket.connect(serverURL, portNumber)
    to connect to a server through telnet port 23. I am unable to
    connect through port 23. please advise

  • Remote Exchange Powershell invoke command - customize return result

    Hi
    I am trying to create a powershell which connects to an exchange management shell and executes a command.
    [scriptblock]$Command = {Get-MailboxDatabaseCopyStatus | select Name,ContentIndexState}
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$Computername/powershell -Credential $Cred
    Import-PSSession $Session
    $Returnvalue = $Command.Invoke()
    Remove-PSSession $Session
    This would return a result like this:
    Name : DB02 - Specielle\EXCHANGE01
    ContentIndexState : Healthy
    Name : DB01 - Standard\EXCHANGE01
    ContentIndexState : Healthy
    Now how do I create an if-sentence that would check if both are "Healthy" and then return "Echo "Healthy"", else if one is not healthy then return "Echo "Not Healthy""? (I dont need to specify which one that
    isn't healthy).
    Best Regards,
    Soren

    Hi Soren,
    Give this a try (untested, sorry):
    [scriptblock]$Command = {
    $healthy = $true
    $statusList = Get-MailboxDatabaseCopyStatus
    foreach ($status in $statusList) {
    If ($status.ContentIndexState -ne 'Healthy2') { $healthy = $false }
    If ($healthy) { Write-Output 'Healthy' }
    Else { Write-Output 'Not Healthy' }
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • Empty folders on remote server after synchronization

    I am trying to set up a working environment for a very large web site and to get to the point of my post...
    Whenever I try and synchronize my FTP with my local copy, I am selecting "Delete remote files not on local drive."
    While the files are deleted on the remote server as they should be, it leaves behind empty directories all over the place where these files used to be.
    The site is large enough that it takes over an hour to ftp it up to my testing server and I am doing a large amount of cleanup and deleting un-necessary files / directories all over the site. If I am going to have to manually track down every empty directory and remove them one by one, it is going to be faster to completely delete my FTP space and re-upload the site every single time I make some revisions which is a bit ridiclulous.
    Isn't deleting the remote directories if I have deleted them locally considered part of SYNCHRONIZATION?
    The site is so large that I can go grab a coffee while the synchronization is taking place but it is not quite as bad as re-uploading the entire local copy of the site every time I make significant changes to the site structure.
    I guess this is related to why Dreamweaver throws "_notes" folders all over my site CONSTANTLY even when I have design notes turned off for my sites?
    I have so many complaints about Dreamweaver and the fact that it pretty much has not improved much at all since Adobe took it over from Macromedia I don't know where to begin. I guess this would be a good place to start LOL!

    As much as I hate replying to myself...
    I was reading through this thread
    http://digg.com/apple/OSXLeopard_Another_Serious_BUG_Unable_to_Browse_SMB_WindowsShares
    I tried many of the suggestions one at a time. Unfortunately, I tried way too many suggestions to know if/which any single one was the "fix". The last three configuration changes I made were to disable IPV6, enable SMB sharing, then disable AFP sharing. After each of these, I did "sudo killall Finder" from a terminal.
    Now it works for me as desired.
    I hope this helps someone else.

Maybe you are looking for

  • Unable to install windows 8.1 in Yosemite

    Hi, I have a mac book pro retina display, as well as Boot Camp 5.1 version, yet I can't install windows 8.1. I followed the instructions in Boot Camp: Creating an ISO image from a Windows installation DVD - Apple Support to create an ISO image but wh

  • Email notifications stuck in Mail status

    Hi, The notification mailer is up and running and we receive emails when we run the test. However, when a user goes through the application, lets say the Purchase requisition process, the process completes successfully, we see the notification in his

  • Pegging with characteristics

    Is it possible that pegging between production orders and requirements take into account their characteristic values? For example if the characteristic "width" is 2600 for the production order and 2000 for the requirement then these wouldn't peg? My

  • Jdbc to SQL Server Express

    Hi I am trying to connect jdeveloper to sql server express. my code is as follows: Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn = DriverManager.getConnection("jdbc:sqlserver://localhost\\SQLExpress;user = joebloggs;pssword=pass

  • Maping of business into sap system

    Dear Experts- Please tell me in detail to map preoder activites in the system. we want inquiry and  quatation . revenue palanning on the behalf of quatation with order billing request . and linking of all the things to project system. Please explain