使用powershell命令行开关中包含引号的变量

时间:2015-12-22 18:58:27

标签: powershell variables command

我在这方面苦苦挣扎了几个小时,我尝试使用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

请告知 谢谢

1 个答案:

答案 0 :(得分:3)

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

事实证明,你可以忘记所有这些花哨的格式并让自己更容易,所以在你提出$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\2.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可以抑制这些错误。