Quantcast
Channel: PowerShell.org » All Posts
Viewing all 13067 articles
Browse latest View live

Question about parameters accepting pipeline input

$
0
0

Straight away, let me say I couldn't be more of a noob, so I apologize for the noobicity of this question.
Just started learning Powershell using the 30 Lunches book. My question is on the topic of cmdlets accepting pipeline output.

I've been using this handy command for a while to see what drives were mapped on a remote computer (though never having used Powershell, I just knew to copy and paste it into PS to get my results – had zero idea what was happening):

Get-WmiObject -Class Win32_MappedLogicalDisk -ComputerName  | Select-Object -Property Name, ProviderName

Knowing a little more now, I'm trying to follow the process through. Here's my question: The help for Select-Object shows that its parameter "-Property" does NOT accept pipeline input. In that case, how is it acting on the objects coming through the pipe from Get-WmiObject?

Hope that makes sense!
James


Reply To: Question about parameters accepting pipeline input

$
0
0

Select-Object has a parameter named -InputObject. That's what's accepting the pipeline input. The -Property parameter tells the command which properties, from the objects passed to -InputObject, to output.

If a parameter is accepting pipeline input, you'd never see that parameter typed out. In fact, typing a parameter manually prevents it from accepting pipeline input.

Reply To: Creating a new VM and VHD with HyperV

$
0
0

Hi Daniel,

Not so certain I understand why you are reading values in your function via Read-Host when you are already passing these in as parameters to the function? It defeats the purpose.

Also, can you post the actual error message?

Reply To: Creating a new VM and VHD with HyperV

$
0
0

Good point, thanks. Got it working, thanks!

[string]$Name = Read-Host 'Name your VM'
[int64]$RAM = Read-Host 'How much RAM?'
[int64]$HDD = Read-Host 'How much storage?'
New-VM -Name $Name -MemoryStartupBytes ($RAM * 1mb) -path C:\HyperV\$Name
New-VHD -path C:\HyperVStorage\$Name.vhdx -SizeBytes ($HDD * 1gb) -Dynamic
Add-VMHarddiskDrive -VMName $Name -path C:\HyperVStorage\$Name.vhdx
Set-VMdvddrive -VMname $Name -ControllerNumber 1 -path C:\users\dbrooks\desktop\en_windows_server_2012_x64_dvd_915478.iso
Add-VMNetworkAdapter -VMName $Name -SwitchName vSwitch

Reply To: Problem with DoCMD.runsql

$
0
0

Jack,

Get-childitem is still commented out. That is my next task, to get the file/table names that will eventually pipe into the $table variable. (I am learning how to parse the name from the extension.) I will write the names to a text file and get the content for the $table variable from that text file. For now I was just building and testing the script step by step.

The $table variable works fine with the "$a.DoCom.TransferSpreadsheet…" statement, just not the "$a.DoCmd.runsql" statement.

Reply To: Creating a new VM and VHD with HyperV

$
0
0

No, you want to parametrize your function so you don't have to prompt the user inside the function, using Read-Host. Instead, the information is passed in at the same time the function is called. In my example, the function is created, and then called including the required parameters (notice we made those mandatory).

Function New-Server2012r2VM {
    Param(
        [Parameter(Mandatory=$true)]
        [int]$RAM,
 
        [Parameter(Mandatory=$true)]
        [string]$Name,
 
        [Parameter(Mandatory=$true)]
        [int]$HDD
    )
 
    Begin {
    } #End Begin
 
    Process {
        New-VM -Name $Name -MemoryStartupBytes ($RAM * 1gb) -path C:\HyperV\$Name
        New-VHD -path C:\HyperVStorage\$Name.vhdx -SizeBytes ($HDD * 1gb) -Dynamic
        Add-VMHarddiskDrive -VMName $Name -path C:\HyperVStorage\$Name\$Name.vhdx
        Set-VMdvddrive -VMname $Name -ControllerNumber 1 -path C:\users\dbrooks\desktop\en_windows_server_2012_x64_dvd_915478.iso
        Add-VMNetworkAdapter -VMName $Name -SwitchName vSwitch1
        Start-VM $Name
    } # End Process
} #End Function
 
New-Server2012r2VM -RAM 2 -Name DC01 -HDD 80

Reply To: Question about parameters accepting pipeline input

Reply To: Problem with DoCMD.runsql

$
0
0

Ah…I misunderstood then my bad. Okay then the problem is where you placed your "$sql = " statement. Since it depends on the value of $t you have to place it inside the foreach loop.

Example:

$table = 'ScheduleTasks', 'Budget', 'Process_CBVR'
$sql = "DELETE * FROM $($t);"
 
ForEach ($t in $table) {
    Write-Output "T:  $t"
    Write-Output "SQL: $sql"
}

Gives you:

T:  ScheduleTasks
SQL: DELETE * FROM Process_CBVR;
T:  Budget
SQL: DELETE * FROM Process_CBVR;
T:  Process_CBVR
SQL: DELETE * FROM Process_CBVR;

But this:

$table = 'ScheduleTasks', 'Budget', 'Process_CBVR'
 
ForEach ($t in $table) {
    $sql = "DELETE * FROM $($t);"
    Write-Output "T:  $t"
    Write-Output "SQL: $sql"
}

Gives you this:

T:  ScheduleTasks
SQL: DELETE * FROM ScheduleTasks;
T:  Budget
SQL: DELETE * FROM Budget;
T:  Process_CBVR
SQL: DELETE * FROM Process_CBVR;

Reply To: Problem with DoCMD.runsql

$
0
0

Thanks Jeff. That solves that question. I didn't realize I had to put the query variable in the ForEach loop, but it makes sense.

Also, thanks for the Write-output step. That's a great way for me to trouble shoot and check my script.

Thanks again and Aloha!

remote call script by icmp: fail tcp socket

$
0
0

Hello guys, need help.
I have a simple code in script and this script works correctly when I run locally :

$server = "srv"
$portToCheck = '1433'
Test-NetConnection -ComputerName $server -Port $portToCheck

similar :

$server = "srv"
$portToCheck = '1433'
New-Object System.Net.Sockets.TCPClient -ArgumentList $server,$portToCheck

But when I try to call this script remotely by icmp I receive an error :
WARNING: TCP connect to srv:1433 failed false Exception calling ".ctor" with "2" argument(s): "An attempt was made to access a socket in a way forbidden by its access permissions 192.168.12.145:1433"
end I have notify in event:

The Windows Filtering Platform has blocked a connection.
 
Application Information:
	Process ID:		2524
	Application Name:	\device\harddiskvolume2\windows\syswow64\windowspowershell\v1.0\powershell.exe
 
Network Information:
	Direction:		Outbound
	Source Address:		192.168.12.183
	Source Port:		54636
	Destination Address:	192.168.12.145
	Destination Port:		1433
	Protocol:		6
 
Filter Information:
	Filter Run-Time ID:	66927
	Layer Name:		Connect
	Layer Run-Time ID:	48

So, I had blocked package. Have you any ideas how to get around the problem? I would like to resolve this issue only with help PowerShell solution without writing filter by C++ for ALE WFP
I tried to use in script body: Invoke-command , -asjob
Now I've created job in task scheduler and ICMP call to start job. Result (true or false) write to txt file after that I've got content. But it's crutch and isn't true way.

Additionally: this situation catch only on servers with Server 2012R2 (WMF4), on Server 2008r2 all works without any problems.

Update script questions

$
0
0

I'm looking to write a script that can install against a repository of Windows updates. It will be a mixture of .msu and .exe, which may have different switches for installs (/q vs /quiet etc).

Below is a script I've used in the past and wanted to modify it. The $exit variable is later put into a switch that tells what the error code is.

The .msu's seem to be pretty standard and I don't seem to run into issues with them, but the .exe's seem to have some different switches. Such as some have /q but missing /norestart and then fail due to parameter's being incorrect. Is there a better more thorough way to do it than I am below?

Or is there a way to do like:

patch.exe -> fails in the else statement because it does not hav ethe /norestart -> moves to different statement that only checks for /q

Any advice would be greately appreciated.

$from = "C:\Patches"  #put your file path here!
 
$updates = @(Get-ChildItem -Path $from | where{$_.name -like '*.exe' -or $_.name -like '*.msu'} | foreach{$_.name})
if ($updates.Count -ge 1 ) 
{
	foreach($update in $updates)
	{
		if($update -like "*.msu")
		{
			Write-Host "Processing update $update."
			$exit = ((Start-Process -FilePath "$from\$update" -ArgumentList "/quiet /passive /norestart" -Wait -passthru).ExitCode)
		}
		else
		{
			Write-Host "Processing update $update."
			$exit=((Start-Process -FilePath "$from\$update" -ArgumentList "/q /norestart" -Wait -passthru).ExitCode)
		}
       }
}

Reply To: Update script questions

$
0
0

With EXEs you're really limited to what the package author came up with. Because they don't run under PowerShell (it shells out to Cmd.exe), you're even limited in what you can capture. So what you're doing in terms of grabbing the $exit is probably the best you can do. Sucks, right?

BTW, Write-Host, ew. Consider Write-Verbose and save a puppy.

You could certainly build out the logic you're suggesting. After you run the EXE, have another If construct that checks $exit and runs the command with only /q, grabbing its exit code. If there's only these couple of variations, that's probably the way to go. If you start getting into… "well, there's four ways to do this, and I'd like to try them all until one succeeds," it might be more elegant to use a slightly different approach.

Use PowerShell to Create Terminal Server Profiles

$
0
0

I have spent quite a bit of time googling to try and figure this out and can't seem to find an answer. I am involved in a Terminal Server rebuild project where we need to create local user profiles for 75 different users. We are hoping to avoid having to login as every single user and then logging off. Is this something PowerShell can handle? We have a list of all their usernames and credentials.

Reply To: Use PowerShell to Create Terminal Server Profiles

$
0
0

Why would you be logging in to create RDS local profiles? At worst I would expect you to have a properly configured default profile or group policy preferences configured to set up the user's session properly.

Reply To: Update script questions

$
0
0

Thanks for the response, I think I might have something figured out.

Whats the real difference between write-host and write-verbose?

I also just opened ps and tried a write-verbose -message "hi" and noticed it didnt write to screen…am I using it incorrectly?


Reply To: Use PowerShell to Create Terminal Server Profiles

$
0
0

I need the user profile folders to exist first so that I can copy over settings from previously used user profile disks

Reply To: Update script questions

$
0
0

Write-Host draws directly to the screen; it can't be captured or redirected. That's why it's generally a poor practice; if your script ran in a non-console host, you wouldn't necessarily be able to capture that output into, say, a log.

The Verbose pipeline is better, but it's off by default. Your script can set $VerbosePreference='Continue' to enable it, although if you're using a [CmdletBinding()] Param block, your script gains an automatic -Verbose switch that enables verbose output. That's why it's kind of a part of best practices – use a Param() block, add [CmdletBinding()], use Write-Verbose, Write-Warning, etc.

Reply To: Use PowerShell to Create Terminal Server Profiles

$
0
0

You can create profiles by running:

runas /user:DOMAIN\USER cmd.exe

for everyuser you want to create profile. Powershell would help you to automate it for your 75 users :-)

Find and Replace Strings in Multiple Files

$
0
0

Hello and my apologies up front if this has been addressed under a different post. Honestly, I've read so much over the past few days my head hurts,

My Goal: Search all files in a given path (including sub-directories) and replace strings with new strings.

For example: Search all files in c:\temp\* and d:\temp* for "servername1" and "servername2" and replace those strings with "newservername1" and "newservername2".

I haven't convinced myself I want this all in one script as there may be files like Web.configOLD that I would not want to update. That said once I find out what file(s) contain these strings I can then make a decision how to proceed and will eventually want this all in one script.

I can successfully gather the path and file name into a file using the following:

$Date = Get-Date -Format MM_dd_yyyy
$exclude = @("*log*", "*bak*")
$SearchString = 'Server1', 'Server2', 'Server3'
$FileName = "$Date ServerNamesSearchResults"
Get-ChildItem -Path "D:\temp", "c:\temp" -Recurse -exclude $exclude | Select-String $SearchString | Select-Object -Unique Path | FT -hide | Out-File "D:\PSScripts\Results\$FileName.txt"

This results in a text file that contains something like this:

D:\temp\New Text Document.txt
C:\temp\New Text Document (2).txt
C:\temp\New Text Document.txt

Now the hard part.

I now want to replace the strings "servername1" and "servername2" in each of these files with "newservername1" and "newservername2"

Please help. I'm sure there is even a better way to do this but I haven't figured it out.

Reply To: Use PowerShell to Create Terminal Server Profiles

$
0
0

Hi Jacob,

I think it would be easier to copy the profiles onto a file server and configure the Remote Desktop profile path for each user or via GPO. Once you have roaming profiles configured Windows will copy down the profile automatically.

Another alternative would be to introduce Microsoft UE-V in the old environment before the rebuild. UE-V will save the settings you've selected onto the users home drive.

P.S. Local profiles on terminal servers are never a good idea. Roaming profiles can become very large and the last log off wins. Would be better to use UE-V or another product to only roam settings.

Best,
Daniel

Viewing all 13067 articles
Browse latest View live