在 powershell commandlet 中使用包含引号的变量

Using variables that contain quotes in a powershell commandlet

我为此苦苦挣扎了几个小时,我尝试 Google 但使用双引号、Invoke-Expression 或带有 @ 的东西没有帮助。

$SrcLoc = ''
$VMachine = 'computer'
$Paths = @()
$Paths = ('\c$\Users\', '\c$\Program Files\', '\c$\Program Files (x86)\')

foreach ($path in $Paths){
    $SrcLoc += '"\' + $VMachine + $path + '" ,' 
}
$SrcLoc = $SrcLoc.Substring(0,$SrcLoc.Length-2)
#$CREDENTIALED_SECTION = @{Username=$SrcLoc}
Write-Host $SrcLoc
#Invoke-Expression $SrcLoc
Get-ChildItem $SrcLoc -filter "*google*"  -Directory -Recurse -force  | % { $_.fullname }

结果是:

PS C:\Users\admin> C:\Users\admin\Desktop\New folder (3)\chrome2.ps1
"\computer\c$\Users\" ,"\computer\c$\Program Files\" ,"\computer\c$\Program Files (x86)\" 
\computer\c$\Users\ 
\computer\c$\Program Files\ 
\computer\c$\Program Files (x86)\ 

Get-ChildItem : Illegal characters in path. At C:\Users\admin\Desktop\New folder (3)\chrome2.ps1:13 char:1
+ Get-ChildItem $SrcLoc -filter "*google*"  -Directory -Recurse -force  | % { $_.f ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.GetChildItemCommand

请指教 谢谢

我只是移动了一些东西并稍微清理了语法,它工作正常:)

事实证明,您可以忘记所有那些花哨的格式,让自己更轻松地完成这项工作,所以在您提出 $SrlLoc 的行中,只需将该语句移至ForEach 循环并在那里获取目录内容。不需要多个步骤,也不需要构建一个空数组来向其中添加项目(这就是你对 $srcLoc = @() 所做的)

$VMachine = 'computer'
$Paths = ('c$\Users\', 'c$\Program Files\', 'c$\Program Files (x86)\')

foreach ($path in $Paths){
   $SrcLoc = "\$VMachine$path"
   Write-Output "Searching $srcloc"
   Get-ChildItem $SrcLoc -filter "*google*" -Directory -Recurse -ea SilentlyContinue | 
     select -ExpandProperty FullName
}

我将您的 Get-ChildItem 命令移到了 ForEach 循环中,以使事情更清晰、更容易理解。至于变量串联的语法,我真的建议人们避开 $something = "sometext" + $SomeObject + (Some-Command).Output,当你要求 PowerShell 像这样把东西混在一起时,你是在乞求错误。

代码的输出是这样的。

Searching \behemoth\c$\Users\
\behemoth\c$\Users\Stephen\Dropbox\My Code\SCCMBackup\Google Earth
Searching \behemoth\c$\Program Files\
Searching \behemoth\c$\Program Files (x86)\
\behemoth\c$\Program Files (x86)\Google
\behemoth\c$\Program Files (x86)\Microsoft SDKs\Microsoft Azure\Mobile Services.0\Packages\Microsoft.Owin.Security.Google.2.1.0
\behemoth\c$\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-4ccd2ca\Services.bundle\Contents\Service Sets\com.plexapp.plugins.googledrive
\behemoth\c$\Program Files (x86)\Plex\Plex Media Server\Resources\Plug-ins-4ccd2ca\Services.bundle\Contents\Service Sets\com.plexapp.plugins.googledrive\URL\Google Drive
\behemoth\c$\Program Files (x86)\TechSmith\Camtasia Studio 8\GoogleDrive

我将 -ErrorAction SilentlyContinue 添加到 Get-ChildItem 中,因为您会 运行 遇到权限问题,试图远程查看受保护的目录。使用 -Ea SilentlyContinue 可以抑制这些错误。