【问题标题】:"Get ChildItem : Cannot find path" showing path I did not supply“获取 ChildItem:找不到路径”显示我没有提供的路径
【发布时间】:2022-01-19 18:13:55
【问题描述】:

我继承了一个脚本,它应该只是将文件从 -source 移动到 -target。两者都提示我,在提供路径后,它告诉我在显示我绝对没有提交的路径时找不到路径,但无法弄清楚它是如何到达那里的。

    [Parameter(
        Mandatory = $true,
        Position = 0,
        HelpMessage = "Root of the folders or share to archive"
    )]
    [String] $source,
 
    [Parameter(
        Mandatory = $true,
        Position = 1,
        HelpMessage = "Path of the folder or share of archive"
    )]
    [string] $target,
 
    [Parameter(
        Mandatory = $false,
        Position = 3
    )]
    [int] $days = 30
)
 
# Get all the files from the source path, that are not shortcuts (*.lnk) and older than the days set
Get-ChildItem $source -Recurse |  
        Where-Object {!$_.psiscontainer -and ((get-date) - $_.lastwritetime).totaldays -gt $days -and $_.extension -ne ".lnk"} |
            ForEach-Object {

# For each file build the destination path 
                $dest = $_.fullname -replace ([regex]::escape($source)), $target
 
# Move the files into the destination
                Move-Item -Path $_.fullname -Destination $dest -ErrorAction silentlycontinue
}

日志显示“找不到路径 '\\appserver\abc$\Automation\Daily\Archive\appserver\abc$\Storage',因为它不存在” - 看看它是如何开始重复的? \\appserver\abc$\Automation\Daily\Archive\ 是脚本的位置,而 \\appserver\abc$\Storage\ 是我输入的-source。所以我不知道它为什么要查看脚本的路径,然后同时附加源路径。

编辑:这就是我调用脚本的方式(来自一个鲜为人知的名为 APX 的金融应用程序):

SHELL PowerShell \\appserver\abc$\Automation\Daily\Archive\ArchiveFiles.ps1 -source \\appserver\abc$\Dataport\dpdata -target \\appserver\abc$\Dataport\archived -days 30

【问题讨论】:

  • 在您的foreach-object 中添加一些日志记录并检查变量是否包含您期望的值 - 例如write-host "source = '$source'"; write-host "target = '$target'"; write-host "fulllname = '$($_.FullName)'"; write-host "dest = '$dest'",然后向后工作。我的猜测是你的 -replace 正在做一些意想不到的事情......
  • 您能解释一下“添加一些日志记录”的评论吗?对 Powershell 的经验很少,不确定第一步会是什么。谢谢
  • @mklement0 帖子现已编辑
  • 谢谢,但请format the command properly 并说明您从哪个应用程序调用。使用正确的格式,您可以完全按照在您的环境中提交的命令来表示。
  • 老实说,我不确定哪些格式选项适用于我的命令,对不起,我在这里的第一篇文章。它是没有人听说过的金融相关软件,称为 APX。该命令在 APX“脚本”中,我保存它并单击运行,然后调用 PS 脚本。

标签: powershell path filesystems


【解决方案1】:

当你的脚本启动时,它从你运行它的目录开始,所以它已经在\\appserver\abc$\Automation\Daily\Archive\,如果你不提供UNC resource prefix,比如\\A:\ 然后它将从该目录向下查找 ChildItems。因此,当您提供文件夹路径时,它会将其附加到其当前目录并且无法找到新路径。

因为只有在字符串开头省略了\\ 时才会发生这种情况,因此我只希望您将appserver\abc$\Storage\ 作为源代码提交给您的输出。如果您确定您确实提供了 \\,那么更仔细地查看将命令 to 传递给该脚本的任何脚本行,看看它是否有原因提前剥离了 \\ .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2014-09-14
    • 2017-10-05
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多