Powershell:为什么这个功能不起作用?

时间:2018-05-24 20:21:42

标签: function powershell powershell-v3.0

我正在尝试使用整齐排列的函数制作一个脚本,比较两个文件夹项。该计划:

  1. 提示用户输入文件路径
  2. 检查文件名是否不同
  3. 检查文件大小是否不同
  4. 作为测试,我一直在将相同的文件夹与自身进行比较(输出应为false,false)。在执行第1步($referencepath)函数(FolderPrompt)时,我的程序无法正常工作,我的意思是,我似乎每次运行时都会得到不同的答案。

    这有效:

    $referencePath = Read-Host -Prompt "Enter new DTNA folder path to check" 
    
    NameDisc
    SizeDisc
    
    function NameDisc {
        write-host "Name Discrepancy: " -NoNewline 
    
        if (Compare-Object -Property name (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
            {return $true} 
        else
            {return $false}
    }
    
    function SizeDisc {
        write-host "Size Discrepancy: " -NoNewline 
    
        if (Compare-Object -Property length (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
            {return $true} 
        else
            {return $false}
    }     
    

    但这不是:

    FolderPrompt
    NameDisc
    SizeDisc
    
    function FolderPrompt {
        $referencePath = Read-Host -Prompt "Enter new DTNA folder path to check" 
    }
    
    function NameDisc {
        write-host "Name Discrepancy: " -NoNewline 
    
        if (Compare-Object -Property name (Get-ChildItem $referencePath) -DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
            {return $true} 
        else
            {return $false}
    }
    
    function SizeDisc {
        write-host "Size Discrepancy: " -NoNewline
    
        if (Compare-Object -Property length (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
            {return $true} 
        else
            {return $false}
    }     
    

    我尝试过:

    • 在调用函数之前声明函数

    • 每次都要$referencePath = 0重置值 认为这是问题

    • Return $referencePath放在不同功能的末尾

    我最好的猜测是我需要做function <name> ($referencePath)这样的事情来传递变量(?)。

1 个答案:

答案 0 :(得分:5)

分配给函数后,

$referencepath将成为函数的本地函数,因此您的值将丢失,因为您不返回它。你说你试过在“各种功能”中回归它,但目前还不清楚它是什么样的。

您也不应该依赖从父作用域继承变量的函数。理想情况下,您将传递任何所需信息作为参数。

在PowerShell中调用函数时,不要对参数使用括号和逗号,请使用空格。

function FolderPrompt {
    Read-Host -Prompt "Enter new DTNA folder path to check" 
}

function NameDisc { 
param($referencePath)

    write-host "Name Discrepancy: " -NoNewline 

    if (Compare-Object -Property name (Get-ChildItem $referencePath) -DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
        {return $true} 
    else
        {return $false}
}

function SizeDisc {
param($referencePath)

    write-host "Size Discrepancy: " -NoNewline

    if (Compare-Object -Property length (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
        {return $true} 
    else
        {return $false}
}     

$refPath = FolderPrompt
NameDisc -referencePath $refPath
SizeDisc -referencePath $refPath

这就是修改后的代码的外观。

相关问题