PowerShell XML:切换vs if [英] PowerShell XML: Switch vs if

查看:122
本文介绍了PowerShell XML:切换vs if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过PowerShell对XML文件进行简单的查找/替换。我在尝试替换节点中的文本时遇到错误,但仅在使用开关时...使用通用if语句完美地工作。

Doing a simple find/replace with an XML file via PowerShell. I am getting errors when attempting to replace text in a node but only when using a switch...using a general if statement works perfectly.

代码从此开始:

$oldString = 'AAAA'    
$newString = 'BBBB' 
[xml]$xml = Get-Content $myXMLFile
$list = Select-Xml -Xml $xml -XPath '//add'
$list|Foreach-Object {
   [string]$key = $_.node.key
   [string]$value = $_.node.value

普通的旧IF版本可以正常工作...

The plain old IF version works as I would expect...

   if($value -eq $oldString)
   {
      $_.node.value = $newString
   }
}|Set-Content $myXMLFile

但是用switch语句替换IF会引发错误。

But replacing the IF with a switch statement throws an error.

   switch($value)       
   {
       $oldString{$_.node.value = $newString}
   }    
}|Set-Content $myXMLFile

Property 'value' cannot be found on this object; make sure it exists and is settable.
+          $oldString{$_.node.value = $newString}
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
     + FullyQualifiedErrorId : PropertyNotFound

我有很多节点数据需要替换,如果我可以使用开关,我宁愿不写一堆IF。

I have a lot of node data to replace and I would rather not write a bunch of IF's if I can get away with a switch.

推荐答案

$ _ 的上下文在开关块内部与其外部不同。

The context of $_ is not the same inside the switch block as it is outside of it.

交换机块内部 $ _ $ value 而不再是原始节点。

Inside the switch block $_ is $value and not the original node anymore.

这篇关于PowerShell XML:切换vs if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆