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

Powershell $lastexitcode return works on non-zero return but keeps hanging otherwise

$
0
0

So I have performed some major customization on SQLSPADE thats available on CodePlex

sqlspade.codeplex.com

Here is where I am stuck. I have 2 functions in play. When the first functions executes, It calls the second function called Install-SQLSERVER. The code Snippet for the first function is provided below.

Function Fn_Install() 
{
$Global:ResultTextBox.AppendText(" Installaling $Global:Version $Global:edition Edition on $env:computername .Please Wait....`n ")
Install-SQLSERVER -Parameters $ht -TemplateOverrides $overrides -Verbose -DontCopyLocal -InstallOnly
Return
}

As you can see, it writes data to a text box and calls the function Install-SQLSERVER. Within that function, it runs the setup.exe to run a silent SQL Server installation.The code snippet for the second function is provided below



if (($InstallOnly -eq $true -or $Full -eq $true) -and $Global:CriticalError -eq $false)
		{
			Write-Log -level "Section" -message "Starting SQL Server Install"
				#Call the queit install process  - because it writes to the console we don't have to force the code to wait
				if ($pscmdlet.ShouldProcess("Start SQL Installer Package", "Install SQL")) #if (!$Global:Simulation)
				{
                    Invoke-Expression $command
                   [int] $Global:exitCode = $Lastexitcode
				}
                 if ($Global:exitCode -eq 0) 
                {
                $Global:ResultTextBox.AppendText(" Installation Completed Successfully `n ")
                $Global:ButtonPostInstall.enabled = $True
		$Global:CriticalError = $false
                }

                else 

                {
                Write-Log -level "Error" -message "SQL Server Install failed - please check the console output"
                $Global:ResultTextBox.AppendText(" Installation Failed with error Code: $exitCode `n ")
				$Global:CriticalError = $true
                }

                else
		{
			Write-Log -level "Section" -message "Skipping SQL Server Install"
		}


So I am evaluating the condition based on $lastexitcode. It evaluates the condition and does what its supposed to when the installation fails with a non-zero error code. However, when the installation succeeds, it doesnt evaluate the IF condition at all and just stays stuck on the screen. I have to kill the script from the task manager when that happens. The problem is, I cant evaluate if the $lastexitcode was 0 since I have to kill the entire session. Any idea why this is happening?

Thanks,

Lokesh 



Lokesh Gunjugnur


How to check to see if a file is open/locked before trying to copy it

$
0
0

I am trying to copy a set of files and folders fomr one location ot another. It works ok, but if a file is open it generates an error. Is there a way to check to see if a file is open before trying to cpoy it? I mean, can I use it in conjunction with the copy-item cmdlet? My code below

try
{
	copy-item -Path $SourceHomeDirectoryPath -Destination $TargetServerHomePathShort -Recurse -ErrorAction SilentlyContinue
}
catch
{
	$Error
	$MyError = $Error
	$arrayErrors += $MyError
}

 

Where does PowerShell look for DLLs? I have a custom DLL I want to load.

$
0
0

Re: Where does PowerShell look for DLLs? I have a custom DLL I want to load.

I wrote a .Net DLL. Currently I am loading it in my PS script with a LoadFrom. I will be distributing my solution to several sites. Do not want to load it in the GAC, or registry, but do not want to depend on a hardcoded path. Where does Powershell look for DLLs? Maybe I can have it copied to a particular folder and it will be picked up?

[System.Reflection.Assembly]::LoadFrom('C:\temp\EncryptionExample\test.dll')

Need to use -credential in get-wmiobject

$
0
0

Hi,

I would like to remotely enumerate printers on our 2012r2 print server from a Windows 7 box. I am logged into the Win7 box with a domain account that is in the local admins group on the print server. When I:

  get-wmiobject -class "Win32_Printer" -computer printserver.college.edu

I get the dreaded 0x80070005 access denied. If I add "-credential DOMAIN\user" (where DOMAIN\user is the account I am already logged into the Windows 7 box with) and enter my password when prompted, it works fine (so I am sure DOMAIN\user has the proper authority on the print server to do this). I've tried this from the PowerShell console/command line as well as in the ISE with the same results.

What's going on here? Thanks, Tony

Register-PSSession Problem

$
0
0

Greetings everyone.  I'm trying to assign non-admins access to webadministration

commandlets.  First I created a configuration file:

New-PSSessionConfigurationFile –ModulesToImport WebAdministration –VisibleCmdLets * –LanguageMode "FullLanguage" –SessionType RestrictedRemoteServer –Path "c:\webadministration.pssc"


Thereafter I try to register it with RunAs credentials:

Register-PSSessionConfiguration –Name "WebAdmin2" –Path "c:\webadministration.pssc" -RunAsCredential $(Get-Credential) -ShowSecurityDescriptorUI

However, this gives me the following error:

Register-PSSessionConfiguration : An internal error occurred. 
At line:205 char:5
+     Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -sho ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Register-PSSessionConfiguration

Note: If I don't use 'runas', I get no error message.

I am an administrator on the server.

PS script to find recursive folders in a path created within a specific time range

$
0
0

Hi there,I'm fairly new to PS and was wondering if anyone could help out with a script to pass in a folder path, then within that path it will recursively check all folders created time, say within 1-3am and delete them.

thanks.

Need convert txt to csv using Powershell

$
0
0

Hello,

I'm trying to read txt file:

==================================================
URL               : about:blank
Title             : 
Visit Time        : 06.10.2014 8:43:03
Visit Count       : 5354
Visited From      : 
Web Browser       : Internet Explorer 10
User Profile      : User
==================================================

==================================================
URL               : file:///C:/
Title             : 
Visit Time        : 15.03.2013 10:32:03
Visit Count       : 1
Visited From      : 
Web Browser       : Internet Explorer 10
User Profile      : User
==================================================

==================================================
URL               : http://xx
Title             : 518 
Visit Time        : 30.07.2014 15:16:28
Visit Count       : 1
Visited From      : http://xx.xxxxx.xx/adv_out?Id=68265&direct=1
Web Browser       : Chrome
User Profile      : User
==================================================

I need output:

URL, Visit time,

about:blank, 06.10.2014 8:43:03,

file:///C:/, 15.03.2013 10:32:03

http://xx, 30.07.2014 15:16:28

thank you very much for help

this i'm trying to use, but i get one line

$lines = Get-Content "1.txt"

ForEach ($Line in $lines)
{
if ((($Line.contains("URL")) -or
 ($Line.contains("Visit Time"))))
 {
 $Object += $Line + " , "
 }
 }
$Object | out-file 1_out.txt


Create (security)event

$
0
0

Hello,

How can I use PowerShell to create a (security) event?

The structure of the message part of the event should be like the following:

<EventData>
<Data Name="SubjectUserSid">S-1-5-21-1229272821-1801674531-839522115-18652</Data>
<Data Name="SubjectUserName">admindijc</Data>
<Data Name="SubjectDomainName">PGGM-INTRA</Data>
<Data Name="SubjectLogonId">0x21ec6eef</Data>
<Data Name="ObjectType">File</Data>
<Data Name="IpAddress">145.4.61.34</Data>
<Data Name="IpPort">56027</Data>
<Data Name="ShareName">\\*\IPC$</Data>
<Data Name="ShareLocalPath"
/>
<Data Name="AccessMask">0x1</Data>
<Data Name="AccessList">%%4416</Data>
</EventData>

The PowerShell script should be able to create the (xml) eventdata structure with (custom) names for the different parameters. This will enable me to address the individual parts of the avent in OM2012. Without the xml structure SOM2012 would need to search the whole event text which is an expensive operation

Thanks in advance

Regards,

Coen


Uninstall-Windowsfeature in WS2012 R2

$
0
0

Hi,

When I try to remove a feature using Uninstall-Windowsfeature with -Remove it doesn't seems to remove the binaries from the server as when I try to run Install-Windowsfeature for the same feature without mentioning the source its is getting installed. Same with Remove-Windowsfeature as well. Any clue?

Thanks

Install Powershell 3 via GPO?

$
0
0

Hi,

I would like to be able to install PowerShell 3 on all of our Windows 2008 R2 SP1 servers.

Is GPO the best way to go? (I know very little about GPO)

I found this code:

@echo off
SET DC_NAME=domain-controller-computer-name-here

rem Check to see this is Windows XP
ver | find "Windows XP" >NUL
if errorlevel 1 goto end

rem Check to see if the update is already installed
reg QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows XP\SP20\KB943729" >NUL 2>NUL
if errorlevel 1 goto install_update
goto end

:install_update
\\%DC_NAME%\netlogon\Windows-en-US-KB943729.exe /passive /norestart

:end

Should I modify the above code and run it via GPO or is there a better way?

Thanks!

Powershell $webclient.UploadFile

$
0
0

Hello Community!

I am new to powershell and i have been playing around with getting files to upload using FTP.

I have got it working and i am happy with the results but i would like to get the script to exit if the upload fails and to only move the file if its successful. 


#Files to Send
$Dir="C:\test\Output"

#ftp server
$ftp = "ftp://xxx.xxx.xxx.xxx/"
$user = "User"
$pass = "Password"
$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  

foreach($item in (dir $Dir "*.csv")){ "Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name) 
$webclient.UploadFile($uri, $item.FullName) 

Move-Item c:\test\Output\*.csv c:\test\Output\copied

can anyone assist please?

Many Thanks in advance :-)

Kallum

Cannot save xlsx file from powershell

$
0
0

Hi.

My problem is that I cannot save xlsx file that is created by ps script. 

Last string drop errors: Microsoft Excel cannot get access to file: C:\Users\PROFILENAME\Desktop\67E69410
This file is blocked or unexist.

Why so?

$xl=New-Object -ComObject Excel.Application

$xl.DisplayAlerts = $false 
$xl.ScreenUpdating = $true
$xl.Visible = $true
$xl.UserControl = $true
$xl.Interactive = $true

$wb = $xl.Workbooks.Add()
$wb.WorkSheets.Add()

(some filling code)

$wb.SaveAs('C:\Users\PROFILENAME\Desktop\FILENAME.xlsx')



Using powershell to check and removing duplicate entries

$
0
0

Hi Guys,

I have been trying to get my head around powershell to check a csv file. It needs to read in each line in the csv and compare it to the last one and only pull out the entry with the newest time stamp. The data is something like this (btw it has no headers pulled into the csv file).

UID,Type,Sub,Blank,deviceID,Brand,V#,OS,DType,Blank,Date/time

TT1234567,PRINT,7DAY_SUB,,7DD758034,iPad3,6,IOS,Tablet,,2014-09-22T10:59:40.345Z
TT1234567,PRINT,7DAY_SUB,,7DD758034,iPad3,6,IOS,Tablet,,2014-09-22T11:00:40.500Z
TT1234567,PRINT,7DAY_SUB,,f04f7c213b0f,kftt,2,KINDLE,Tablet,,2014-09-23T11:25:16.303Z
TT1234567,PRINT,7DAY_SUB,,f04f7c213b0f,kftt,2,KINDLE,Tablet,,2014-09-23T11:25:18.303Z
TT1234567,PRINT,7DAY_SUB,,08606eb42491,nexus7,4.4,ANDROID,Tablet,,2014-09-24T14:48:23.668Z
TT1234567,PRINT,7DAY_SUB,,08606eb42491,nexus7,4,4,ANDROID,Tablet,,2014-09-24T14:48:24.700Z
p@gmail.com,DIGITAL,DIG_SUB,,08606eb42491,nexus7,4.4,ANDROID,Tablet,,2014-09-24T15:09:08.359Z
p@gmail.com,DIGITAL,DIG_SUB,,08606eb42491,nexus7,4.4,ANDROID,Tablet,,2014-09-24T15:09:09.468Z
TT1234567,PRINT,7DAY_SUB,,7DD758034,iPad3,6,IOS,Tablet,,2014-09-25T11:59:40.345Z
TT1234567,PRINT,7DAY_SUB,,7DD758034,iPad3,6,IOS,Tablet,,2014-09-25T11:59:45.345Z

Output to file should be like the following.

TT1234567,PRINT,7DAY_SUB,,7DD758034,iPad3,6,IOS,Tablet,,2014-09-25T11:59:45.345Z
TT1234567,PRINT,7DAY_SUB,,f04f7c213b0f,kftt,2,KINDLE,Tablet,,2014-09-23T11:25:18.303Z
TT1234567,PRINT,7DAY_SUB,,08606eb42491,nexus7,4,4,ANDROID,Tablet,,2014-09-24T14:48:24.700Z
p@gmail.com,DIGITAL,DIG_SUB,,08606eb42491,nexus7,4.4,ANDROID,Tablet,,2014-09-24T15:09:09.468Z

Same UID can have multiple devices we want to know all the devices and the latest time stamp. As you can see thatTT1234567 used the ipad on the 2014-09-22T11:00:40.500Zbut then used it again on the 2014-09-25T11:59:45.345Z we only want the newest time stamp for that device.

I hope you guys can help me out. 


PowerShell Copy

$
0
0
How do I copy files from one network drive to another network drive using Power Shell.  The files are SQL transaction logs so I need the files for a 24 hour span.  I would like the copy to run at the bottom of each hour preferably 1:45, 2:45…..  Once the copy is complete I would like a log to verify that the copy was successful.  After the copy is successful I would like to delete the transaction logs older than 48 hours old on the source computer.  I am new to Power Shell but this seems like the route to go.

Test Script using Get-WebSite

$
0
0

I need to be able to test a given web site and ensure that 5 different properties are set correctly.

If all the properties are correct, the test script should return true, otherwise false. So far I have this:

$prop = get-website | where { $_.Name -eq $site }

$prop.id -eq "57037"

$prop.enabledProtocols -eq "http,net.tcp"
So how do I group these together to so that the result is either $True or $False


Active code page

$
0
0
For some reason, write-host does not display correct Chinese anymore. I tried using chcp 936 but getting 'CHCP : Invalid code page'.

Get-Childitem with Get-FileHash Info

$
0
0

Hello,

I have been able run the following script to get File names in a Recurse folders, although I'm looking to use Get-Filehast too, although I'm not sure or unable to tag this on the end of this script File-filehast info.  could you advise.

my current Get-Childitem script

get-childitem'\\folder1\folder2\folder3'-recurse|

Add-Member

-MemberTypeScriptProperty-NameVersion-Value{

$this

.VersionInfo.ProductVersion

}

-PassThru|


select-object

DirectoryName,Name,Version,LastWriteTime,Length|where{$_.DirectoryName-ne$NULL}

 

Add line to a text file just after a specific line with PowerShell

$
0
0

Hi,

I have to edit remotely a file called nsclient.ini on hundreds of computers, the file contains some command definitions. For example:

[/settings/external scripts/scripts]    
check_event="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e System -t Error
check_event_application="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e Application -t Error
check_activedir=cscript "C:\Program Files\NSClient++\scripts\Check_AD.vbs" //nologo

I need to add a new line just beneath [/settings/external scripts/scripts] This new line should not overwrite the existing lines beneath.

Thanks for your help.

Don't Import Last Line In CSV

$
0
0

I'm using PowerShell and Log Parser 2.2 to import CSV data into SQL Server. I've encountered an issue whereby a batch of files has an extra line at the very end (totals) and I don't want it imported. Is it possible to either remove the very last line of the CSVs using PowerShell, or tell Log Parser not to import the last row. I've looked for a switch to do this in Log Parser but couldn't find anything.

Thanks in advance
Adam

Security permission in DNS object

$
0
0

Hi.

I have problem with several DNS objects, in security permission disappeared account of himself.

I can`t find powershell cmdlet for this action.

I need 2 scripts: one for get all dns object without account of himself, and second to fix it.

thanks in advance.

Viewing all 21975 articles
Browse latest View live


Latest Images

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