gc "C:\folder1\folder2\MyService.exe.config"
一切都很好
gwmi win32_service|?{$_.name -match "MyService"} | % {$_.pathname}
"C:\folder1\folder2\MyService.exe.config"
返回正确的路径
gwmi win32_service|?{$_.name -match "Mailing"} | % {$_.pathname} | % {$_.gettype()}
返回类型绝对是一个字符串
gwmi win32_service|?{$_.name -match "Mailing"} | % {$_.pathname} | % {gc -path $_}
gc : Cannot find drive. A drive with the name '"C' does not exist.
At line:1 char:71
+ gwmi win32_service|?{$_.name -match "MyService"} | % {$_.pathname} | % {gc -path $ ...
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ("C:String) [Get-Content], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand
我在这里缺少什么?
答案 0 :(得分:3)
仔细查看错误消息:
A drive with the name '"C' does not exist.
^
请注意驱动器号前面的"
。
从WMI查询返回的路径在双引号之间,即双引号不是分隔字符串,就像在第一个语句中一样,但是字符串的一部分 ,因此Get-Content
失败,因为找不到驱动器"C:
。
演示:
PS C:\> $path = "C:\temp\web.config"
PS C:\> $path
C:\temp\web.config
PS C:\> Get-Content $path
...
PS C:\> $path = '"C:\temp\web.config"'
PS C:\> $path
"C:\temp\web.config"
PS C:\> Get-Content $path
Get-Content : Cannot find drive. A drive with the name '"C' does not exist.
At line:1 char:1
+ Get-Content $path
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: ("C:String) [Get-Content], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand
从字符串的开头和结尾删除双引号,问题将消失:
Get-WmiObject Win32_Service |
? { $_.Name -match "Mailing" } |
% { $_.PathName -replace '^"(.*)"$', '$1' } |
% { Get-Content -Path $_ }