湖边的白杨树

探索是一种乐趣

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

(PowerShell) 文件操作

  • Get current ps1 file's parent path
$x = Split-Path -Parent $MyInvocation.MyCommand.Definition
  •  Create a folder if it does not exist.
$myNewFolder = $x +"myTestFolder\"
if(!(Test-Path $myNewFolder))
{
new-item -path $x -name myTestFolder -type directory
}
  • Open a XML file , and get what we want.
[String]$xmlDocPath = "F:/TestData/TestXml.xml"
[String]$nodeName = "Property"

$xmlDoc = New-Object "System.Xml.XmlDocument"
$xmlDoc.Load($xmlDocPath)
$nodelist = $xmlDoc.GetElementsByTagName($nodeName);
foreach($node in $nodelist)
{ 
  # Use Attributes will throw error.
  #$namestr = $node.Attributes[0].InnerXml
  #Write-Host "$namestr" 
  $namestr = $node.GetAttribute("Value")
  Write-Host "$namestr" 
  $childnodes= $node.ChildNodes;
  foreach($childnode in $childnodes )
  {
    $textstr = $childnode.InnerXml.ToString()
    Write-Host "$textstr"
  }
}

Xml file

<?xml version="1.0" encoding="gb2312"?>
<Root>
<Property Name = "First" Value ="value">
<GUID>xxoxx</GUID>
<Tel>123456</Tel>
<Start>5.95</Start>
</Property>
<Property Name = "Second">
<GUID>xxoxx</GUID>
<Tel>123456</Tel>
<Start>5.95</Start>a
</Property>
</Root>

 

  • Get special file from a directory , and copy them into local folder
$fileName = "test123"
$fileList = Get-ChildItem -path $LogServer -Filter "$fileName*"
foreach($file in $fileList)
{
source = $LogServer+$file 
Copy-Item $source $targetFolder
Write-Host "$file"."is copied. "
}

 获取指定文件夹下的所有文件夹大小

$rootDirectory = "D:\TFS"
 
 
$colItems = (Get-ChildItem $rootDirectory  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems)
    {
        $subFolderItems = (Get-ChildItem $i.FullName -recurse | Measure-Object -property length -sum)
        $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
    }
 

 

posted on 2013-02-02 22:47  fdyang  阅读(5120)  评论(0编辑  收藏  举报