本文介绍了如何在PowerShell中比较其中包含与号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PowerShell来比较其中包含&符号的两个字符串(即字符串"Policies& Procedures").

I am using PowerShell to compare two strings that have an ampersand (&) in them (i.e. the string "Policies & Procedures").

无论我做什么,我都无法使这些字符串匹配.我已经尝试过修剪琴弦,以消除多余的空白.我试过将字符串用单引号和双引号(以及两者的组合)包装:

No matter what I try, I cannot get these strings to match. I have tried trimmed the strings to get rid of an extra white spaces. I have tried wrapping the the string in both single and double quotes (and a combination of both):

"Policies & Procedures"
'Policies & Procedures'
"'Policies & Procedures'"

我用来比较字符串的代码是:

The code I am using to compare the strings is:

if ($term1 -eq $term2) {
  do something
}

目视检查字符串-它们是相同的,但是if语句永远不会评估为true.有没有一种方法可以比较这两个字符串,使它的评估结果为true?

Inspecting the strings visually - they are identical, however the if statement never evaluates to true. Is there a way to compare these two strings so that it does evaluate to true?

编辑

我在其中进行字符串比较的上下文是在SharePoint网站的分类中查找术语名称.这是我正在使用的代码:

The context in which I am doing this string compare is looking for a term name in a taxonomy for a SharePoint site. Here is the code I am using:

function getTerm($termName) {

  foreach($term in $global:termset.Terms) {
    $termTrimmed = $term.Name.trim()
    Write-Host "term name = $termTrimmed" -foregroundcolor cyan
    if ($termTrimmed -eq $termName) {
      return $term
    }
  }
  return null
}

我在屏幕上同时打印了term.Name和termName,它们是相同的.如果字符串中没有&"号,则此函数有效.如果有与"号,则此功能将失败.这就是我知道&"号出问题的方式.

I have printed both term.Name and termName to the screen and they are identical. If there is no ampersand in the string, this function works. If there is an ampersand this function fails. This is how I know the ampersand is the problem.

推荐答案

这是已知怪癖:

我们最喜欢和最爱的人

  • & ASCII码: 38
  • & ASCII Number: 38

冒名顶替者

  • & ASCII码: 65286
  • ASCII Number: 65286

阅读 Nick Hobbs ="=" nofollow noreferrer>这篇文章当您创建一个术语时,它会将 38 和号替换为 65286 和号.

After reading this article by Nick Hobbs, it became apparent that when you create a term it replaces the 38 ampersand with a 65286 ampersand.

如果您想与您的产品进行比较,那么这将成为一个问题原始来源(电子表格,数据库等),因为它们不再是一样.

This then becomes a problem if you want to do a comparison with your original source (spreadsheet, database, etc) as they are no longer the same.

如尼克的文章所述,您可以使用 TaxonomyItem.NormalizeName 方法来创建"Taxonomy"版本的您要比较的字符串:

As detailed in Nick’s article, you can use the TaxonomyItem.NormalizeName method to create a "Taxonomy" version of your string for comparison:

尝试一下(未经真实SharePoint测试):

Try this (not tested on real SharePoint):

function getTerm($termName)
{
  foreach($term in $global:termset.Terms) {
    $termNormalized = [Microsoft.SharePoint.Taxonomy.TaxonomyItem]::NormalizeName($term.Name)
    if ($termNormalized -eq $termName) {
      return $term
    }
  }
  return null
}

这篇关于如何在PowerShell中比较其中包含与号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 18:07