Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

how to create TFS query link

$
0
0

I have below TFS query and I want to create a link for TFS like QueryLink so when we click the link it should open the query in web in TFS

please let me know how do I create the link.

$tasktfs = $tfs.query("
    SELECT *
    FROM WorkItems
    WHERE [System.TeamProject] = 'DO'
    AND [System.WorkItemType] = 'RDTask'
    AND [System.AssignedTo] = '$team'
    AND [System.ChangedDate] >= '$fromDate'
    AND [System.ChangedDate] <= '$toDate' ")

Thanks


Thanks,


date format conversion

$
0
0

hi,

Is there a single command available to convert the format of date from one to another? Such as:

mmddyy to yyyymmdd

String validation - use REGEX?

$
0
0

Hi all

I'm trying to figure out the best way to perfom validation on a string representing a UNC path.  I would like to check that the path has a fourth backslash and also has some characters after the fourth backslash, e.g.

\\blah\blah\blah = ok

\\blah\blah or \\blah\blah\ = not ok

"blah" could be anything.

Is regex the simplest way to go with this or is there an easier way?


Alexei

Find files that match with given string, except one character in a fixed position

$
0
0
Hi,

I want to find files in a directory with a given string (ss-20140129-process-000*.sdx), where only one character will be mismatched, so have to use wildcard for that character. This means I am looking for filenames where everything needs to be matched except one character in position of "*". For the samples given below: 1st 3 files matched with the given string, but last 3 files have not matched, so first 3 files will be counted.


ss-20140129-process-0001.sdx
ss-20140129-process-0004.sdx
ss-20140129-process-0009.sdx
zx-20140129-process-0001.sdx
bt-20140129-process-0002.sdx
zx-20140129-process-0001.sdx


I can use the command like (GCI -path $folder -filter ss-20140129-process-000?.sdx), BUT problem is i am building a string for the filter (code given below), where i DO NOT know how to use "?" within the string to make a character exception.


Code:
$datevalue = [datetime]::parseexact($trandate,"MMddyy",$null)
$yyyymmdd = $datevalue.tostring('yyyyMMdd')

$FileToCheck = ("ss-"+$yyyymmdd+"-process-000?.sdx")

GCI -path $folder -filter $FileToCheck

But it's definitely NOT working for syntax problem.
Any help?




Install multiple hotfixes using powershell

$
0
0

Guys,

I need help in  installing multiple hot fixes  using powershell on our domain controllers. i searched a little on google/bing  but was unable to find  the solution may be i am searching wrong :) . The solution should install  multiple hotfixes  and don't restart . restart can be done manually. 

Remove old files and empty folders

$
0
0

Hi,

I try to elegantely remove old files and folders.

I got this Script Snippet:

Function RemoveOldFiles
{
	$TimeSpan = "14" 
	$TargetFolder = "D:\test\folder"
	if (Test-Path $TargetFolder)
	{
		$Now = Get-Date
		$LastWrite = $Now.AddDays(-$TimeSpan)
		$Files = Get-Childitem $TargetFolder -include * -recurse | Where {$_.LastWriteTime -le "$LastWrite"} 
		foreach ($File in $Files)
		{
			write-host "Deleting file $File"; 
			Remove-Item $File | out-null
		}
	}
	else
	{
		Write-Host "'$TargetFolder' doesn't exist." -foregroundcolor "Red"
	}
}


RemoveOldFiles

But I also want to delet the now empty directories ...
Is there a way to easily change the existing snippet


User lastlogon workstation in domain

$
0
0

Hi

 I have list of users in CSV file ..

I need to get the all users lastlogontime on workstations details where they have logged in domain..

In short,, Lastlogon workstation of user in domain..

How can I achieve it .. please advise..


Find only one different extension, whole path, last write time, only files and over 260

$
0
0

Hello!

I need some help with my PowerShell script. This is what I got so far.

Get-ChildItem p:\ -Include *.* -Recurse | Where { ! $_.PSIsContainer } | Select-Object Extension,LastWriteTime | Sort-Object -Property Extension -Unique | Out-File c:\skriptit\file.txt

I need to find out every different extension what there is our shared files. I want only one file for each extension and it have to be last time when somebody used(write) it. I also need whole path and over 260 character
long. Also every subfolders and only files, no folders.

This script what I have, it take first extension it finds and take that Last Write Time. Also threre is no full path and no over 260 characters.

Mika


Use Same Excel Object in Start-Job as Main PS1

$
0
0

I have hundreds of Excel files and one main file that has links to each of these files, but in order for the data to be pulled into the main excel file I need to have every file opened within the same Excel instance and then work through each one. If Microsoft let me open more than 15 files at a time this would be as easy as it was back in the day to open them all at once, but I understand why this isn't allowed anymore... So I created a script to open all of the files with:


$xl = New-Object -comobject Excel.Application
foreach($file in $files){
$wb = $xl.Workbooks.open($filename)
}
$xl.visible = $true

I am also going to be processing hundreds of rows per file. I don't care about the order the files are opened in necessarily. So I have narrowed in on usingStart-Job like so because of the unordered opening and the overhead of starting the Start-Job is better than the forking process I have tried the following:

Start-Job -ScriptBlock {Param( $filename); Write-Host $filename "*" $input "*"; $input.Workbooks.open($filename) } -inputobject $xl -ArgumentList @($filename)

~my_path_and_filename~ * System.Management.Automation.Runspaces.PipelineReader`1+<GetReadEnumerator>d__0[System.Object] *
You cannot call a method on a null-valued expression.+ CategoryInfo          : InvalidOperation: (open:String) [], RuntimeException+ FullyQualifiedErrorId : InvokeMethodOnNull

Start-Job -ScriptBlock {Param( $filename); Write-Host $filename "*" $args[0] "*"; $filename.Workbooks.open($args[0]) } -ArgumentList @($xl, $filename)

Microsoft.Office.Interop.Excel.ApplicationClass * ~my_path_and_filename~ *
Method invocation failed because [Deserialized.System.__ComObject#{000208db-0000-0000-c000-000000000046}] doesn't contain a method named 'open'.+ CategoryInfo          : InvalidOperation: (open:String) [], RuntimeException+ FullyQualifiedErrorId : MethodNotFound

Start-Job -ScriptBlock {Param($xl, $filename); Write-Host $filename "*" $xl "*"; $xl.Workbooks.open($filename) } -ArgumentList @($xl, $filename)

~my_path_and_filename~ * Microsoft.Office.Interop.Excel.ApplicationClass *
Method invocation failed because [Deserialized.System.__ComObject#{000208db-0000-0000-c000-000000000046}] doesn't contain a method named 'open'.
    + CategoryInfo          : InvalidOperation: (open:String) [], RuntimeException+ FullyQualifiedErrorId : MethodNotFound

So, is there a way to pass an Excel Object to the Start-Job cmdlet? Or is there a way to pass an Excel object out of the Start-Job so the main Object can take it over? And lastly, when receiving a job, does one get access to the actual objects inside of the job?

Script to create a folder that can print a certain amount of files - works for Libre but not for Word.

$
0
0

I've got this script 

[int]$copies = Read-Host "Number of copies"
 for ($i=0;$i -lt $copies;$i++) {
     Get-ChildItem "C:\Users\USER NAME\Desktop\PrintMe" | foreach {Start-Process -FilePath $_.FullName -Verb Print}
 }

Which works fine if the documents are in libre format, but if they are in word MS Word starts opening up an instance for every document and then comes up with loads of pop up messages about the Template file and thing's. 

This come's up although there is a printer linked to the computer and I'm able to print thing's out by opening the file and selecting print....

Not too sure what's it's struggling with

Remove-item recursive

$
0
0

How do you delete all the txt files from one folder and all sub folders?

remove-item -Path Logs -Filter *.txt -Recurse

This works but it tries also to delete the subfolders and raises some exceptions

remove-item -Path Logs\* -Filter *.txt -Recurse

This doesn't delete the txt files in the subfolders

remove-item -Path Logs -Include *.txt -Recurse

This does exactly nothing, most probably because the Path has no wildcard

remove-item -Path Logs\* -Include *.txt -Recurse
This doesn't delete the txt files in the subfolders

It seems a simple task, but it doesn't, so I tried all the combinations of path with include and filter but no one really works, what I missing?

Issuing a PKI Certificate via Powershell

$
0
0

Hi All,

Noob in need of Powershell help:

Currently my Access Control team have to manually issue PKI Certificates from the Certificate Authority console. I looking to automate this via powershell. I am able to Sumit the .req file to the CA and retreive the .cer but cannot Issue the Pending Request.

Im really struggling to find any info/help about this.

Whats is really bugging me is I cant figure out how I can issue the correct RequestID from the CA, I can I let the script know the RequestID of the certificate I have just submitted?

Can anyone give me a sample code..

Sorry if I havent explained myself well......

Use Powershell to Reset Permissions on files/folders

$
0
0

Hello,

I have a shared folder on a Windows 2003 R2 server that users are allowed full control to.  I have setup permissions on the root of the share, and all sub-folders inherit the permissions.  If a user wanted to change the permissions, they could, but they could easily remove the Administrator access and System access as well.  So I'm looking for a script to verify that the Administrators and System accounts have access to the folders.

However, I can't seem to get it working.  Logged in as a member of the Administrators group, I have setup a test folder so I have ownership over the folder.  Then I remove the Administrators group from the ACL through the GUI.  So I end up with a folder where I'm the owner, but have no rights to edit/view the contents.

In powershell, if I run a simple:

$acl= get-acl $folder$allinherit=[System.Security.AccessControl.InheritanceFlags]"ContainerInherit", "ObjectInherit"$allPropagation=[System.Security.AccessControl.PropagationFlags]"None"$AR= New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl", $allInherit, $allPropagation, "Allow")$acl.SetAccessRule($AR)

Set-Acl -AclObject $acl-Path $folder


I keep getting a Permission Denied error when running this.  Is there anyway to add a permission to a folder when I'm the owner but don't have ACL rights?  I can do it through the GUI without any errors.

Thanks for your time.

Solved - How to take ownership and change permissions for blocked files and folders in Powershell

$
0
0

Hello,
I was trying to take ownership & fix permissions on Home Folder/My Documents structures, I ran into the common problem in PowerShell where Set-Acl & Get-Acl return access denied errors. The error occurs because the Administrators have been removed from file permissions and do not have ownership of the files,folders/directories. (Assuming all other permissions like SeTakeOwnershipPrivilege have been enabled.

I was not able to find any information about someone successfully using native PS to resolve the issue.  As I was able to solve the issues surrounding Get-Acl & Set-Acl, I wanted to share the result for those still looking for an answer.
----
Question: How do you use only Powershell take ownership and reset permissions for files or folders you do not have permissions or ownership of?
----

Problem: 
Using the default function calls to the object fail for a folder that the administrative account does not have permissions or file ownership. You get the following error for Get-Acl:

PS C:\> Get-Acl -path F:\testpath\locked
Get-Acl : Attempted to perform an unauthorized operation.+ get-acl <<<<  -path F:\testpath\locked+ CategoryInfo          : NotSpecified: (:) [Get-Acl], UnauthorizedAccessException+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetAclCommand

If you create a new ACL and attempt to apply it using Set-Acl, you get:

PS C:\> Set-Acl -path F:\testpath\locked -AclObject $DirAcl
Set-Acl : Attempted to perform an unauthorized operation.
At line:1 char:8+ Set-Acl <<<<  -path "F:\testpath\locked" -AclObject $DirAcl+ CategoryInfo          : PermissionDenied: (F:\testpath\locked:String) [Set-Acl], UnauthorizedAccessException+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetAclCommand

Use of other functions like .GetAccessControl will result in a similar error: "Attempted to perform an unauthorized operation."

How do you replace owner on all subcontainers and objects in Powershell with resorting to external applications like takeown, icacls, Windows Explorer GUI, etc.?

Tony

Extract data from a log (txt) and import them in excel

$
0
0

Hello everyone,

I'd like to ask you if it is possible (As I'm newbie in powershell) and how to extract data(specific lines) from a log (txt) and import them in excel.

Here the "problem" in details:

I receive every day a specific log file (in text) from an application that traces some transactions.

The log filename has the following format: LOGyyyymmddHHMM.log

Sometimes, I have an error message and I that's I need to extract  and import it in an Excel file.

Here how it appears the lines in the log(not the real log as it is for a medical application):

 "13/12/23 07:30:04  This is the error message.    <The rest of the line, I want to discard it."

So, firstly I would like to insert in the excel file, in one column the date,in the other the hour that the error happened and on the third one the error message (in this case "This is the error message") and the rest of the line to be discarded.

Secondly I'd like to run this script every day at 02h00 for each new file based on it's name (file name given above) and add the results in the excel file.

And for the end, I need one excel file per month.

For the record, I tried this one but it misses a lot of code in order to accomplish that I need:

Set-ExecutionPolicy RemoteSigned

$mylog = Get-Content C:\CFT\LOG2013122323590018

$mylog | Select-String "This is the error message"

So, now $mylog contains all the lines with the error but as I explained above, I need some more.

Does anyone know if it is possible?

Thank you in advance Guys.





list directory of different servers

$
0
0

I am trying to get the list of directory of multiple servers, and trying the below code. But, When i execute the script, I get DirectoryList as empty. I have tried Invoke-Command, It doesn't work as WInrm can't be turned on system due to some reason. Is there anyother way to get list of folders of array of servers.

$Server = "localhost", "k0z0s" , "sabee" $DirectoryList= $Server| ForEach-Object { Get-ChildItem $DriveLetter -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $true)} | Select-Object Name,FullName} }

Foreach ($Directory in $DirectoryList) { IF ($Directory -ne $null) { $DirectoryName= $Directory.FullName write-Output "Directory is $DirectoryName" } Else { write-Output "Directory is Null" } }



Known Issues with PoSh 3.0 / WMF 3.0 on Server 2008 R2

$
0
0

Hi, we want to deploy WMF 3.0 on Server 2008R2 Sp1 on a larger scale.
 

Are there any more known Issues other than with these:

 System Center 2012 Configuration Manager

System Center Virtual Machine Manager
Exchange Server 2007 and Microsoft Exchange Server 2010
SharePoint 2010
Windows Small Business Server 2008 and Windows Small Business Server 2011

 

And does WMF 3 work fine with System Center 2012 Configuration Manager SP1?

Thanks, Rob



"Powershell 2 host programs that have been compiled with CLR 2"

$
0
0

Hi, i was reading the Windows PowerShell System Requirements and stumbled over the following sentence:

"..."due to a change in the runtime activation policy in Microsoft .NET Framework 4.0, Windows PowerShell host programs that werewritten for Windows PowerShell 2.0 and compiled with Common Language Runtime (CLR) 2.0 cannot run without modification in Windows PowerShell 3.0, which is compiled with CLR 4.0."

Can someone explain that to me? What are Powershell host programs?

Thanks, Rob

Powershell v2 and Active directory module

$
0
0

Could anyone provide me the windows powershellv2(CTP3) link and Active directory module for 32 bit (OS: Windows 2003)

Pls help.

Getting Error trying to convert XLS to CSV using Powershell Only when using scheduled tasks.

$
0
0

Hello

I have a Powershell script to convert XLS files to CSV. The CMD file calls the PS1 script, it takes all the XLS files from my input folder and convert them to CSV. that works nice if you run the CMD file from the desktop. 

The problem starts when I use a Windows Scheduled Tasks to run the CMD files every 10 minutes. I get below error and the files are not converted

New-Object : Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)). At C:\PowerShell\BatchConvertXLS.ps1:58 char:14 + $Excel = New-Object -Com Excel.Application + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : ResourceUnavailable: (:) [New-Object], COMExcept ion + FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman ds.NewObjectCommand Property 'visible' cannot be found on this object; make sure it exists and is settable. At C:\PowerShell\BatchConvertXLS.ps1:59 char:5 + $Excel.visible = $False + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound Property 'displayalerts' cannot be found on this object; make sure it exists and is settable

Any idea how to make it works?

I am using Windows 2012 with excel 2013 installed

Thanks


Javier Villegas | @javier_villhttp://sql-javier-villegas.blogspot.com/

Please click "Propose As Answer" if a post solves your problem or "Vote As Helpful" if a post has been useful to you

Viewing all 21975 articles
Browse latest View live


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