Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

The specified path, file name, or both are too long

$
0
0

Hi

Hoping someone can help, I've been running a script to delete files/folders and it's been running great, however recently some of the folder names have become very long and the script cannot delete these and errors with:

"Remove-Item : The specified path, file name, or both are too long. The fully qualified file name must be less than 260
characters, and the directory name must be less than 248 characters."

I've googled this error and it seems that this is a limitation of PS and .Net?
Is there any way around this?

Here is the code for the script:
$filelocation = "e:\oldbackups"

 
gci -path $filelocation -r | where-object {$_.PsIsContainer -eq "True"} |
    ?{$_.creationtime -lt (get-date).adddays(-30)} | %{del $_.fullname -r -force}


Input parameters not available when calling powershell script from VBA

$
0
0

Hello. I am having some issues when calling a PowerShell script from within VBA. The issue seems that the input parameters to the script do not seem to have a global scope as they do when you call the script from within PowerShell itself. Can someone confirm this and tell me if there is a workaround to this? Or do I just rewrite my script like one would write a app in a language such as C# and pass the input parameters from entry point within the script?

 This is the string used when calling the script:

powershell.exe -executionPolicy Bypass -NoExit -NoLogo -mta -WindowStyle Normal -file "\\ServerName\Share\Path\CalledScript.ps1" -LoginID "SomeID" -ComputerName "Computer1" -OutputPath "\\ServerName\Share\Path\" -Title "Computer1"  -Verbose

 

Thanks, 

Limit to the length of an array

$
0
0

I'm building an advanced function to parse the security log. It seems when I add a 23rd element to my array $list, the script breaks. As long as I stay at 22 or less, it works. Below is the guts of my function:

$list = 4741,4742,4743,4739,4720,4722,4723,4724,4725,4726,4738,4740,4766,4767,4649,4657,4697,4716,4738,4739,4740,4816
#,5148,4776,5149,4625

$events = get-winevent -filterhashtable @{logname="security"; ID = $list}
Foreach ($event in $events) {if ($List -contains $event.id) {$event.timecreated, $event.id, $event.message |
out-file -append c:\sec.txt}}

Powershell and WSUS - Get-WSUSClient - possible bug?

$
0
0

Tim here...

I am attempting to write a script that looks at my Active Directory for specific OUs where I have Policies set to run Windows Updates. I have everything working as I would want.  My issue is in the command:

Get-WSUSClient

I feed into this command via a foreach loop, a list of computer names.  However, if a computer name is similar I can get conflicting results.  Example:

Get-WSUSClient -computer "serverA"

This can return:

serverA

NEWserverA

OLDserverA

How can I ensure that only "serverA" is selected?

What I am attempting to do is to automate the placement of each system into the correct WSUS Computer Group by just adding the system in the correct AD OU.

I have it working and I can Add-WSUSClientToGroup or Remove-WSUSClientFromGroup as long as the names are not similar like my example.  When they are similar I can get those systems in the wrong group which will cause those systems to update and reboot out side of their specific schedule.

Thanks in advance,

Tim now going over there...

Check a valid DATE format

$
0
0

Hi,

 

I tiring to check if the user input is valid DATE format DD/MM/YYYY and it's not NULL,

I tried to use "TryParseExact" command but I get error:

"TryParseExact : Cannot find an overload for "TryParseExact" and the argument count: "2".

what is the best way to do it?

 

Thanks

Lior

 

Send an email from link

$
0
0

Hi

Does anyone know how to create a link in an html file to send an Outlook email.

I'm trying to create a link in a report so the user can just click on the link to send an email.

Thanks

run a command with anther user credential

$
0
0

Hi,

 

I wrote a PS script that ruining a command that deal with user email.

I have the admin privilege for running this command.

By default the mailbox user owner and the exchange admin have privilege to delete emails from the mailbox.(exchange 2007)

This script will be use by Help-Desk users that don't have exchange admin privilege, I need a way that when they run the command they can put the user credential (I used get-Credential command) and the specific command (Export-Mailbox) will run with the mailbox owner credential that the Help-Desk user input before.

The "get-Credential " part is working well.

I need help with the second part - ruining the specific command with user credential.

Thanks'

Lior 

 

Best way to install roles and features in server 2008 r2

$
0
0

Hi All,

I want to install below roles in server 2008 r2. I use import-module servermanager, add-windows feature myroles_and_features. Here are the roles and features:

gpmc,Web-Server,Web-Common-Http,Web-Default-Doc,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Scripting-Tools,Web-Mgmt-Service,Web-Mgmt-Compat,Web-Metabase,Web-WMI,Web-Lgcy-Scripting,Web-Lgcy-Mgmt-Console,RDS-RD-Server,RDS-Licensing,NET-Framework, NET-Framework-Core, Application-Server.

What is the best way to install all these roles with the add-windows feature command. Because I think some of the above roles might need a restart. For example, if I execute all the above roles at a time, It throws me an error saying application-server is not installed. So, I am executing all the above roles except application-server role, then reboot and then install application-server role. Hence I want to know what is the best way to install all the above roles.

Chaitanya.


Replacing part of a element in an Array

$
0
0

Hello

I woundered if someone could please give me some advice on the following.

Is there an easier way to achieve the following

$b = $null

$A = "AXA","BZB","CYC"

foreach ($element in $A)

{

switch -wildcard ($element)

{  "*X*" {$element = $element -replace "X","T";continue}   }

[array]$b += $element

}


$A = $B

So basically I am looking for any element in Array $A which contains an "X" character and if seen replace the X with a T and put the results in Array B, so $B looks like this

ATA
BZB
CYC

Then, $A = $B makes $A the same as $B (e.g. my X has been replaced with T)

I was thinking may be I could use the $A -Contains operator using a wildcard or regex statement e.g. $A -contains *X* no joy.

I just wondered if there was a simpler way

Thanks All

Ernie

 

List the ARP(Add or Remove Program) entries.

$
0
0

Is there any cmdlet or any other way through powershell to get the ouput of what ARP display?

 

Puneeth.

Question about -Split

$
0
0

$String = @("asdf asdf hijk Database:001 asdf:45545 asdf asdf:4554 Database:101 hijk"
"asdf asdf hijk Database:301 asdf asdf asdf asdf:4545 asdf asdf Database:011 hijk ")
Select-String -InputObject $String -Pattern 'Database:\d+' -AllMatches | %{$_.Matches} | %{$_.Value -split ':'}

I am a using above code as a part of a script..

Select-String -InputObject $String -Pattern 'Database:\d+' -AllMatches | %{$_.Matches -split ':'}
# and this
Select-String -InputObject $String -Pattern 'Database:\d+' -AllMatches | %{$_.Matches.Value -split ':'}
Show the same result.

My question is how -split works on the object $_.Matches. I am looking for a technical explanation...

Is it taking the property values by default? if yes why -split took the Property VALUE to process? any reason?

In the following example -split uses Name property and process it.. how does it decide which property to process?

$Service = Get-Service
$Service -split "SV"

Very Old FTP, Need Password Encripted

$
0
0

We have a very very very old mainframe here and the FTP that can pull from it is also old and I need to pull a couple of files from it on a daily basis using PowerShell (PS.) This is not a problem, it’s very easy.  The problem is I can’t encrypt the password because the only way I can figure out how to get the files is to have PS call a text file that fills in the FTP info.
ftp -s:C:\POWERSHELL\LIVESCRIPTS\FTP.txt

The text file simply has…
open 123.456.78.90
AccountName
Password123
get 'taz.arc.tape.daily' E:\DAILY\DAILY1\DAILY
quit

Note that the target is ‘taz.arc.tape.daily’ and has periods instead of backslashes.  This is because there really is not a path, the full file name is ‘taz.arc.tape.daily’ but when I pull it down it becomes simply ‘daily’

This opens the FTP, logs on and pulls the file from the FTP to the location I want and closes the FTP.  It works perfectly except the fact that anybody can open the text file and see the password.   I know how to encrypt the password in PS but what I need to know is… Ether how to encrypt the password in the text file or how to have the password be a variable in PS that can be used at that spot in the text file.

One solution I came up with is to have PS make the text file and delete it at the end of the script.  This is not perfect because somebody could grab the text file before PS has the chance to delete it.  It is at least making it harder for someone to get the password but I would like it to be a lot more secure than that.

Any help is appreciated.  Thank you, -Dan

reading values from xml

$
0
0

 </TaskHeader>

  <TaskDetails>

    <Item MailboxName="lior test">

      <Source>

        <Identity>ysds.co.il/Users OU's/HQ/Marketing/lior test</Identity>

        <DistinguishName>CN=lior test,OU=Marketing,OU=HQ,OU=Users OU's,DC=ysds,DC=co,DC=il</DistinguishName>

        <DisplayName>lior test</DisplayName>

        <Alias>liortest</Alias>

        <LegacyExchangeDN>/o=Services LTD/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=liortest</LegacyExchangeDN>

        <PrimarySmtpAddress>ltest@ysds.co.il</PrimarySmtpAddress>

        <SourceServer>MAILSTORE.ysds.co.il</SourceServer>

        <SourceDatabase>mailstore\SG6\MS6</SourceDatabase>

        <IsResourceMailbox>False</IsResourceMailbox>

        <SourceGlobalCatalog>DCHQ1</SourceGlobalCatalog>

      </Source>

      <MailboxSize>2705KB</MailboxSize>

      <Duration>00:00:00</Duration>

      <Result IsWarning="False" ErrorCode="0">Messages have been deleted from the source mailbox.</Result>

    </Item>

  </TaskDetails>

  <TaskFooter>

    <EndTime>06/06/2013 16:45:05</EndTime>

    <TotalSize>2705KB</TotalSize>

    <StandardMessagesDeleted>3</StandardMessagesDeleted>

    <AssociatedMessagesDeleted>0</AssociatedMessagesDeleted>

    <DumpsterMessagesDeleted>80</DumpsterMessagesDeleted>

    <Result ErrorCount="0" CompletedCount="1" WarningCount="0" />

  </TaskFooter>

</export-Mailbox>

 

I need to read the following values:

<Alias>

<StandardMessagesDeleted>

and send them to txt file: <Alias>, <StandardMessagesDeleted>

 

what the best way to do it?

 

Thanks

Lior

 

View installed updates.

$
0
0

Hi,

In powershell is there any cmdlet or any other way to list all the installed updates on a windows 7 PC. 

I have tried Get-Hotfix but it not giving the total list of updates installed on a PC.

not finding new-symlink cmdlet error

$
0
0

I have installed:

  • powershell 3.0 on my server 2008 R2 server
  • the corresponding v3.0 pscx community extension module which includes the new-symlink cmdlet

I'm running a powershell script under a service.  When the service runs the script, I get the message:

New-Symlink : The term 'New-Symlink' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

 

If I run the script through the PowerShell ISE it runs ok.  I'm assuming that the module sis not loading properly.  How do I get the module to load properly when the script runs as a service?


Call a 2nd PS, as another user and bring back paramters

$
0
0

Hi

 

I'm new to PS, but not scripting in general and am trying to create a script to automate our Win7 build process.

For various reasons, the machine will be built off the domain, then join itself to an existing machine account at the end.

In order to get the right set of applications installed, the machine account is added to an AD group when created and this info will need to be pulled back to call the applications.

During the build, the machine gets logged on as a local user with admin rights which has no access to the domain.

Now we come to the issue I am having...

I can get the PS1 to call PS2 one and pull back the required parameters, but only while logged on with a domain account.

The PS1 is as follows with some options I've tried commented out:

#Invoke-Command -FilePath R:\PostBuild\OUInfo.ps1#Invoke-Command -Credential $strCred -ScriptBlock {$strOU, $strCompName = & "R:\PostBuild\OUInfo.ps1"}$strOU, $strCompName = & "R:\PostBuild\OUInfo.ps1" -Credential $strCred

There is a working command above this to set $strCred - I know this works as it has been copied from a working PS.

When I try either of the Invoke-Command lines, I just get the following error:

 

Invoke-Command : Parameter set cannot be resolved using the specified named parameters.

At R:\PostBuild\PostBuild.ps1:10 char:15

+ Invoke-Command <<<<  -FilePath R:\PostBuild\OUInfo.ps1

    + CategoryInfo          : InvalidArgument: (:) [Invoke-Command], ParameterBindingException

    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeCommandCommand

 

But the line not using Invoke-Command works while run as a network user but doesn't use the credentials provided and thus falls over when run as a local user.

 

Sorry if I've been a bit ambiguous here, I may not be explaining myself properly

Does anyone know of a way to do what I need to do?

 

Thanks in advance

 

Matt

Parse a text file

$
0
0

Hi Guys,

I have to parse a text file with recurring informations from different items. Looking like this.

Slot #1
Servername: SRV00001
Type: Blade
Model: Dell
Slot #2
Servername: SRV00002
Type: RackMounted
Model: HP
Slot #3
Info: No Server Installed
Slot #4 .....

What I like to have is a table looking like this:

Slot           Servername      Type  
1               SRV00001         Blade
2               SRV00002         RackMounted
3               NoServerInstalled
4 ....

I'm thinking about using an array to fill in this informations, but I didn't find a way so far to loop for every serer slot. Any help would be appreciated.

Thanks,
Thomas

Replace usernames from mapping-table.csv

$
0
0

Hi.

I have several text-files with different usernames that has to be replaced according to a mapping-table.csv file. Does anyone know of a nice script to use?

Best regards Trond

Printing to TIFF Conversion then verifying file has printed.

$
0
0

Have a script:

Function Printfiles{
 param ($dirfiles, $log)
 foreach ($file in $dirfiles){
  #Printing each file in Blackice Dir
  $file | Out-Printer
 }
}

Function ValidatePrinted{
 param ($dirfiles, $Efile)
 $TiffDir = ""
 foreach ($file in $dirfiles){
  #Converting to string to change extension
  $extension = Get-ChildItem $file.Name | %{$_.Extension}
  $filest = [string]$file.name
  [string] $Vfile = $filest.replace($extension, ".tiff")
  #checking if file printed.
  if (Test-Path $TiffDir\$Vfile ){
    #File Printed
    "$Vfile exists" >> $log
   } Else {
    #File did not print
    "$Vfile does not exist" >> $log
    #adding to do not delete file
    $Vfile >> $Efile
    #Sending to Event Viewer
    Write-EventLog -LogName Application -Source BlackIcePrint -EventId 1000 -EntryType Error -Message "Did not convert $Vfile."
    #Emailing error
    EmailError $Vfile
   }
 }
}

My issue is that periodically when this runs it is hitting the validate routine and the files are still queued up and printing.  This is a file conversion versus physical printer. 

My thought was to modify this script to do something like this, but since I did not write the original script but inherited it I am at my learning curve trying to figure this out...but I think I would like to do something like this

Function PrintAndValidateFiles{
     foreach ($file in $dirfiles){
          $file | Out-Printer - Wait #I want it to wait here until file is printed before continue
          #Waits until file is printed(converted)
          $extension = Get-ChildItem $file.Name | %{$_.Extension}
          $filest = [string]$file.name
          [string] $Vfile = $filest.replace($extension, ".tiff")
          #Is File Printed?
         if (Test-Path $TiffDir\$Vfile ){
           #File Printed
           "$Vfile exists" >> $log
          } Else {
           #File did not print
           "$Vfile does not exist" >> $log
           #adding to do not delete file
           $Vfile >> $Efile
           #Sending to Event Viewer
          Write-EventLog -LogName Application -Source BlackIcePrint -EventId 1000 -EntryType Error -Message "Did not convert $Vfile."
          #Emailing error
          EmailError $Vfile
          }
     }
}

I believe it should all work correctly if I can just figure out the -Wait portion to make the script stop executing until after the printing is done then validate the TIFF file is there.

Any suggestions, pointers or help to a newbie would be greately appreciated.

Steven

 

Code signing error

$
0
0

Dear Sir,

 

              I used a script to sign scripts. 

 

               Following is the script I used. 

 

## sign-file.ps1

## Sign a file

param([string] $file=$(throw "Please specify a filename."))

$cert = @(Get-ChildItem cert:\CurrentUser\MY -codesigning)[0]

Set-AuthenticodeSignature $file $cert

 

                When I run this script, it will generate the following error:

 

Get-ChildItem : A parameter cannot be found that matches parameter name 'codesigning'.

At C:\Users\paul\Documents\Documents\WindowsPowerShell\scripts\sign-file.ps1:4 char:46

+ $cert = @(Get-ChildItem cert:\CurrentUser\MY -codesigning)[0]

+                                              ~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException

    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

 

Set-AuthenticodeSignature : Cannot bind argument to parameter 'Certificate' because it is null.

At C:\Users\paul\Documents\Documents\WindowsPowerShell\scripts\sign-file.ps1:5 char:33

+ Set-AuthenticodeSignature $file $cert

+                                 ~~~~~

    + CategoryInfo          : InvalidData: (:) [Set-AuthenticodeSignature], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SetAuthenticodeSignatureCommand

 

                   When run the same script again, no more error.

                    Kindly help.

 

Paul Cheuk

 

 

Viewing all 10624 articles
Browse latest View live