如何将列表中的文件夹名称动态包含到mailto URL中?

时间:2013-04-30 22:12:21

标签: html powershell

我有这个脚本。它扫描文件夹位置并将文件夹的名称映射到文件夹所有者的名称,该文件夹从CSV文件中提取,然后从AD获取用户电子邮件地址,并将其作为可点击的mailto:链接添加到新列。然后,这将在HTML页面的表格中输出。

经历了几次迭代,现在已经到了最后阶段。

我现在的问题是如何将文件夹名称拉入mailto正文HTML。

Import-Module ActiveDirectory

function Encode($str) {
return ( $str -replace ' ', '%20' -replace '\n', '%0A%0D' )
}

function name($filename, $folderowners, $directory, $output){
$subject = Encode("Folder Access Request")
$body = Encode("Please can I have access to the following folder $directory")
$server = hostname
$date =  Get-Date -format "dd-MMM-yyyy HH:mm"
$a = "<style>"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color:black;}"
$a = $a + "Table{background-color:#ffffff;border-collapse: collapse;}"
$a = $a + "TH{border-width:1px;padding:0px;border-style:solid;border-color:black;}"
$a = $a + "TR{border-width:1px;padding-left:5px;border-style:solid;border-color:black;}"
$a = $a + "TD{border-width:1px;padding-left:5px;border-style:solid;border-color:black;}"
$a = $a + "body{ font-family:Calibri; font-size:11pt;}"
$a = $a + "</style>"

$c = " <br></br> Content"
$c = $c +"<p>More Content</p>"
$x = ""

$b = Import-Csv $folderowners
$mappings = @{}
$b | % { $mappings.Add($_.FolderName, $_.Owner) }


       Get-ChildItem $directory | where {$_.PSIsContainer -eq $True} | select Name, Path, @{n="Owner";e={$mappings[$_.Name]}}, @{n="Email";e={"mailto:"+((Get-ADUser $mappings[$_.Name] -Properties mail).mail)}}  | sort -property Name | 
 ConvertTo-Html -head $a -PostContent $c | % {
  $body = Encode("Please can I have access to the following folder " + $_.Name)
  $_ -replace '(mailto:)([^<]*)', 
    "<a href=`"`$1`$2?subject=$subject&amp;body=$body`">`$2</a>"
} | Out-File $output
}

    name "gdrive" "\\server\departmentfolders$\location\gdrive.csv" "x:" "\\server\departmentfolders$\location\gdrive.html"

这现在出来了,在电子邮件的正文中显示路径,但不包括文件夹名称只是路径位置\ server \ departmentfolders $,这几乎只需要文件夹名称...

1 个答案:

答案 0 :(得分:0)

如果要在替换字符串中使用变量,则必须在字符串周围使用双引号而不是单引号:

$_ -replace '...', "... $directory ..."

在这种情况下,您必须转义替换字符串中的其他元素,即内部双引号和后引用($1$2)到组((...))in正则表达式:

$_ -replace '(...)(...)', "<a href=`"`$1`$2...`">..."

此外,您应该在网址中对空格(%20)和换行符(%0A%0D)进行编码。

function Encode($str) {
  return ( $str -replace ' ', '%20' -replace '\n', '%0A%0D' )
}

整件事情看起来像这样:

Import-Module ActiveDirectory

function Encode($str) {
  return ( $str -replace ' ', '%20' -replace '\n', '%0A%0D' )
}

function name($filename, $folderowners, $directory, $output) {
  $subject = Encode("Folder Access Request")

  ...

  Get-ChildItem $directory | ... |
    ConvertTo-Html -head $a -PostContent $c | % {
      if ( $_ -match '^<tr><td>([^<]*)' ) {
        $body = Encode("Please can I have access to the following folder " +
                       "{0}\{1}" -f ($directory, $matches[1]))
      }
      $_ -replace '(mailto:)([^<]*)', 
        "<a href=`"`$1`$2?subject=$subject&amp;body=$body`">`$2</a>"
    } | Out-File $output
}

...