Powershell - 移动文件后如何重命名文件?

Powershell - How to rename a file after moving it?

我目前正在处理一个项目,该项目要求我移动一个文件,然后重命名它。我正在使用此代码来移动它并且正在运行。但是,重命名部分没有按预期进行。我不明白为什么这不起作用。我搞砸了什么?为了解决这个问题,我一直在用头撞桌子至少 20 分钟。

# Variables for Watcher
$folder = "C:\Program Files\Whatever\Connector\Export\JobStatus"
$filter = '*.txt'
$date=(get-date -Format d) -replace("/")
$time=(get-date -Format t) -replace(":")

# Watcher + Settings                     
$fsw = New-Object IO.FileSystemWatcher $folder, $filter
$fsw.IncludeSubdirectories = $false
$fsw.NotifyFilter = [IO.NotifyFilters]'FileName', 'DirectoryName'

# Register Event (when file is created)
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated 
-Action {

# Foreach file loop 
ForEach ($f in $fsw)
{
    if (($File = Get-Item $Event.SourceEventArgs.FullPath | select -Expand 
Extension) -eq ".txt")
    {
        #Used for file testing - Opens the text file for 10 secs, then kills 
it.
        #Start-Process -FilePath $Event.SourceEventArgs.FullPath  | %{ sleep 
10; $_ } | kill


        # Variables for move   
        $folderpath = ($Event.SourceEventArgs.FullPath | Split-Path)
        $folderfile = ($Event.SourceEventArgs.FullPath | Split-Path -Leaf)
        $destination = "C:\Program Files\Whatever\Connector\Staging\"
        $newname = "job.import.$date"+"_"+"$time.txt"


    }

    # Variables for logging
    $logpath = 'C:\Program 
Files\Whatever\Connector\Export\JobStatus\outlog.txt'

    # Grab current file and move to "Staging" folder
    try
    {



        Get-ChildItem -Path $folderpath -Filter $folderfile | Move-Item - 
Destination $destination | sleep 5 | Write-Host Rename-Item 
$destination$folderfile -NewName $newname | Out-File -FilePath $logpath - 
Append
        Write-Host $destination$newname
        #sleep 5

        #Rename-Item "$destination $folderfile" -NewName $newname
        #Write-Host $destination $folderfile
        #"File $folderfile renamed to $newname" | Out-File -FilePath 
$logpath -Append

        # Log the move in logfile   
        "File $folderfile moved to $destination" | Out-File -FilePath 
$logpath -Append






    }

    # Log if errors + clear
    catch
    {
        $error | Out-File -FilePath $logpath -Append
        $Error.Clear()
    }
}
}

我实际上修复了这个删除管道重命名并将其替换为 5 秒睡眠。我在睡觉后重命名,现在工作正常。仍然不确定为什么重命名在管道命令中不起作用。

没有对象输出时管道中断。除非使用 -passthru 参数,否则 move-item 不会输出对象。此外,set-sleep 不输出任何内容。因此,rename-item 永远不会达到。

move-itemsleep 之后的管道替换为分号,它应该可以工作。