gpt4 book ai didi

powershell - Get-Content 无法读取通过 WMI 检索的路径

转载 作者:行者123 更新时间:2023-12-03 00:37:32 25 4
gpt4 key购买 nike

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

我在这里缺少什么?

最佳答案

仔细查看错误消息:

A drive with the name '"C' does not exist.                       ^

Note the " in front of the drive letter.

The path returned from the WMI query is between double quotes, i.e. the double quotes are not delimiting the string as in your first statement, but are part of the string, so Get-Content fails, because it can't find a drive "C:.

Demonstration:

PS C:\> $path = "C:\temp\web.config"PS C:\> $pathC:\temp\web.configPS C:\> Get-Content $path<?xml version="1.0" encoding="utf-8" ?><configuration>...</configuration>PS C:\> $path = '"C:\temp\web.config"'PS C:\> $path"C:\temp\web.config"PS C:\> Get-Content $pathGet-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

Remove the double quotes from beginning and end of the string and the problem will disappear:

Get-WmiObject Win32_Service |
Where-Object { $_.Name -match "Mailing" } |
ForEach-Object { $_.PathName <b>-replace '^"(.*)"$', '$1'</b> } |
ForEach-Object { Get-Content -Path $_ }

关于powershell - Get-Content 无法读取通过 WMI 检索的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30371764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com