如何在PowerShell脚本中定义共享服务器文件路径以获取文件信息
解决PowerShell脚本读取共享服务器文件信息的路径问题
直接修改脚本里的Get-ChildItem(缩写gci)命令,指定共享服务器的路径即可,支持两种路径格式:
1. 基础修改版(固定共享路径)
把目标共享路径用UNC格式(\\服务器名\共享文件夹)直接传给Get-ChildItem,修改后的脚本如下:
# 替换成你的共享服务器UNC路径 $sharePath = "\\FileServer\PublicDocuments" $shell = New-Object -com shell.application Get-ChildItem -Path $sharePath | Select-Object Name, CreationTime, LastWriteTime, @{Name='Author'; Expression={ $shell.NameSpace($_.DirectoryName).ParseName($_.Name).ExtendedProperty("System.Author") }}, @{Name='Owner'; Expression={ If ($_.PSIsContainer) { $Shell.NameSpace($_.FullName).Self.ExtendedProperty("System.FileOwner") } Else { $shell.NameSpace($_.DirectoryName).ParseName($_.Name).ExtendedProperty("System.FileOwner") } }}
2. 灵活参数版(支持命令行传路径)
如果需要频繁切换目标共享路径,可以把脚本改成接受命令行参数的形式,使用更方便:
param( [Parameter(Mandatory=$true)] [string]$TargetPath # 命令行传入共享路径 ) $shell = New-Object -com shell.application Get-ChildItem -Path $TargetPath | Select-Object Name, CreationTime, LastWriteTime, @{Name='Author'; Expression={ $shell.NameSpace($_.DirectoryName).ParseName($_.Name).ExtendedProperty("System.Author") }}, @{Name='Owner'; Expression={ If ($_.PSIsContainer) { $Shell.NameSpace($_.FullName).Self.ExtendedProperty("System.FileOwner") } Else { $shell.NameSpace($_.DirectoryName).ParseName($_.Name).ExtendedProperty("System.FileOwner") } }}
执行时直接传共享路径:
.\Get-ShareFileInfo.ps1 -TargetPath "\\FileServer\ProjectFiles"
关键注意事项
- 路径格式可选:除了UNC路径,也可以先映射网络驱动器(比如
Z:\),再用盘符作为路径,映射命令示例:# 需要权限验证时用这个命令 New-PSDrive -Name Z -PSProvider FileSystem -Root "\\FileServer\SharedFiles" -Credential (Get-Credential) - 权限要求:执行脚本的账号必须拥有目标共享文件夹的读取权限,否则会报错或无法获取作者、所有者等扩展属性;
- 属性为空的情况:部分文件类型(如纯文本、普通压缩包)本身没有
System.Author属性,返回空值属于正常现象。
内容的提问来源于stack exchange,提问作者iftekharus
相关产品推荐
相关产品推荐

