尝试将Powershell代码简化为单行

时间:2018-03-27 19:06:29

标签: powershell

以下代码片段获取路径列表,将每个路径的每个字符转换为其ASCII值并将其存储在名为$ output

的变量中
 $itemlist = (Get-ChildItem -Recurse -Path "$data_path").FullName 
 Foreach($item in $itemlist)
    { 
     $output+= [int[]]@("$item").ToCharArray() -join ',' | Out-String
    }
 Write-Host $output

我试图将所有这些都放在一行中(由于复杂的原因阻止我运行Powershell脚本)所以我可以运行一个Powershell命令来获得相同的效果但是到目前为止我有很难过

以下是我设法实现的目标。

(Get-ChildItem -Recurse -Path "$data_path").FullName | Format-Table -Property @{n='';e={[int[]]@($_).ToCharArray() -join ','}} | Out-Host

但是输出没有ASCII值,输出中的路径以字符表示。有人可以帮我解决这个问题吗?

7 个答案:

答案 0 :(得分:2)

如果您从cmd.exe运行

$Command = @'
$itemlist = (Get-ChildItem -Recurse -Path "$data_path").FullName 
Foreach($item in $itemlist)
{ 
    $output+= [int[]]@("$item").ToCharArray() -join ',' | Out-String
}
Write-Host $output
'@
[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($Command))

最终结果:

powershell.exe -NoProfile -NoLogo -EncodedCommand JABpAHQAZQBtAGwAaQBzAHQAIAA9ACAAKABHAGUAdAAtAEMAaABpAGwAZABJAHQAZQBtACAALQBSAGUAYwB1AHIAcwBlACAALQBQAGEAdABoACAAIgAkAGQAYQB0AGEAXwBwAGEAdABoACIAKQAuAEYAdQBsAGwATgBhAG0AZQAgAAoAIABGAG8AcgBlAGEAYwBoACgAJABpAHQAZQBtACAAaQBuACAAJABpAHQAZQBtAGwAaQBzAHQAKQAKACAAIAAgACAAewAgAAoAIAAgACAAIAAgACQAbwB1AHQAcAB1AHQAKwA9ACAAWwBpAG4AdABbAF0AXQBAACgAIgAkAGkAdABlAG0AIgApAC4AVABvAEMAaABhAHIAQQByAHIAYQB5ACgAKQAgAC0AagBvAGkAbgAgACcALAAnACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcACgAgACAAIAAgAH0ACgAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAkAG8AdQB0AHAAdQB0AA==

答案 1 :(得分:2)

如果这变成了一场短暂的比赛..

ls $data_path -r|%{($_|% f*|% t*y|% toi*2 $null)-join','}|out-string

答案 2 :(得分:1)

我猜你可以用这个:

(Get-ChildItem -Recurse -Path "$data_path").FullName | ForEach-Object { [int[]]@("$_").ToCharArray() -join ',' } | Out-String

答案 3 :(得分:0)

$itemlist = (Get-ChildItem -Recurse -Path "$data_path").FullName; Foreach($item in $itemlist){$output+= [int[]]@("$item").ToCharArray() -join ',' | Out-String};Write-Host $output

答案 4 :(得分:0)

Get-ChildItem -Path "$data_path" | ForEach-Object { [int[]][char[]]$_.FullName -join ',' }

Get-ChildItem -Path "$data_path" | ForEach-Object { [int[]]@($_.FullName).ToCharArray() -join ',' }

答案 5 :(得分:0)

到目前为止,使用别名是我能想到的进一步缩短它:

ls "$data_path" -r | %{[int[]]@($_.FullName).ToCharArray() -join ","} | Out-String

答案 6 :(得分:-3)

 $itemlist = (Get-ChildItem -Recurse -Path "$data_path").FullName 
 Foreach($item in $itemlist)
    { 
     $output+= [int[]]@("$item").ToCharArray() -join ',' | Out-String
    }
 Write-Host $output