powershell - 如何从带有 powershell 的链接中获取文件格式
问题描述
这是我的项目
cls
$url = Read-Host 'URL'
if ( $url -eq "")
{
exit
}
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.Forms")
function save-file([string]$initialDirectory)
{
$savefile = New-Object System.Windows.Forms.SaveFileDialog
$savefile.InitialDirectory = $initialDirectory
$savefile.Filter="All files(*.*)|*.*"
$savefile.ShowDialog() | out-null
return $savefile.FileName
}
$file=save-file ""
if ( $file -eq "")
{
exit
}
else
{
echo "User Selected $file"
}
Invoke-WebRequest -Uri "$url" -OutFile "$file"
我将总结项目的想法
使用 powershell 从浏览器下载文件的程序。
我希望文件以链接格式自动保存
有没有办法使用 powershell 或 cmd 从链接获取文件格式?
我找到了我的问题的答案(我将把这个项目放在任何人都可以从中受益)
cls
$url = Read-Host 'URL'
if ( $url -eq "")
{
exit
}
$dot = $url.Split(".")[-1]
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.Forms")
function save-file([string]$initialDirectory)
{
$savefile = New-Object System.Windows.Forms.SaveFileDialog
$savefile.InitialDirectory = $initialDirectory
$savefile.Filter="$dot file(*.$dot)|*.$dot"
$savefile.ShowDialog() | out-null
return $savefile.FileName
}
$file=save-file ""
if ( $file -eq "")
{
exit
}
else
{
echo "User Selected $file"
}
Invoke-WebRequest -Uri "$url" -OutFile "$file"
解决方案
To complement Hackoo's helpful answer with a slightly more robust version, which parses the URL (URI) via System.Uri
:
PS> ([uri] 'https://example.org/downloads/foo.exe?other=stuff').Segments[-1]
foo.exe
The advantage of this approach is that any query-string suffix in the URL is ignored, which a strictly string-based parsing approach based on .Split()
would not.
Append .Split('.')[-1]
to get just the filename extension (exe
, in the example above), as also shown in your updated question, or enclose in [System.IO.Path]::GetExtension(...)
(which would yield .exe
); in PowerShell (Core) 7+ you could also use Split-Path
-Extension
(also yields .exe
).
推荐阅读
- amazon-web-services - 如何使用 aws-cdk 在 EC2 和 RDS 之间创建 DependsOn 关系
- python - Pyspark DataFrame 循环
- python - 函数中的函数返回“TypeError:+ 的不支持的操作数类型:'int' 和 'NoneType'”
- ios - UIScene userActivity 为零
- css - 如何使用Angular关闭多个对话框
- git - 将 .gitignore 文件应用到存储库中包含单个项目的所有子文件夹的简单方法
- bash - sed 用文件中的另一个哈希替换哈希
- python - 防止在Python程序中多行输入后需要按Command+D
- java - 当我在 RecyclerView 项目中单击时,片段加载数据错误数据
- java - 检查nfc标签是否在附近