Iterate through PSOObject - amazon-web-services

I am writing a script where Block Devices attached to a EC2 instance are matched and then a corresponding tag is set.
I have following PSOObject and visualization in the console
New-Object PSObject -Property #{
Disk = $Disk;
Partitions = $Partitions;
DriveLetter = If ($DriveLetter -eq $null) { "N/A" } Else { $DriveLetter };
EbsVolumeId = If ($EbsVolumeID -eq $null) { "N/A" } Else { $EbsVolumeID };
Device = If ($BlockDeviceName -eq $null) { "N/A" } Else { $BlockDeviceName };
VirtualDevice = If ($VirtualDevice -eq $null) { "N/A" } Else { $VirtualDevice };
VolumeName = If ($VolumeName -eq $null) { "N/A" } Else { $VolumeName };
}
} | Sort-Object Disk | Format-Table -AutoSize -Property Disk, Partitions, DriveLetter, EbsVolumeId, Device, VirtualDevice, VolumeName
Now I have following simple New-EC2tag command tagging the instance.
New-EC2Tag -Resource $InstanceId -Tags #{ Key = $DriveLetter; Value = $BlockDeviceName}
Basically it just writes the C: Drive and I believe I have to iterate through the PSObject to basically also set the corresponding drives.
I would bge grateful for any help.

Related

Export data from SP 2013 list to SQL database with comment versions

I'm trying to figure out a way to get comments from all item versions into one column in a sql table and view, but still unsuccessful.
I have listed the script I wrote below, but I can't add comments to it. Second script is light foreach loop which get comments history and add in new column in item, but this is not good solution if you have more than 10 000 items in SharePoint 2013 list.
Add-pssnapin microsoft.sharepoint.powershell
cls;
# env settings
#$env = "https://sharepoint.com/"
#$sqlConnectionString = "Server=servername\servername;Database=Database;User Id=UserID;Password=UserPassword;Timeout=15"
# settings
$webUrl = "$env"
$fromListUrl = "Lists/Name"
$fromViewName = "Sharepoint list view"
$targetTableName = "Target SQL table"
$targetViewName = "Target SQL View"
$targetPrimaryKey = "DBID"
$sourcePrimaryKey = "ID"
# script internal settings
$sqlDropTable = "DROP TABLE IF EXISTS [dbo].[{TABLENAME}]"
$sqlCreateTable = "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{TABLENAME}]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].[{TABLENAME}]( [{PRIMARYKEY}] [int] IDENTITY(1,1) NOT NULL, CONSTRAINT [PK_{TABLENAME}_{PRIMARYKEY}] PRIMARY KEY CLUSTERED ([{PRIMARYKEY}] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] END"
$sqlCreateColumn = "IF COL_LENGTH('{TABLENAME}', '{COLUMN}') IS NULL BEGIN ALTER TABLE [dbo].[{TABLENAME}] ADD [{COLUMN}] {TYPE} END "
$sqlSelect = "SELECT $targetPrimaryKey,$sourcePrimaryKey FROM [dbo].[$targetTableName]"
$sqlInsert = "INSERT INTO [dbo].[$targetTableName]({COLUMNS}) VALUES ({VALUES})"
$sqlUpdate = "UPDATE [dbo].[$targetTableName] SET {COLUMNVALUES} WHERE [$sourcePrimaryKey] = {IDVALUE}"
$sqlCreateView = "IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[{VIEWNAME}]')) EXEC dbo.sp_executesql #statement = N'CREATE VIEW [dbo].[{VIEWNAME}] AS SELECT {COLUMNS} FROM [dbo].[{TABLENAME}]' "
$sqlDropView = "DROP VIEW IF EXISTS [dbo].[{VIEWNAME}]"
$commit = $true # false to dont make changes in shp (folders creation, files upload, log items)
$recreate = $false # true will erase target table and create new
# script variables
$wasError = $false # flag to see if script encountered any error
$connection = $null
function GetColumnFromField($field, $row)
{
$name = $field.InternalName
if([string]::IsNullOrEmpty($fieldTitle))
{
$name = $field.InternalName
}
if(($field.Type -eq "User" -or $field.Type -eq "Lookup") -and $field.hidden -eq $false)
{
$value1 = [DBNull]::Value
$value2 = [DBNull]::Value
if($row -ne $null)
{
$value = $row[$field.internalname]
if([string]::IsNullOrEmpty($value) -eq $false)
{
try
{
$lookup = New-Object Microsoft.SharePoint.SPFieldLookupValue($value)
$value1 = $lookup.LookupId
$value2 = $lookup.LookupValue
if ($value1 -eq $null) { $value1 = 0 }
if ($value2 -eq $null) { $value2 = [DBNull]::Value }
}
catch
{
$value1 = 0
$value2 = $value
}
}
}
$cols = #()
$cols += ,#("$($name)_ID", "int", $value1, "$($field.Title) ID")
$cols += ,#("$($name)_Value", "nvarchar(255)", $value2, "$($field.Title)")
return ,$cols
}
$type = "NVARCHAR(MAX)"
if($field.Type -eq "Integer" -or $field.Type -eq "Counter")
{
$type = "int"
}
elseif($field.Type -eq "Number")
{
$type = "float"
}
elseif($field.Type -eq "DateTime")
{
$type = "datetime"
}
elseif($field.Type -eq "Boolean")
{
$type = "bit"
}
elseif($field.Type -eq "Guid")
{
$type = "uniqueidentifier"
}
elseif($field.Type -eq "Text" -or $field.Type -eq "Choice")
{
$type = "nvarchar(255)"
}
elseif($field.Type -eq "Note")
{
$type = "nvarchar(MAX)"
}
$value = [DBNull]::Value
if($row -ne $null -and $row[$field.internalname] -ne $null)
{
if($field.Type -eq "Integer")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Number")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "DateTime")
{
$value = [System.DateTime]$row[$field.internalname]
}
elseif($field.Type -eq "Boolean")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Guid")
{
$value = $row[$field.internalname]
}
elseif($field.Type -eq "Text")
{
$value = $row[$field.internalname].tostring()
}
elseif($field.Type -eq "Note")
{
$value = $row[$field.internalname].tostring()
}
else
{
$value = $row[$field.internalname].tostring()
}
if ($value -eq $null) { $value = [DBNull]::Value }
}
$cols = #()
$cols += ,#($name,$type,$value,"$($field.Title)")
return ,$cols
}
try
{
# connect to shp
write-host "Started $([DateTime]::Now.ToString()), web: $webUrl, listurl: $fromListUrl, view: $fromViewName, target: $targetTableName"
$web = get-spweb $webUrl
$list = $web.getlist($fromListUrl)
$view = $list.views[$fromViewName]
if (!$?) {throw "Could not open SHP connections."}
write-host "Connected to SHP list: $($list.title)"
# connect to sql
$connection = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString
$connection.Open()
if (!$?) {throw "Could not open SQL connections."}
write-host "Connected to SQL db: $($connection.Database)"
# recreate target table
if($recreate -eq $true)
{
$dropTableQuery = $sqlDropTable.replace("{TABLENAME}",$targetTableName)
$dropTableCommand = New-Object System.Data.SqlClient.SqlCommand $dropTableQuery, $connection
if($commit)
{
$dropTableCommand.ExecuteScalar()
}
$dropViewQuery = $sqlDropView.replace("{VIEWNAME}",$targetViewName)
$dropViewCommand = New-Object System.Data.SqlClient.SqlCommand $dropViewQuery, $connection
if($commit)
{
$dropViewCommand.ExecuteScalar()
}
}
# ensure target table
$syncTableQuery = $sqlCreateTable.replace("{TABLENAME}",$targetTableName).replace("{PRIMARYKEY}",$targetPrimaryKey)
$syncTableCommand = New-Object System.Data.SqlClient.SqlCommand $syncTableQuery, $connection
if($commit)
{
$syncTableCommand.ExecuteScalar()
}
# ensure sql table columns
$viewColumns = ""
$syncColumnsQuery = $sqlCreateColumn.replace("{TABLENAME}",$targetTableName).replace("{COLUMN}", $sourcePrimaryKey).replace("{TYPE}", "int")
for($c = 0; $c -lt $view.viewfields.count; $c++)
{
$field = $list.fields.getfieldbyinternalname($view.viewfields[$c])
$columns = GetColumnFromField -field $field -row $null
foreach($column in $columns)
{
if($column.internalname -eq "ID")
{
continue
}
write-host "Ensuring column: $($column[0]) - $($column[1])"
$syncColumnsQuery += $sqlCreateColumn.replace("{TABLENAME}",$targetTableName).replace("{COLUMN}", $column[0]).replace("{TYPE}", $column[1])
$viewColumns += "[$($column[0])] as [$($column[3])],"
}
}
$syncColumnsCommand = New-Object System.Data.SqlClient.SqlCommand $syncColumnsQuery, $connection
if($commit)
{
$syncColumnsCommand.ExecuteScalar()
}
write-host "Sql columns ensured"
# ensure sql view
if($false)
{
$createViewQuery = $sqlCreateView.replace("{TABLENAME}",$targetTableName).replace("{VIEWNAME}",$targetViewName).replace("{COLUMNS}", $viewColumns.trimend(','))
$createViewCommand = New-Object System.Data.SqlClient.SqlCommand $createViewQuery, $connection
if($commit)
{
$createViewCommand.ExecuteScalar()
}
}
# read data from sql
$imported = new-object System.Collections.Hashtable
$selectCommandQuery = $sqlSelect
$selectCommand = New-Object System.Data.SqlClient.SqlCommand $selectCommandQuery, $connection
$dr = $selectCommand.ExecuteReader()
if ($dr.HasRows)
{
while ($dr.Read())
{
$key = $dr[$sourcePrimaryKey]
$value = $dr[$targetPrimaryKey]
if($imported.containskey($key) -eq $false)
{
$imported.add($key,$value)
}
}
}
$dr.close()
write-host "Loaded already imported rows: $($imported.count)"
# read data from list
$query = new-object microsoft.sharepoint.spquery
$query.query = $view.Query
$query.ViewAttributes = "Scope='Recursive'";
#$query.RowLimit = 40
$data = $list.getitems($query)
write-host "Loaded sharepoint list items: $($data.count)"
write-host "Processing items count: $($data.count)"
foreach($row in $data)
{
$key = $row[$sourcePrimaryKey]
Write-host "Processing item: $key... " -nonewline
if($imported.containskey($key))
{
Write-host "Row found Sql ID: $($imported[$key])... " -for yellow -nonewline
# generate update query
$updateColumnValues = ""
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
#write-host "Updating value: $($column[0]) - $($column[1]) => $($column[2])"
$updateColumnValues += "[" + $column[0] + "] = #" + $column[0] + ","
}
}
Write-host "UpdateQuery generated... " -nonewline -for green
# execute insert query
$updateCommandQuery = $sqlUpdate.replace("{COLUMNVALUES}", $updateColumnValues.TrimEnd(',')).replace("{IDVALUE}", $key)
$updateCommand = New-Object System.Data.SqlClient.SqlCommand $updateCommandQuery, $connection
# add values to parameters
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
$param = $updateCommand.Parameters.AddWithValue("#" + $column[0], $column[2])
}
}
if($commit)
{
$updateCommand.ExecuteScalar()
}
Write-host "UpdateQuery executed" -for green
}
else
{
# generate insert query with parameters
$insertCommand_Part1 = "[" + $sourcePrimaryKey + "],"
$insertCommand_Part2 = $row[$sourcePrimaryKey].tostring() + ","
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
#write-host "Setting value: $($column[0]) - $($column[1]) => $($column[2])"
$insertCommand_Part1 += "[" + $column[0] + "],"
$insertCommand_Part2 += "#" + $column[0] + ","
}
}
Write-host "InsertQuery generated... " -nonewline -for green
# execute insert query
$insertCommandQuery = $sqlInsert.replace("{COLUMNS}", $insertCommand_Part1.TrimEnd(',')).replace("{VALUES}", $insertCommand_Part2.TrimEnd(','))
$insertCommand = New-Object System.Data.SqlClient.SqlCommand $insertCommandQuery, $connection
# add values to parameters
foreach($fieldInternalName in $view.viewfields)
{
if($fieldInternalName -eq "ID")
{
continue
}
$field = $list.fields.getfieldbyinternalname($fieldInternalName)
$columns = GetColumnFromField -field $field -row $row
foreach($column in $columns)
{
$param = $insertCommand.Parameters.AddWithValue("#" + $column[0], $column[2])
}
}
if($commit)
{
$insertCommand.ExecuteScalar()
}
Write-host "InsertQuery executed" -for green
}
}
}
catch
{
$wasError = $true
write-host "error occured" -for red
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error: $($_.Exception.Message) in script: $($_.fullname)"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error details: $($_.Exception.tostring())"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error stack: $($_.ScriptStackTrace)"
write-host "$([system.datetime]::now.tostring(""yyyy.MM.dd_HH.mm.ss.ffff"")) - error position: $($_.invocationinfo.positionmessage)"
}
if($connection -ne $null)
{
$connection.close()
}
if($wasError)
{
write-host "Script encountered error" -for red
}
else
{
write-host "No error occured" -for green
}
write-host "Finished $([DateTime]::Now.ToString())"
Foreach loop to get item versions and comments ->
foreach($item in $items){
foreach($version in $item.Versions)
{
if($item["ID"] -eq $($item.id)){
#$VersionData = "$($version['Odpoved'])"
if($VersionData -ne $null){
if($item['Export_Odpoved'] -ne $version['Odpoved']){
#write-host $version['Odpoved']
#write-host $VersionData.ToString();
$item["Export_Odpoved"] += $version['Odpoved']
#write-host $item["Export_Odpoved"]
$item.SystemUpdate()
write-host $item["ID"] "updated" -ForegroundColor Green
#write-host #$VersionData "||" $item["ID"] "updated" -ForegroundColor Green
} else{write-host "preskakujem ziadost, nakolko je korektne zmigrovana" $item["ID"] -ForegroundColor Yellow}
};
};
};
};
Any suggestions to make it work ? Thanks

Powershell parsing parsing error ".*\((?KB\d{6,7})\)" - Unrecognized grouping construct

Hi I'm trying to play with windows updates with PowerShell script, the script works fine but before results it through parsing error.
my script
$Session = New-Object -ComObject Microsoft.Update.Session
$Searcher = $Session.CreateUpdateSearcher()
$HistoryCount = $Searcher.GetTotalHistoryCount()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa386532%28v=vs.85%29.aspx
$Searcher.QueryHistory(0,$HistoryCount) | ForEach-Object -Process {
$Title = $null
if($_.Title -match "\(KB\d{6,7}\)"){
# Split returns an array of strings
$Title = ($_.Title -split '.*\((?KB\d{6,7})\)')[1]
}else{
$Title = $_.Title
}
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa387095%28v=vs.85%29.aspx
$Result = $null
Switch ($_.ResultCode)
{
0 { $Result = 'NotStarted'}
1 { $Result = 'InProgress' }
2 { $Result = 'Succeeded' }
3 { $Result = 'SucceededWithErrors' }
4 { $Result = 'Failed' }
5 { $Result = 'Aborted' }
default { $Result = $_ }
}
New-Object -TypeName PSObject -Property #{
InstalledOn = Get-Date -Date $_.Date;
Title = $Title;
Name = $_.Title;
Status = $Result
}
} | Sort-Object -Descending:$true -Property nInstalledO |
Select-Object -Property * -ExcludeProperty Name | Format-Table -AutoSize -Wrap
above script works fine but before results it shows some parsing error at line
error:
parsing ".*\((?KB\d{6,7})\)" - Unrecognized grouping construct.
At B:\Clients\SirAhmad\check-updates-history.ps1:9 char:9
+ $Title = ($_.Title -split '.*\((?KB\d{6,7})\)')[1]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
at line
$Title = ($_.Title -split '.*\((?KB\d{6,7})\)')[1]
Looks regx issues.
Can someone help me out to indicate what is the issue with regix?

Add DOMAIN\Domain Admins group as Full Access to the orphaned Home Directory?

The below script was created by the great https://stackoverflow.com/users/9898643/theo to list all orphaned HomeDirectory:
$ServerHomeDirShare = "\\FileServer\HomeDir$"
$filter = "(Enabled -eq 'true')"
# get all user accounts from AD; only SamAccountName required
$users = Get-ADUser -Filter $filter | Select-Object -ExpandProperty SamAccountName
Get-ChildItem -Path $ServerHomeDirShare -Directory |
Where-Object { $users -notcontains ($_.Name -replace '^(\w+\.\w+).*', '$1') } |
Select-Object -Property Name, FullName,
#{ n = 'LastAccessTime'; e = { $_.LastAccessTime.ToString('yyyy-MM-dd HH:mm:ss') } },
#{ n = "Directory Size (MB)"; e = {
Try {
$Size = (Get-ChildItem -Path $_.FullName -Recurse -ErrorAction Stop |
Measure-Object Length -Sum).Sum / 1MB
[math]::Round($Size, 2)
}
Catch {
"ERROR: $($_.Exception.Message)"
}
}
} |
Export-Csv -NoTypeInformation -Path C:\UserProfilesNotExist-Size.csv
However, there is one more issue that needed fixing, to add DOMAIN\Domain Admins AD group as Full Access to the directory ACL, BUT ONLY when the directory is not accessible or throwing error.
$FullAccessADGroup = "DOMAIN\Domain Admins"
function Take-Ownership
{
param (
[String]$Folder
)
takeown.exe /A /F $Folder
$CurrentACL = Get-Acl $Folder
write-host "`n`t...Adding NT Authority\SYSTEM to $Folder" -ForegroundColor Yellow
$SystemACLPermission = "NT AUTHORITY\SYSTEM", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
$SystemAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $SystemACLPermission
$CurrentACL.AddAccessRule($SystemAccessRule)
write-host "`t...Adding Infrastructure Services to $Folder" -ForegroundColor Yellow
$AdminACLPermission = $FullAccessADGroup, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
$SystemAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $AdminACLPermission
$CurrentACL.AddAccessRule($SystemAccessRule)
Set-Acl -Path $Folder -AclObject $CurrentACL
}
function Test-Folder($FolderToTest) {
$error.Clear()
$ErrorArray = #()
Get-ChildItem $FolderToTest -Recurse -ErrorAction SilentlyContinue | Select-Object FullName
if ($error) {
$ErrorArray = $error + $ErrorArray
foreach ($err in $ErrorArray) {
if ($err.FullyQualifiedErrorId -eq "DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand") {
Write-Host Unable to access $err.TargetObject -ForegroundColor Red
Write-Host Attempting to take ownership of $err.TargetObject -ForegroundColor Yellow
Take-Ownership($err.TargetObject)
Test-Folder($err.TargetObject)
}
}
}
}
Test-Folder $source
Because even though I am using DOMAIN\Administrator account to execute the script above, I cannot get the directory size or even opened the directory via the UNCPath, this is the error:
ERROR: Access to the path '\\FileServer\HomeDir$\Jane.Liz.V2' is denied.
ERROR: Access to the path '\\FileServer\HomeDir$\Lisa.Chan.V5' is denied.
ERROR: Access to the path '\\FileServer\HomeDir$\Carolline.Marce.V6' is denied.
...

Can't check ArchiveStatus for mailbox

I am building a script that'll check if ArchiveStatus for an Office 365 mailbox is active or not. I am able to pull the data, but my if/else statement doesn't seem to work. This is what I have so far:
$Data = Get-Mailbox -Identity "MailboxName" | ft name,*Archive*
$Data
if ($_.ArchiveStatus -eq $true) {
Write-Host "Archive Enabled"
} else{
Write-Host "Archiving Disabled"
}
No matter what mailbox I search up, the result is always "Archiving Disabled" even if the console shows user enabled.
The current object variable ($_) is only available in a pipeline context. Your if statement is outside a pipeline, so $_ doesn't exist, meaning that $_.ArchiveStatus evaluates to $null, which is interpreted as $false in the comparison.
Change this:
$Data = Get-Mailbox -Identity "MailboxName" | ft name,*Archive*
$Data
if ($_.ArchiveStatus -eq $true) {
Write-Host "Archive Enabled"
} else {
Write-Host "Archiving Disabled"
}
into this:
$Data = Get-Mailbox -Identity "MailboxName"
$Data | ft name,*Archive*
if ($Data.ArchiveStatus -eq $true) {
Write-Host "Archive Enabled"
} else {
Write-Host "Archiving Disabled"
}
and the problem should disappear.
So I was able to figure it out with help from #Ansgar Wiechers. The -eq $true wasn't working because it was either Active or None. When i created the variable for this it worked. The working code is below:
$Data = Get-Mailbox -Identity "MailboxName"
$Data | ft name, ArchiveStatus
$Status = "Active"
if($Data.ArchiveStatus -eq $Status) {
Write-Host "Archive Enabled"
} Else {
Write-Host "Archiving Disabled"
}
Thank you for your help!!

how can we unpublish item with its subitem for one particular language in sitecore?

we have option in ribbon publish - > change but that is not unpublishing subitems .
how can we unpublish item with its subitem for one particular language in sitecore ?
Thanks
Approach 1:
In the Publish ribbon, click the Change button and UNCHECK Publishable on the Item tab. Now delete the parent item with sub-items and the item will be removed from the published DB. Next go back to the item and CHECK Publishable, then publish the item only in the language you want.
Approach 2:
Use the database selector in the Sitecore shell (bottom right corner) and select your publishing target DB (e.g. "web"). GO into that tree, find the item in the language and delete that version. After that you'll need to go to your public site's cache page and clear that cache manually: http://host/sitecore/admin/cache.aspx
Approach 3:
Delete the item in the master DB, publish the parent, restore it form the recycle bin, publish it again live but not in the language you don't want.
some script is also fine :)
just publish site after use it
function GetItemDatasources {
[CmdletBinding()]
param([Item]$Item)
# grab all datasources that are not header and footer elements
return Get-Rendering -Item $item -FinalLayout -Device (Get-LayoutDevice -Default) |
Where-Object { -not [string]::IsNullOrEmpty($_.Datasource)} |
Where-Object { $_.Placeholder -ne 'Above Page Content' } |
Where-Object { $_.Placeholder -ne 'Below Page Content' } |
ForEach-Object { Get-Item "$($item.Database):" -ID $_.Datasource }
# ForEach-Object { Write-Host ($_ | Format-List | Out-String) }
}
$location = get-location
$languages = Get-ChildItem "master:\sitecore\system\Languages"
$currentLanguage = [Sitecore.Context]::Language.Name
$langOptions = #{};
foreach ($lang in $languages) {
$langOptions[$lang.Name] = $lang.Name
}
$result = Read-Variable -Parameters `
#{ Name = "destinationLanguages"; Title="Language(s) for clean up "; Options=$langOptions; Editor="checklist"; },
#{ Name = "includeSubitems"; Value=$false; Title="Include Subitems"; Columns = 4;} `
-Description "Select an languages that should be cleanup" `
-Title "Cleanup Language" -Width 650 -Height 660 -OkButtonName "Proceed" -CancelButtonName "Cancel" -ShowHints
if($result -ne "ok") {
Exit
}
Write-Host "destinationLanguages = $destinationLanguages"
$items = #()
$items += Get-Item $location
# add optional subitems
if ($includeSubitems) {
$items += Get-ChildItem $location -Recurse
}
# Remove any duplicates, based on ID
$items = $items | Sort-Object -Property 'ID' -Unique
$items | ForEach-Object { Write-Host ($_.ItemPath | Sort-Object | Format-List | Out-String) }
$message = "You are about to cleanup <span style='font-weight: bold'>$($items.Count) item(s)</span> with the following options:<br>"
$message += "<br><table>"
$message += "<tr><td style='width: auto'>Languages:</td><td>$destinationLanguages</td></tr>"
$message += "<tr><td style='width: auto'>Include Subitems:</td><td>$includeSubitems</td></tr>"
$message += "</table>"
$message += "<br><p style='font-weight: bold'>Are you sure?</p>"
$proceed = Show-Confirm -Title $message
if ($proceed -ne 'yes') {
Write-Host "Canceling"
Exit
}
Write-Host "Proceeding with execution"
$items | ForEach-Object { Remove-ItemVersion -Item $_ -Language $destinationLanguages -ExcludeLanguage "en*" }
I did this
function GetItemDatasources {
[CmdletBinding()]
param([Item]$Item)
# grab all datasources that are not header and footer elements
return Get-Rendering -Item $item -FinalLayout -Device (Get-LayoutDevice -Default) |
Where-Object { -not [string]::IsNullOrEmpty($_.Datasource)} |
Where-Object { $_.Placeholder -ne 'Above Page Content' } |
Where-Object { $_.Placeholder -ne 'Below Page Content' } |
ForEach-Object { Get-Item "$($item.Database):" -ID $_.Datasource }
# ForEach-Object { Write-Host ($_ | Format-List | Out-String) }
}
$location = get-location
$languages = Get-ChildItem "master:\sitecore\system\Languages"
$currentLanguage = [Sitecore.Context]::Language.Name
$langOptions = #{};
$actions = #{};
$actions["Unpublish"] = "1";
$actions["Publish"] = "";
foreach ($lang in $languages) {
$langOptions[$lang.Name] = $lang.Name
}
$result = Read-Variable -Parameters `
#{ Name = "destinationLanguages"; Title="Language(s) for publich/unpublish"; Options=$langOptions; Editor="checklist"; },
#{ Name = "includeSubitems"; Value=$false; Title="Include Subitems"; Columns = 4;},
#{ Name = "action"; Value="1"; Title="Action"; Options=$actions; Tooltip="Unpublish: Set language as unblishded on all langauge vestions.<br>Publish: Set language as publishded on all langauge vestions."; }`
-Description "Select languages that should be proceed during updates" `
-Title "Language Publish - Unpublish" -Width 650 -Height 660 -OkButtonName "Proceed" -CancelButtonName "Cancel" -ShowHints
if($result -ne "ok") {
Exit
}
Write-Host "destinationLanguages = $destinationLanguages"
$items = #()
$items += Get-Item $location
# add optional subitems
if ($includeSubitems) {
$items += Get-ChildItem $location -Recurse
}
# Remove any duplicates, based on ID
$items = $items | Sort-Object -Property 'ID' -Unique
$items | ForEach-Object { Write-Host ($_.ItemPath | Sort-Object | Format-List | Out-String) }
$message = "You are about to publish/unpublish <span style='font-weight: bold'>$($items.Count) item(s)</span> with the following options:<br>"
$message += "<br><table>"
$message += "<tr><td style='width: auto'>Languages:</td><td>$destinationLanguages</td></tr>"
$message += "<tr><td style='width: auto'>Include Subitems:</td><td>$includeSubitems</td></tr>"
$message += "</table>"
$message += "<br><p style='font-weight: bold'>Are you sure?</p>"
$proceed = Show-Confirm -Title $message
if ($proceed -ne 'yes') {
Write-Host "Canceling"
Exit
}
Write-Host "Proceeding with execution"
$items | ForEach-Object {
$vitems = Get-Item $_.ID -Language $destinationLanguages -Version *
$vitems | ForEach-Object {
$_.Editing.BeginEdit()
$_["__Hide version"] = $action
$_.Editing.EndEdit()
}
}