當運行Start-Process并-ArgumentList傳遞字串陣列$configArgs時,它有一個字串,其中包含一個特殊字符,即管道 ( |)。管道字符來自最后一個用 .$passwordtemp添加的變數--windowsLogonPassword。
由于管道字符,我收到以下錯誤訊息,
“檔案名、目錄名或卷標語法不正確。”
有什么想法可以避免這種情況嗎?
[CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = "NoVersion")]
param(
[parameter(Mandatory = $false)]
[string]$AgentDirectory = [IO.Path]::Combine($env:USERPROFILE, "VSTSAgents"),
[parameter(Mandatory = $false)]
[string]$Work,
[parameter(Mandatory = $false)]
[string]$Name = [System.Environment]::MachineName "-$(Get-Random)",
[parameter(Mandatory = $false)]
[string]$Pool = 'Default',
[parameter(Mandatory = $true)]
[string]$PAT,
[parameter(Mandatory = $true)]
[uri]$ServerUrl,
[parameter(Mandatory = $false)]
[switch]$Replace,
[parameter(Mandatory = $false)]
[pscredential]$LogonCredential,
[parameter(Mandatory = $false)]
[string]$Cache = [io.Path]::Combine($env:USERPROFILE, ".vstsagents")
)
if ($PSVersionTable.Platform -and $PSVersionTable.Platform -ne 'Win32NT') {
throw "Not Implemented: Support for $($PSVersionTable.Platform), contributions welcome."
}
if ( $Verbose ) { $VerbosePreference = 'Continue' }
$existing = Get-VSTSAgent -AgentDirectory $AgentDirectory -NameFilter $Name
if ( $existing ) {
if ($Replace) {
Uninstall-VSTSAgent -NameFilter $Name -AgentDirectory $AgentDirectory -PAT $PAT -ErrorAction Stop
}
else { throw "Agent $Name already exists in $AgentDirectory" }
}
$findArgs = @{ 'Platform' = 'win' }
if ( $MinimumVersion ) { $findArgs['MinimumVersion'] = $MinimumVersion }
if ( $MaximumVersion ) { $findArgs['MaximumVersion'] = $MaximumVersion }
if ( $RequiredVersion ) { $findArgs['RequiredVersion'] = $RequiredVersion }
$agent = Find-VSTSAgent @findArgs | Sort-Object -Descending -Property Version | Select-Object -First 1
if ( -not $agent ) { throw "Could not find agent matching requirements." }
Write-Verbose "Installing agent at $($agent.Uri)"
$fileName = $agent.Uri.Segments[$agent.Uri.Segments.Length - 1]
$destPath = [IO.Path]::Combine($Cache, "$($agent.Version)\$fileName")
if ( -not (Test-Path $destPath) ) {
$destDirectory = [io.path]::GetDirectoryName($destPath)
if (!(Test-Path $destDirectory -PathType Container)) {
New-Item "$destDirectory" -ItemType Directory | Out-Null
}
Write-Verbose "Downloading agent from $($agent.Uri)"
try { Start-BitsTransfer -Source $agent.Uri -Destination $destPath }
catch { throw "Downloading $($agent.Uri) failed: $_" }
}
else { Write-Verbose "Skipping download as $destPath already exists." }
$agentFolder = [io.path]::Combine($AgentDirectory, $Name)
Write-Verbose "Unzipping $destPath to $agentFolder"
if ( $PSVersionTable.PSVersion.Major -le 5 ) {
Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop
}
[System.IO.Compression.ZipFile]::ExtractToDirectory($destPath, $agentFolder)
$configPath = [io.path]::combine($agentFolder, 'config.cmd')
$configPath = Get-ChildItem $configPath -ErrorAction SilentlyContinue
if ( -not $configPath ) { throw "Agent $agentFolder is missing config.cmd" }
[string[]]$configArgs = @('--unattended', '--url', "$ServerUrl", '--auth', `
'pat', '--pool', "$Pool", '--agent', "$Name", '--runAsService')
if ( $Replace ) { $configArgs = '--replace' }
if ( $LogonCredential ) { $configArgs = '--windowsLogonAccount', $LogonCredential.UserName }
if ( $Work ) { $configArgs = '--work', $Work }
if ( -not $PSCmdlet.ShouldProcess("$configPath $configArgs", "Start-Process") ) { return }
$token = [System.Net.NetworkCredential]::new($null, $PAT).Password
$configArgs = '--token', $token
if ( $LogonCredential ) {
$passwordtemp = [System.Net.NetworkCredential]::new($null, $LogonCredential.Password).Password
$configArgs = '--windowsLogonPassword', $passwordtemp
}
$outFile = [io.path]::Combine($agentFolder, "out.log")
$errorFile = [io.path]::Combine($agentFolder, "error.log")
Write-Verbose "Registering $Name to $Pool at $ServerUrl"
Start-Process $configPath -ArgumentList $configArgs -NoNewWindow -Wait `
-RedirectStandardOutput $outFile -RedirectStandardError $errorFile -ErrorAction Stop
if (Test-Path $errorFile) {
Get-Content $errorFile | Write-Error
}
uj5u.com熱心網友回復:
有兩個因素在起作用:
不幸的是,一個長期存在的錯誤需要在包含空格的引數周圍使用嵌入式雙引號,例如- 請參閱此答案。
Start-Process-ArgumentList '-foo', '"bar baz"'呼叫批處理檔案 (
.cmd) 時,命令列被不恰當地決議,就好像它是從內部cmd.exe提交的一樣cmd.exe,需要包含cmd.exe元字符的無空格引數,例如|雙引號或單獨的元字符^-逃脫了。
您可以手動補償這些行為,如下所示:
$configArgsEscaped =
switch -Regex ($configArgs) {
'[ ^&|<>",;=()]' { '"{0}"' -f ($_ -replace '"', '""') }
default { $_ } # no double-quoting needed
}
現在使用-ArgumentList $configArgsEscaped代替-ArgumentList $configArgs你的Start-Process電話。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478628.html
上一篇:從字串中獲取2個字符之間的值
下一篇:PowerShell變數值不同
