(PowerShell) 文件操作

(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"

    }

 

 

你可能感兴趣的:(powershell)