Delete directory content using Azure Automation DSC - azure

I am using Azure Automation DSC to deploy some basic configurations on my Azure VMs. However, I am struggling to delete recursively all the content of C:/Temp directory and leave the directory as an empty folder.
I am using the following code:
$temp_dir = "C:\temp\"
File "Clean Temp Folder" # Delete $temp_dir Directory
{
Ensure = "Absent"
Type = "Directory"
Recurse = $true
DestinationPath = $temp_dir
Force = $true
}
As soon as I assign node configuration to the VM, C:/Temp/ folder gets deleted completely, but if I recreate it manually afterwards it won't be deleted on the next DSC run even though the Force parameter is set to true.
Any suggestions are very welcome!

I would recommend to go with Script resource or else if you want to go with File resource only then try something as shown below.
$temp_dir = "C:\temp\"
File "Clean Temp Folder" # Delete $temp_dir Directory
{
Ensure = "Absent"
Type = "Directory"
Recurse = $true
DestinationPath = $temp_dir
Force = $true
}
$temp_dir = "C:\temp\"
File "Create empty Temp Folder" # Create empty $temp_dir Directory
{
Ensure = "Present"
Type = "Directory"
DestinationPath = $temp_dir
Force = $true
}

The issue was on the Azure side. While I was registering nodes in DSC, the configuration mode was set to ApplyAndMonitor.
The bad thing is that the setting was not visible for the already registered node, but after re-registering the issue was solved.
Screenshot

Related

Trying to delete an excel worksheet and recreate it, but throws an error that the name already exists

Edit: Ended up finding out what was causing it, but unsure why this works. The fix was to add this line after the excel object was created:
$excel.DisplayAlerts = $False
I'm using PowerShell and trying to delete an existing excel worksheet and then recreate it. My environment is locked down for modules, so unfortunately I can't use ImportExcel or other similar modules. I'm a bit new to PowerShell so apologies if the code is messy, but here's what I currently have:
$TodaysDate = Get-Date -Format "yyyy-MM-dd"
# Open a new excel object
$excel = New-Object -ComObject excel.application
$excel.visible = $False
# If a workbook does not already exist, create one
# If a workbook does exist, open it.
if (-not(Test-Path -Path $ExistingExcelFile -PathType Leaf)) {
$workbook = $excel.Workbooks.Add()
# Delete the automatically generated sheet
$workbook.WorkSheets.Item("Sheet1").Delete()
} else {
$workbook = $excel.Workbooks.Open($ExistingExcelFile)
}
# If a worksheet with todays date already exists, delete it so we can start fresh
if (($TodaysDate -in $($workbook.Worksheets).Name)) {
$TodaysWrkSheet = $workbook.WorkSheets.Item($TodaysDate)
$TodaysWrkSheet.Activate()
$TodaysWrkSheet.Delete()
}
#Add the worksheet and set the name
$WrkSheet = $workbook.Worksheets.Add()
$WrkSheet.Name = $TodaysDate
# If the summary page exists, delete it so we can start fresh
if (("Summary" -in $($workbook.Worksheets).Name)) {
$SummaryWrkSheet = $workbook.WorkSheets.Item("Summary")
$SummaryWrkSheet.Activate()
$SummaryWrkSheet.Delete()
}
$SummaryPage = $workbook.Worksheets.Add()
$SummaryPage.Name = "Summary"
This is the error I get when it tries to create the new sheet with todays date:
That name is already taken. Try a different one.
The second part with the summary page works fine and it finds/deletes/recreates it, so I'm assuming it's a problem with $TodaysDate, but why? The if statement block of code for ($TodaysDate -in $($workbook.Worksheets).Name) gets hit, would there be a problem with $TodaysWrkSheet = $workbook.WorkSheets.Item($TodaysDate)? It creates the sheet just fine as long as it doesn't exist already, so it at least doesn't complain creating a sheet name with $TodaysDate. I've been trying for a while to figure out why but haven't been having any luck.
Any help is appreciated.

HP ALM - download a resource under a specific folder in the Test Resource module

We are using ALM 12. We have multiple folders in our Test Resources module, and some of the resources stored in these folders have the same name as in other folders. I am able to download a resource using the name, but can't figure out how to get a resource under a specific folder. Anyone know how to download a resource specifying the folder to download it from?
e.g
Folder1
mysheet.xls
Folder2
mysheet.xls
I want to download Folder2\mysheet.xls and not Folder1\mysheet.xls
You could download the resource by resource id rather than resource name.
Below is VBS sample (with OTA API) for your reference:
Option Explicit
Dim tdc, cust, resource
set tdc = CreateObject("TDApiOle80.TDConnection")
tdc.InitConnectionEx "http://YourALMServer:Port/qcbin"
tdc.Login "username", "password"
tdc.Connect "domainName", "projectName"
# 1001 is the resource id which you want to download.
set resource = tdc.QCResourceFactory.Item("1001")
# "C:\\tmp\\" is the local path where you want to place the downloaded resource
resource.DownloadResource "C:\\tmp\\", TRUE
tdc.Disconnect
tdc.Logout
tdc.ReleaseConnection
Option Explicit
Dim objCon, cust, resource
set objCon= CreateObject("TDApiOle80.TDConnection")
objCon.InitConnectionEx "http://YourALMServer:Port/qcbin"
objCon.Login "username", "password"
objCon.Connect "domainName", "projectName"
Set oResourceFolder = objCon.QCResourceFolderFactory
Set oFilter = oResourceFolder.Filter
oFilter.Filter("RFO_NAME") ="abc" \\ abc is your folder name
Set oList = oFilter.NewList()
set oChild = oList.item(1).QCResourceFactory.NewList("")
''assuming that there is only 1 folder with name "abc" in Test Resources section
For i =1 to oChild.count Step 1
oChild.item(i).DownloadResource "c:\\a", TRUE
''c:\\a is the location where we need to safe the resource
next
set objCon = Nothing

Sharepoint CSOM OpenBinaryDirect in Powershell, Method not found

I'm trying to use powershell and Sharepoint 2013 CSOM to copy attachments of one item to a new item in another list. I've been able to successfully generate an attachments folder for the new item, so in theory all I need to do is move the files from the old attachments folder to the new one. CopyTo and MoveTo only seem to work for moving files within a list, so I thought to use OpenBinaryDirect and SaveBinaryDirect with the site context. However, in powershell, calling either of these methods results in the following error: Method invocation failed because [System.RuntimeType] doesn't contain a method named 'OpenBinaryDirect'.
$attachments = $item.AttachmentFiles
if($attachments.Count -gt 0)
{
#Creates a temporary attachment for the new item to genereate a folder, will be deleted later.
$attCI = New-Object Microsoft.SharePoint.Client.AttachmentCreationInformation
$attCI.FileName = "TempAttach"
$enc = New-Object System.Text.ASCIIEncoding
$buffer = [byte[]] $enc.GetBytes("Temp attachment contents")
$memStream = New-Object System.IO.MemoryStream (,$buffer)
$attCI.contentStream = $memStream
$newItem.AttachmentFiles.Add($attCI)
$ctx.load($newItem)
$sourceIN = $sourceList.Title
$archIN = $archList.Title
$sourcePath = "/" + "Lists/$sourceIN/Attachments/" + $item.Id
$archPath = "/" + "Lists/$archIN/Attachments/" + $newItem.Id
$sFolder = $web.GetFolderByServerRelativeUrl($sourcePath)
$aFolder = $web.GetFolderByServerRelativeURL($archPath)
$ctx.load($sFolder)
$ctx.load($aFolder)
$ctx.ExecuteQuery()
$sFiles = $sFolder.Files
$aFiles = $aFolder.Files
$ctx.load($sFiles)
$ctx.load($aFiles)
$ctx.ExecuteQuery()
foreach($file in $sFiles)
{
$fileInfo = [Microsoft.SharePoint.Client.File].OpenBinaryDirect($ctx, $file.ServerRelativeUrl)
[Microsoft.Sharepoint.Client.File].SaveBinaryDirect($ctx, $archPath, $fileInfo.Stream, $true)
}
}
$ctx.ExecuteQuery()
Any help on either getting the BinaryDirect methods to work or just a generalized strategy for copying attachments across lists using powershell + CSOM would be greatly appreciated.
You have the wrong syntax for invoking a static method. You want [Microsoft.SharePoint.Client.File]::OpenBinaryDirect( ... )
Note the double colons syntax :: between the type name and the method name. Same for SaveBinaryDirect invocation.

Create a 'Link to a Document' in a SharePoint Shared Document List using PowerShell

I'm trying to create a link to a document in SharePoint 2010 using PowerShell 2.0. I've already enabled other content types and added the 'Link to a Document' content type to the document library in question.
The document that I'm trying to link to is in a different shared document list on another web in the same site collection. The actual file is nested in a subfolder called "PM". The file types may range from excel files to word files to PDFs.
I've tested the process manually (Shared Documents -> New Document -> Link to a Document -> ...) and it worked fine (as was indicated by the document icon with an arrow over the bottom right corner when I was done), but I cannot seem to get it to work with PowerShell. Any ideas?
This is the only non-PowerShell solution that I've come accross so far:
http://howtosharepoint.blogspot.com/2010/05/programmatically-add-link-to-document.html
I got it working finally by porting the aforementioned solution. There's superfluous detail here, but the gist of it is easy enough to parse out:
# Push file links out to weekly role page
$site = New-Object Microsoft.SharePoint.SPSite($roleURL)
$web = $site.OpenWeb()
$listName = "Shared Documents"
$list = $web.Lists[$listName]
$fileCollection = $list.RootFolder.files
ForEach ($doc in $docLoadList) {
$parsedFileName = $d.Split("\")
$index = $parsedFileName.Length
$index = $index - 1
$actualFileName = $parsedFileName[$index]
$existingFiles = Get-ExistingFileNames $homeURL
If ($existingFiles -Match $actualFileName) {
$existingFileObject = Get-ExistingFileObject $actualFileName $homeURL
$docLinkURL = Get-ExistingFileURL $actualFileName $homeURL
# Create new aspx file
$redirectFileName = $actualFileName
$redirectFileName += ".aspx"
$redirectASPX = Get-Content C:\Test\redirect.aspx
$redirectASPX = $redirectASPX -Replace "#Q#", $docLinkURL
$utf = new-object System.Text.UTF8Encoding
$newFile = $fileCollection.Add($redirectFileName, $utf.GetBytes($redirectASPX), $true)
# Update the newly added file's content type
$lct = $list.ContentTypes["Link to a Document"]
$lctID = $lct.ID
$updateFile = $list.Items | ? {$_.Name -eq $redirectFileName}
$updateFile["ContentTypeId"] = $lctID
$updateFile.SystemUpdate()
$web.Dispose()
}
}
I may end up stringing together the .aspx file in the script too at some point...

IIS 5.1: Programmatically Create Virtual Sub-Directory

Background
I'm trying to automate the creation of Virtual Directories based on the location of an existing Virtual Directory and its sub-directories.
Example:
C:\WebSites\Parent\NewVirtualDirectories
Where Parent is a Virtual Directory and NewVirtualDirectories contains any automated Virtual Directories.
Problem
Using the following Code:
Option Explicit
Dim args, strComputer, strVdirName, strVdirPath, objVdir, objIIS, objWebSite
Set args = WScript.Arguments
strComputer = "localhost"
strVdirName = args(1)
strVdirPath = args(0)
Set objIIS = GetObject("IIS://" & strComputer & "/W3SVC/1")
Set objWebSite = objIIS.GetObject("IISWebVirtualDir","Root/Parent")
Set objVdir = objWebSite.Create("IISWebVirtualDir",strVdirName)
objVdir.AccessRead = True
objVdir.Path = strVdirPath
objVdir.AppCreate (True)
objVdir.SetInfo
WScript.Quit
I can create children under Parent, but they show up Directly under the parent. I need them to be in the Sub Folder.
I get: http://localhost/Parent/NewSite
I want: http://localhost/Parent/NewVirtualDirectories/NewSite
I've tried
Set objWebSite = objIIS.GetObject("IISWebVirtualDir","Root/Parent/NewVirtualDirectories")
but NewVirtualDirectories is not a Virtual Directory (an I don't want it to be) so I get an error. I can get the desired effect when I do this manually in IIS manager, but I can't figure out how to automate it.
Any help would be greatly appreciated.
EDIT
For those who are facing similar problems, I found a great resource for VBScript-ing
http://www.cruto.com/resources/vbscript/vbscript-examples/vbscript-sitemap.asp
After doing a lot more digging (trial and error) I was able to figure it out.
By referencing the existing folder as a IISWebDirectory, I was able to select it and then create an application without creating a virtual directory.
Option Explicit
Dim args, strComputer, strVdirName, strVdirPath, objVdir, objIIS, objWebSite
Set args = WScript.Arguments
strComputer = "localhost"
strVdirName = args(1)
strVdirPath = args(0)
Set objIIS = GetObject("IIS://" & strComputer & "/W3SVC/1")
Set objVdir = objIIS.GetObject("IISWebDirectory","Root/Parent/NewVirtualDirectories/" + strVdirName)
objVdir.AccessRead = True
objVdir.AccessScript = True
objVdir.AppFriendlyName = strVdirName
objVdir.AppCreate (True)
objVdir.SetInfo
WScript.Quit

Resources