Quantcast
Channel: PowerShell
Viewing all 15370 articles
Browse latest View live

Robocopy list of profiles powershell help pls

$
0
0

OK I have powershell creating a list of profiles accessed in the last 45 days and outputting it to a text file profiles.txt, that is working fine.

I than need to copy the profiles from that list to a nas for safe keeping during a migration project.

I tried using with it not working at all

$profiles= "profiles.txt"

c:\windows\system32\robocopy c:\users\$profiles \\nas\$env:computername\Users /mir /zb /r:0 /w:0


Remotely Modifying List of Registry Keys from List of Computers

$
0
0

Spiceheads,

I'm working on remotely modifying an autologin key value on batches of PCs at a time, and have run into a bit of a 'red tape' snag. I put together the Powershell script below for this task thinking "Sure, Powershell makes this sort of thing easy!"

Most machines in the environment either 1. Do not have Powershell, or 2. Do not have WinRM configured to accept remote management making the following script... worthless:

$admin = Read-Host "Enter domain\username"
$credential = Get-Credential -Credential $admin
$Computers = Get-Content "c:\path\file.txt"
try
	{
	Invoke-Command -ComputerName $Computers -Credential $credential -ScriptBlock {Remove-ItemProperty -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" -name AutoAdminLogon}
	}
catch
	{
	$msg = $_
	$msg
	}

Does anyone have a dusty VBScript somewhere that does the same thing? Or another idea to get the job done?

Cheers!

Powershell script proof

$
0
0

I'm having an issue with a script I've been working on. The script should first load a number of modules, then load some stored creds and connect to the Office 365/Exchange Online environment.

It then pulls a list of non disabled users from a specified OU and gives an Exchange Online mailbox Full Access rights to those user's mailboxes. Once that's done it uses the MessageOps Exchange Migrator to export the contents of the mailbox to a specified location. The output from the Exchange Migrator includes several lines of data which can be checked. If the Result from the Exchange Migrator is "Successful" then it should proceed with disabling the AD account and taking it's group memberships and putting them in the Notes field for the account and then removing the account from those groups. If it outputs something other than "Successful" for results it should write the entire output to a log file.

So far everything is working fine except for the part where the group memberships are removed. I seem to have gotten the looping wrong somewhere. It tries to remove the user from it's groups 3 times. Everything works the first time, but the following 2 times it proceeds to vomit up errors saying it's not in that group, for obvious reasons. I'm at a loss as to why it would attempt to remove the user from those groups multiple times and could use some help cleaning this up.

Any assistance would be appreciated.

#Declare export path
$ExportFolder = "\\on-fs-01\users\TerminatedUsers"
$ExportLogs = "\\on-fs-01\users\TerminatedUsers\Exportlogs\log.txt"

function clean-disabledOU
{
	Disable-ADAccount -identity $user.SAMAccountName

	# Copy group memberships to Notes field and remove group memberships
	    if ($user.memberof -ne $null) 
		{
        $notes= [string]$user.memberof
        set-qaduser $user.SamAccountName -notes $notes
        $groups= $user.memberof
		foreach ($group in $groups) {$user.memberof | remove-adgroupmember -Members $user.SAMAccountName -confirm$false}
		}
}


#Load required modules
Add-PSSnapin Quest.ActiveRoles.ADManagement
Import-Module ActiveDirectory
import-module Messageops-Migrator
import-module msonline

#Admin Credentials
$powerUser = "Account Username"
$powerPass = "Account Password"
$password = ConvertTo-SecureString $powerPass -AsPlainText -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $powerUser,$password

#Get Remote Powershell Connection 
if ((Get-PSSession | Where-Object {$_.ConfigurationName -eq "Microsoft.Exchange"}) -eq $null){
	$psCred = $creds 
	$rpRemotePowershell = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -credential $psCred  -Authentication Basic -AllowRedirection  
	$importresults = Import-PSSession $rpRemotePowershell 
}

#Create an array of users who are in a specific OU that are NOT disabled.
	$users= get-aduser -searchbase "OU=Autodisable Test,DC=medspring,DC=local" -Filter * -Properties memberof | where {$_.enabled -eq $true}

#Apply full access rights to the mailboxes to be exported to
	foreach ($user in $users) {add-mailboxpermission $user.userprincipalname -user service.account@medspring.com -accessrights fullaccess -confirm$false}

foreach ($user in $users)
	{
		$results = Export-MessageOps.ToPST -DestinationDirectory $ExportFolder -SourceMailbox $user.userprincipalname -Credential $creds -Mailbox
		echo "Export of $user.userprincipalname","$results.result"
		if ($results.result -like "Successful") {clean-disabledou}
		elseif ($results.result -notlike "Successful") {out-file $exportlogs -append}
	}


remove-pssession $rpremotepowershell

append text from same file name in several folder to a new file

$
0
0

OK this will be easy for someone just not me :-(

I have a folder called \date

it has several sub folders and each of those has a file called profiles.txt

I need to append the text from each of those files to a new file as to have a list with all the entries for each profiles.txt from each sub folder t\into one list.

I would prefer a powershell solution but any will work

Thanks

Need to add an Exclusion to a Ex2010 mailbox PS script

$
0
0

Ok.. having a bit of a Powershell mind blank.

We have a script that moves mailboxes from Exchange 2003 to Exchange 2010 on a DB level.

However we need to exclude certain users from these moves due to certain conditions and they will be picked up later on.

Anyone know of a way to get the script to check against a list and exclude those mailboxes from the move.

Here is the {basic) script:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$database = [Microsoft.VisualBasic.Interaction]::InputBox("Source Exchange 2003 Database for moves i.e. KN2-XMB-P0009\XMB0009-MIGRATIONS\XMBMG1", "$env:database")

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$targetdatabase= [Microsoft.VisualBasic.Interaction]::InputBox("Target Exchange 2010 Database for Moves i.e. KN2MBX0001-MB1", "$env:targetdatabase")

Get-Mailbox -database $database | New-MoveRequest -TargetDatabase $targetdatabase -BadItemLimit 10

Powershell script for getting folder sizes

$
0
0

Howdy:

I need a Powershell script that will tell me the sizes of each individual folder in C:\Users\Shares on my SBS2011 server. I thought Get-Item C:\Users\Shares would work, but i got nothing back for a value, so I did a Google search and found this: http://technet.microsoft.com/en-us/library/ff730945.aspx

This didn't help and the scripts did not work.

Does anyone have a simple Powershell script they could share with me that will give me the folder sizes of each individual's user folder in C:\users\shares on my server?

Thanks!

Rob

PowerShell Script Windows XP

$
0
0

So I have a powershell script setup in Group Policy to map the network drives. Which is does perfectly for windows 7 machines. Now does anyone have an advice on how to get the scripts to run on windows XP machine ? (Still using group policy)

Thanks,

Chad

upload file success or failure

$
0
0

I found another post on here about how to FTP upload some files. it's working great, but I want to have a bit more information output. Here's snippet of what I have and what I'd like to do

foreach ($file in $uploadfiles)

{

# create the full path to the file on remote server (odd but okay!)
$ftp_command = $ftp + $file

# for debugging
#$ftp_command

# create a new URI object for the full path of the file
$uri = New-Object System.URI($ftp_command)

#for debugging
#$uri

# finally do our upload to the remote server - URI object, full path to local file
$result = $ftpclient.UploadFile($uri,$file.Fullname)

if ($result) {
 $file.Fullname + " uploaded successfully"
} else {
 $file.Fullname + " not uploaded successfully"
}

}

Basically the if/else loop at the end of the foreach. I want to test for the return from the UploadFile. I'm new to PowerShell but not to programming and just having this little issue.

Thanks in advance


Backing up Event Logs with get-wmiobject

$
0
0

Hey i found a script (if you are reading an wrote this thanks)

# Config
$logFileName = "Security" # Add Name of the Logfile (System, Application, etc)
$path = "e:\seclogs\" # Add Path, needs to end with a backsplash

# do not edit
$exportFileName = "servername" + $logFileName + (get-date -f yyyyMMdd) + ".evt"
$logFile = Get-WmiObject Win32_NTEventlogFile | Where-Object {$_.logfilename -eq $logFileName}
$logile.PSBase.Scope.Options.EnablePrivileges=$True
$logFile.backupeventlog($path + $exportFileName)

I am trying to run it on a windows 2003 file server to get the security logs daily for auditing purposes. I keep getting the errors listed below:

Property 'EnablePrivileges' cannot be found on this object; make sure it exists and is settable.
At C:\ps\BackupSecurityLog.ps1:8 char:30
+ $logile.PSBase.Scope.Options. <<<< EnablePrivileges=$True
+ CategoryInfo : InvalidOperation: (EnablePrivileges:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound

Exception calling "BackupEventlog" : "Access denied "
At C:\ps\BackupSecurityLog.ps1:9 char:24
+ $logFile.backupeventlog <<<< ($path + $exportFileName)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException

Can someone please help me write this? I can't believe exporting event logs would be so painful....

Powershell script help to delete user folders help please

$
0
0

Hello!

The legal organization that employs me is implementing an Exchange 2010 retention policy to move messages to an Exchange archive database after they reach a certain age. This works well for us; however, afterwards users are left with empty personal folders in their mailboxes if all of the items in it have been moved to their archive mailbox. To clean this up I found a powershell script that I am trying to get to work so that I can run it as a scheduled task after MRM finishes running each evening.

At this point I should mention I have can get around Powershell pretty well but can't write scripts and have very limited programming skills.

I also added 'Add-PSSnapin Microsoft.Exchange.Management.Powershell.E2010' to the beginning so that it loads the Exchange Powershell module.

Here it is, I obtained it from here, the issues I have with this script are listed towards the bottom of this post.

## Get the Mailbox to Access from the 1st commandline argument

$MailboxName = $args[0]

## Load Managed API dll  
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"  
  
## Set Exchange Version  
$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2  
  
## Create Exchange Service Object  
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
  
## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
  
#Credentials Option 1 using UPN for the windows Account  
$psCred = Get-Credential  
$creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())  
$service.Credentials = $creds      
  
#Credentials Option 2  
#service.UseDefaultCredentials = $true  
  
## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
  
## Code From http://poshcode.org/624
## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly

## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

## end code from http://poshcode.org/624
  
## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use  
  
#CAS URL Option 1 Autodiscover  
$service.AutodiscoverUrl($MailboxName,{$true})  
"Using CAS Server : " + $Service.url   
   
#CAS URL Option 2 Hardcoded  
  
#$uri=[system.URI] "https://casservername/ews/exchange.asmx";  
#$service.Url = $uri    
  
## Optional section for Exchange Impersonation  
  
#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

function ConvertId{    
	param (
	        $OwaId = "$( throw 'OWAId is a mandatory Parameter' )"
		  )
	process{
	    $aiItem = New-Object Microsoft.Exchange.WebServices.Data.AlternateId      
	    $aiItem.Mailbox = $MailboxName      
	    $aiItem.UniqueId = $OwaId   
	    $aiItem.Format = [Microsoft.Exchange.WebServices.Data.IdFormat]::OwaId      
	    $convertedId = $service.ConvertId($aiItem, [Microsoft.Exchange.WebServices.Data.IdFormat]::EwsId) 
		return $convertedId.UniqueId
	}
}

## Get Empty Folders from EMS

get-mailboxfolderstatistics $MailboxName | Where-Object{$_.FolderType -eq "User Created" -band $_.ItemsInFolderAndSubFolders -eq 0} | ForEach-Object{
	# Bind to the Inbox Folder
	"Deleting Folder " + $_.FolderPath	
	try{
		$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId((Convertid $_.FolderId))   
		$ewsFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)		
		if($ewsFolder.TotalCount -eq 0){
			$ewsFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)
			"Folder Deleted"
		}
	}
	catch{

	}
}

My problems with this script I think are from '$MailboxName = $args[0]' as I think that the '$args' is somehow supposed to be an array that supplies the mailbox. I got around this by making 'MailboxName= Get-Mailbox -Identity user' but would like to be able to input all of my users with retention policies so that it loops through them all. When I make this substitution and run it I am prompted for credentials, I supply them and the script completes with the following output:

PS C:\Users\Administrator\Desktop> C:\Users\Administrator\Desktop\cleanEmpty.ps1
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Deleting Folder /Inbox/Reports/Traffic Reports/Vendors/Integra
Deleting Folder /Inbox/Reports/Traffic Reports/Vendors/J-Thayer
Deleting Folder /Inbox/Reports/Traffic Reports/Vendors/nQueue
Deleting Folder /Inbox/Reports/Traffic Reports/Vendors/PC Law
Deleting Folder /Inbox/Reports/Traffic Reports/Vendors/Planning & Compatibility

However, they are not deleted and still show up in Outlook.

Any ideas? I greatly appreciate any help that you can provide.

Changing Share permissions on 950 user accounts in the same folder

$
0
0

I need to re-install a server OS but to increase the OS drive size I need to move my Student home folders to another drive so I can re-partition the RAID V array. I copied the files to another drive I did this using Robocopy (thanks Spiceworks users) but I cannot find a way to re-instate the share permissions on the top folder of each students folder. Currently each of the 950 students have a folder labelled something like "astudent" and the folder is shared as "astudent$".

I can use the net share command to apply the permissions I want to one student folder but I had to rename the student folder to "astudent$" to get the command to work. This command worked for me on Server 2003 (which I want to replace with Server 2008 r2):

NET SHARE astudent$=j:\students\astudent$ /GRANT:"Authenticated Users",FULL

My question is: Is there a way to write a script which will cahnge each folder one after the other so that I don't have to sit there for a week with a mouse or keep editing this line and running it for each student?

Filtering multiple values in PowerShell

$
0
0

So I'm working on a cool PowerShell script but I'm hung up filtering out objects that have different descriptions in their AD User Object.

Here's the command I'm trying in the script. I'm sure I'm not parsing the array properly so I'm looking for some help.

$then = (Get-Date).AddDays(-90) # The 90 is the number of days from today since the last logon.
$descriptions = "Service Account", "Administrative(Non-Personal)"
Get-ADUser -Property Name,lastLogonDate, Description -Filter {(lastLogonDate -lt $then) -and (description -ne $descriptions)} | FT Name, Description, lastLogonDate

I''m borrowing some of the code from @semicolon'sFind and Disable or Remove Inactive AD Computer Accounts PowerShell script. This was a great script to get started working with AD accounts.

PowerShell Regex match everything before character

$
0
0

I am working on a PowerShell script. I have a string where I need to match every character in that string before the first delimiter / There are multiple / in the string, I just need whatever text is before the first delimiter.

I would imagine this is possible in Regex. My GoogleFu is failing today on this one. I thought i had a script with a regex similar to what I need, but i could not find it.

Any help would be much appreciated.

Cannot display the prompt for "Identity" because type "Microsoft.Exchange.Config

$
0
0

So I've been working on a cool script in PowerShell that disables users if they've not logged on in x number of days along with some other stuff.

One of those items is to remove them from the GAL in Exchange Online if they are disabled.

I'm getting the above error when I try to pipe the identity of the mailbox to the set-mailbox command. I've searched Google and I found 1 person who had the exact same error and wanted to submit a bug to MS for PowerShell on Windows 8 which is what I'm using.

Here's my code:

Import-Module ActiveDirectory
Import-Module MSOnline
$users = Get-ADUser -Property Name,lastLogonDate,Description,Mail -Filter {(lastLogonDate -lt $then)} | Where { $_.Description -notmatch $descriptions }
$userlist = $users| Select-Object mail | export-csv C:\users\mike_brown\Downloads\userlist.txt
$mailbox = import-csv c:\users\mike_brown\Downloads\userlist.txt | ForEach-Object -Process {Get-Mailbox $_.mail}
$mailbox | % {Set-Mailbox -HiddenFromAddressListsEnabled $true -WhatIf}

Here's what I get:

cmdlet Set-Mailbox at command pipeline position 1
Supply values for the following parameters:
Cannot display the prompt for "Identity" because type "Microsoft.Exchange.Configuration.Tasks.MailboxIdParameter" cannot be loaded.
    + CategoryInfo          : ResourceUnavailable: (:) [], PromptingException
    + FullyQualifiedErrorId : System.Management.Automation.Host.PromptingException
    + PSComputerName        : pod51038psh.outlook.com

I'm curious to know if someone with another version of Windows gets this error.

Also is there a better way to do this through powershell?

PowerGUI 3.7.0.92 was released today


Powershell script for WSUS to decline IA64

$
0
0

I'm trying to weed out and decline itanium updates from my WSUS server to save space.

I found a technet page that gave me an almost ready to go script (just change environment variables). Link [Microsoft Technet]

The idea of the script is to decline all Itanium/IA64 updates and send an email stating what it has declined.

I have made the environment changes to the script and I receive the same two errors but I have no idea what they mean or how to resolve them.

Errors:

Exception calling "GetUpdateServer" with "3" argument(s): "The type initializer for 'Microsoft.UpdateServices.Internal.Constants' threw an exception."

At

You cannot call a method on a null-valued expression.

At

Here is the code from the Technet link link (above).

$WsusServer = ""
$UseSSL = $false
$PortNumber = 
$TrialRun = $true

#E-mail Configuration
$SMTPServer = ""
$Recipients = ""
$MessageSubject = "WSUS :: Declining Itanium Updates"

Function SendEmailStatus($MessageSubject, $MessageBody)
{
	$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $Recipients, $MessageSubject, $MessageBody
	$SMTPMessage.IsBodyHTML = $true
	#Send the message via the local SMTP Server
	$SMTPClient = New-Object System.Net.Mail.SMTPClient $SMTPServer
	$SMTPClient.Send($SMTPMessage)
	$SMTPMessage.Dispose()
	rv SMTPClient
	rv SMTPMessage
}

#Connect to the WSUS 3.0 interface.
[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | out-null
$WsusServerAdminProxy = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer($WsusServer,$UseSSL,$PortNumber);

#$itanium = $WsusServerAdminProxy.SearchUpdates('Itanium') | ?{-not $_.IsDeclined}
#$itanium += $WsusServerAdminProxy.SearchUpdates('ia64') | ?{-not $_.IsDeclined}
#Although the above seems faster it also seaches in the description of the update so use the below just to search the title!
$itanium = $WsusServerAdminProxy.GetUpdates() | ?{-not $_.IsDeclined -and $_.Title -match “ia64|itanium”}
If ($TrialRun)
{$MessageSubject += " Trial Run"}
Else
{$itanium | %{$_.Decline()}}

$Style = ""

If ($itanium.Count -gt 0){

	$MessageBody = $itanium | Select `
	@{Name="Title";Expression={[string]$_.Title}},`
	@{Name="KB Article";Expression={[string]::join(' | ',$_.KnowledgebaseArticles)}},`
	@{Name="Classification";Expression={[string]$_.UpdateClassificationTitle}},`
	@{Name="Product Title";Expression={[string]::join(' | ',$_.ProductTitles)}},`
	@{Name="Product Family";Expression={[string]::join(' | ',$_.ProductFamilyTitles)}},`
	@{Name="Uninstallation Supported";Expression={[string]$_.UninstallationBehavior.IsSupported}} | ConvertTo-HTML -head $Style
	SendEmailStatus $MessageSubject $MessageBody
}

I am using WSUS 3.0 on Server 2008 R2 Enterprise.

I am NOT using PoshWSUS.

How to get GPO info via powershell - SYSVOL FILE PATH, MODIFICATION DATE on DC's

$
0
0

Afternoon all,

I was after some advice on which is the best way to get GPO information via powershell for the following on all Domain Controllers :

POLICY NAME,

SYSVOL FILE PATH,

MODIFICATION DATE

Any help or suggestions will be greatly appreciated :D

Powershell HTML Help

$
0
0

I have a simple script that works perfectly, but the output is what I need help with.

Here is my script.

# Clear Screen
cls

# Pre Work
Asnp Citrix.* -ErrorAction SilentlyContinue
Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue

# Delete the exsisting morning report
Remove-Item c:\scripts\DGSUMMARY.htm

$hname = hostname

# Create the HTML table
$a = ""


# ConvertTo-Html -body "

ALP JMF Pooled

" | Add-Content c:\scripts\DGSUMMARY.htm
# Get AD Stats for VDI Groups
##Get-QADGroup VDI_PVS32_Workstation_Access -SizeLimit 0 | Select-Object Name,@{n='MemberCount';e={ (Get-QADGroupMember $_ | Measure-Object).Count}} | ConvertTo-Html -Property Name,MemberCount | Add-Content c:\scripts\DGSUMMARY.htm
Get-QADGroup VDI_PVS32_Workstation -SizeLimit 0 | Select-Object Name,@{n='MemberCount';e={ (Get-QADGroupMember $_ | Measure-Object).Count}} | ConvertTo-Html -Property Name,MemberCount | Add-Content c:\scripts\DGSUMMARY.htm
# Add a Space to the Report
ConvertTo-Html -body "" | Add-Content c:\scripts\DGSUMMARY.htm
# Get % Inuse Stats
$dg = Get-BrokerDesktopGroup "JMF Pooled Win7x86"
Get-BrokerDesktopUsage -AdminAddress ALVJMSWDDC001BP -DesktopGroupUid $dg.Uid -MaxRecordCount 1 -SortBy '-Timestamp' | Select "ALP JMF",InUse,@{Name='Percent';Expression={'{0:P0}' -f ($_.InUse / $dg.TotalDesktops)}} | ConvertTo-Html -head $a -Property "ALP JMF",Inuse,Percent | Add-Content c:\scripts\DGSUMMARY.htm
ConvertTo-Html -body "" | Add-Content c:\scripts\DGSUMMARY.htm

The Output looks like this.

See attchment

What, I am trying to do is get Name, MemeberCount, ALP JMF, Inuse, and percent all on 1 line.

PowerShell learning

$
0
0

Howdy:

I am finding Powershell to be one the most powerful tools I can use on my domain for a variety of tasks.

That said, I have been relying, mostly, on the PowerShell skills of others, and modifying their scripts to get things done that I need done on my network. The latest help was from Martin9700 right here on the Spiceworks forums in utilizing a script to return a nicely formatted report on folder sizes on a SBS server. It was slick. And it was much appreciated!

I have been looking for the best book and or online course for learning PowerShell and thought I would ask this question here. A Google search is overwhelming, and I am hoping for a more personal recommendation from PowerShell users themselves, and what you have found most useful.

Thanks so much!

-Rob

Powershell - Updating array object

$
0
0

I had asked a question a few days ago (http://community.spiceworks.com/topic/365941-powershell-regex-match-everything-before-character?page=1#entry-2411655)

With that question comes another...

I am working with editing XML files with Powershell. Most of my edits work perfectly fine, except the portion I am updating with whatever comes back from the regex results.

Here is the sample XML section:

http://www.w3.org/2001/XMLSchema-instance"; xmlns:xsd="http://www.w3.org/2001/XMLSchema"; verb="">TITL0020000000864577starzencore.comThe JackalThe JackalThe JackalSummary is LongShorter SummaryClosedCaptioning1251997usUNIVERSAL PAY TELEVISIONPremium Channels/Movieplex/All MoviesPremium Channels/Movieplex/DramaPremium Channels/Movieplex/Top HitsMoviePlex_VOD

And here is my current snippet of code:

$TempXML = @(Get-ChildItem $tempDir -recurse -filter "Metadata.xml" | Where-Object {$_.FullName -like "*$($like)*"})

	$Results = @()

	### Edit XML Process
	ForEach ($File in $tempXML)
	{
		$xmlData = [xml](Get-Content "\\Wtcvhovmgmt001\Staging\starzencore.com-TITL0020000000864577\metadata.xml") #(Get-Content $File.Fullname)
		$xmli = $xmlData.assetpackages.assetpackage

		#Regex to replace string in metadata category
		ForEach ($c in ($xmli.metadata.category))
		{
			if ({ $c -notlike "*Subscriptions*" })
			{
				$regex = "^[^/]*(.*)$"
				$c -match $regex
				$c = "Subscriptions" + $matches[1]
				#$c
			}
		}
		$xmlData.Save("\\Wtcvhovmgmt001\Staging\starzencore.com-TITL0020000000864577\metadata.xml") #$xmlData.Save($File.Fullname)
		
		$DirName = Split-Path (Split-Path $file.Fullname -Parent) -Leaf
		$Results += New-Object PSObject -Property @{
			"Date/Time" = $Date
			File = $($file.FullName)
			"Last Write Time" = $($file.LastWriteTime)
			Directory = $($DirName)
			Status = "Successful"
			}
		Write-Host "Succesfully processed $($File.Fullname)" -foregroundcolor green -backgroundcolor black
		
		#Write event to event log for successful metadata editing
		#Write-Eventlog -ComputerName "WTCVHOVCTRL001" Application -source "Microsoft IPTV" -eventid 14888 -message "Successfully edited/updated $($File.Fullname). File is ready for reimport"
	}

The problem I am running into is that when I am inside the ForEach loop attempting to change the value of each item in the Array to the results of the Regex command. It appears to create a variable $c, populate it with the correct value, but then never write that value to the current item in the array that the ForEach is processing.

I have also tried something like the below code (that produced errors):

#Regex to replace string in metadata category
$xmli.metadata.category | ForEach-Object
{
	$regex = "^[^/]*(.*)$"
	$_ -match $regex
	$_ = "Subscriptions" + $matches[1]
}

Any ideas why it's not updating the value of each category node?

Viewing all 15370 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>