首页 > 解决方案 > 将变量作为路径传递时出现 Get-Content 错误 - Powershell 脚本

问题描述

我有以下脚本。

#Script publicador
$carpetas = Get-ChildItem -Directory -Path  C:\Publicaout | Sort-Object {[int]($_ -replace '(\d+).*', '$1')} | Format-Wide -Column 1 -Property Name | Out-String

foreach ($line in $carpetas.Split([string[]]"`r`n", [StringSplitOptions]::RemoveEmptyEntries))
{
  $destino = Get-Content c:\Publicaout\$line\Destino.txt
  echo $destino
  #Copy-Item -Path C:\Publicaout\$line -Recurse -Destination C:\temp\ -ToSession $session -Force 
  #Invoke-Command -ComputerName $destino -Credential $cred -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'c:\temp\$Using:line\publicador.bat'"}
  #Invoke-Command -ComputerName $destino -Credential $cred -ScriptBlock {Remove-Item \\$Using:destino\c$\temp\$Using:line -Recurse -Force}

}

Publicaout它的作用是,首先它按名为in的文件夹上的数字顺序子文件夹排序C:,然后按顺序获取这些子文件夹的列表,然后我使用 for each 将列表中的每个元素用作参数,用于每个文件夹,我将它复制到远程服务器,然后我运行位于该复制文件夹中的脚本,之后,我删除了该文件夹,这样我就不会留下任何剩余物。

到目前为止一切顺利,但现在,在每个文件夹中都有一个文本文件,其中包含每个特定文件夹必须复制到的目标服务器。因此,我认为Get-Content使用包含子文件夹名称的变量向文件添加 + 路径$line就足够了,但是每次运行脚本时都会出现此错误:

Get-Content : Cannot find path 'C:\Publicaout\3000\Destino.txt' because it does not exist.
At C:\Users\elmarichaladmin\Documents\publicador.ps1:18 char:14
+   $destino = Get-Content c:\Publicaout\$line\Destino.txt
+              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Publicaout\3...   \Destino.txt:String) [Get-Content], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

每个文件夹都会发生这种情况,我有 5 个文件夹,分别命名为 1、99,654,3000、65404。这真的很奇怪,因为该Copy命令运行良好,但 Get-Content 没有。

有任何想法吗?我知道错误显示一个空行,但是正如您所见,当我运行字符串拆分时,我删除了每个空行。

标签: powershellscripting

解决方案


推荐阅读