首页 > 解决方案 > 有没有办法自动调用要在脚本中使用的文件?

问题描述

我有一个比较 2 个 XML 文件的脚本。现在,我对文件位置进行了硬编码,但我需要找到一种方法让它们以某种方式被调用。也许使用参数会起作用?我试过到处玩,但无法得到任何工作。我知道使用斜线以某种方式引用它有什么用?我对 PS 真的很陌生,不确定如何去做。

这是我所拥有的:

[xml]$file1 = Get-Content "C:\Generic.xml"
[xml]$file2 = (Get-Content "C:\Comparison.xml")
 $file1
$file2
$file1.configuration
$Compare = Compare-Object -ReferenceObject $file1.configuration.ChildNodes -DifferenceObject $file2.configuration.ChildNodes -IncludeEqual
    if ($compare.SideIndicator -eq "==") {
        "There is a match for all of the child nodes"
    }
    Else {
        "There is a child node missing"
    }

$file1.configuration.appSettings.add | more
$file2.configuration.appSettings.add | more
$Compare = Compare-Object -ReferenceObject $file1.configuration.appSettings.add -DifferenceObject $file2.configuration.appSettings.add -Property key,value -IncludeEqual
foreach ($compare in $Compare) {
    if ($compare.SideIndicator -eq "==") {
        "There is a match for key $($compare.key) and value $($compare.value)"
    }
    if ($compare.SideIndicator -eq "<=") {
        "There is no match for key $($compare.key) and value $($compare.value)"
    }
}

任何意见,将不胜感激!

标签: powershell

解决方案


您可以将其包装在一个函数中,这将允许您使用您选择的可变参数执行脚本:https ://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions ?view=powershell-6

因此,在您的函数中,您将使用大部分相同的代码,但可能需要修改:

[xml]$file1 = Get-Content "C:\Generic.xml"

[xml]$file1 = Get-Content $file1_path

然后使用如下格式执行:

Compare-XML -file1_path "C:\Generic.xml"


推荐阅读