Powershell脚本 - 需要编写和附加文本文件

时间:2017-06-26 11:47:28

标签: powershell

我绝不是一位权威专家,所以我的问题对大多数人来说可能很简单...... 我目前每天运行一个powershell脚本,将所有新的.RTF文件从一个目录移动到另一个目录,以便我们的所有客户信息。
但是,并不总是要移动文件,当发生这种情况时,我希望脚本为第一个客户端创建一个文本文件,然后将此条件发送给每个客户端。 我尝试了几种方法,但无法让它发挥作用。

单个客户端的当前脚本是

$path = "\\XXXXX\XXXXXX\XXXXX\XXXXXX\XXXXXX\XXXXXX\*.rtf" 
$Destination = "\\XXXXX\XXXXXX\XXXXX\XXXXXX\XXXXXX\XXXXXX" 
Foreach($file in (Get-ChildItem $path)) 
{   
If($file.LastWriteTime -gt (Get-Date).adddays(-1).date)     
{       Copy-Item -Path $file.fullname -Destination $Destination    } } 

然后我运行一个主脚本,连续启动这个脚本和其他316 ....

2 个答案:

答案 0 :(得分:1)

不是在if循环中的ForEach (...)语句中测试每个单独的文件,而是最初过滤掉这些文件:

$Path = \\...\*.rtf
$Destination = \\...\...
$LastWrite = (Get-Date).AddDays(-1).Date
$FilesToCopy = (Get-ChildItem $path | Where-Object {$_.LastWriteTime -gt $LastWrite})

您现在应该处理$FilesToCopy中的一系列文件;如果该数组为空(长度为零),则在没有要复制的文件时,您需要采取任何操作,否则复制文件:

if ($FilesToCopy.Length -eq 0) {
    # Create the text file
} else {
    ForEach ($File in $FilesToCopy) {
        Copy-Item -Path $File -Destination $Destination
    }
}

请注意@LotPings在评论中是正确的;我上面代码中的ForEach (...)循环实际上可以被$FilesToCopy | Copy-Item -Destination $Destination替换,但我强烈建议您在进行更改之前熟悉PowerShell管道的工作方式 - 它实际上并没有以相同的方式工作批处理(cmd.exe)或Unix / Linux(sh/csh/bash/etc.)管道。

答案 1 :(得分:0)

让你的命令解决,把它变成变量说$ x然后把它管道输出到Outfile 像这样的东西,

$x | Out-File -Append temp2.txt

完整代码应该添加

$path = 'your Path' 
$Destination = "Your destination" 
$x ="No files to copy for client1" 
$LastWrite = (Get-Date).AddDays(-1).Date
 $FilesToCopy = (Get-ChildItem $path )| Where-Object {$_.LastWriteTime -gt $LastWrite} 

 if ($FilesToCopy.Length -eq 0) {
$x | Out-File -Append d:\creditdetails.txt 
  } 
  else { ForEach ($File in $FilesToCopy.FullName) {
   Copy-Item -LiteralPath $File -Destination $Destination 
   }
}
相关问题