Get-Service | Stop-Process -Name WSearch -WhatIf
Stop-Process : The input object cannot be bound to any parameters for
the command either because the command does not take pipeline input or
the input and its properties do not match any of the parameters that
take pipeline input. At line:1 char:15
+ Get-Service | Stop-Process -Name WSearch -WhatIf
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (fdPHost:PSObject) [Stop-Process], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.StopProcessCommand
Now from my understanding they both share the same property name "Name" so I should be able to pipe thru -Name, right?
PS C:\> Get-Service | gm
TypeName: System.ServiceProcess.ServiceController
Name MemberType Definition
---- ---------- ----------
Name AliasProperty Name = ServiceName
get-help stop-process
-Name <String[]>
Specifies the process names of the processes to be stopped. You can type multiple process names (separated by commas) or use wildcard characters.
Required? true
Position? named
Default value
Accept pipeline input? true (ByPropertyName)
Accept wildcard characters? true
So am I doing something wrong here?
Get-Service -Name wsearch | Stop-Service
will work. Filter first and pass the result through the pipeline.
Related
I'm attempting to write a script that gives me a running list of computers whose name starts with SOU-C128*. I'm assigning the list to a variable and using it as input for the restart-computer cmdlet. However, I'm recieving the error provided:
restart-computer : Computer name #{Name=SOU-C127-04} cannot be resolved with the exception: One or more errors occurred..
At \\nas\user\IT\restart.ps1:2 char:1
+ restart-computer -computername $computers -force -wsmanauthentication ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (#{Name=SOU-C127-04}:String) [Restart-Computer], InvalidOperationException
+ FullyQualifiedErrorId : AddressResolutionException,Microsoft.PowerShell.Commands.RestartComputerCommand
This is the script
$computers=Get-ADComputer -Filter * | Where-Object {$_.Name -like "sou-c127*"} | Select -Property Name | Sort Name
restart-computer -computername $computers -force -wsmanauthentication Kerberos
Please assist!
Thanks.
Your immediate fix would be to use $computers.name or, expand the property in your Get-ADComputer by using Select-Objet -ExpandProperty 'Name'; foreach name would suffice too.
Wanted to suggest something though. In PowerShell when you're filtering, you always want to filter as far left as possible. This can become computationally expensive running a pipeline filter such as Where-Object on a large list. In your case: Get-ADComputer -Filter *, you're filtering for every computer, then filtering again. You can cut that out by filtering using the filter in your Get-ADComputer cmdlet to begin with:
$computers = Get-ADComputer -Filter "Name -like 'sou-c127*'" | Sort-Object -Property 'Name'
Restart-Computer -ComputerName $computers.Name
I have two identical running processes called RocketLeague.exe
I want to store one of the processes PID's in a variable for later use in another command by matching both processes full file paths.
I have been able to come up with two commands so far that pipe the full path of the processes but can't figure out how to continue the piping of the right PID into a final custom command.
How can I store the correct PID in a variable for use in my custom command?
1) Get-Process -Name 'RocketLeague' | Format-List -Property Path
2) Get-Process -Name 'RocketLeague'
Using the feedback from user:lit I was able to come up with this solution.
$procID = Get-process -Name 'RocketLeague' | Select-Object -Property Id,Path | ForEach-Object {
If($_.Path -eq 'C:\Program Files (x86)\Steam\steamapps\common\rocketleague\Binaries\Win64\RocketLeague.exe'){
Set-Variable -Name 'procSteam' -Value $_.Id; Write-Host $procSteam
}
}
If you just want the specific Process that is equal to that Path you can use Where-Object or .Where() method for filtering. The code would be reduced to:
# This:
$procID = (Get-Process -Name 'RocketLeague').Where({
$_.Path -eq 'C:\Program Files (x86)\Steam\steamapps\common\rocketleague\Binaries\Win64\RocketLeague.exe'
}) | Select-Object -Property Id, Path
# Or this:
$procID = Get-Process -Name 'RocketLeague' | Where-Object {
$_.Path -eq 'C:\Program Files (x86)\Steam\steamapps\common\rocketleague\Binaries\Win64\RocketLeague.exe'
} | Select-Object -Property Id, Path
And if, for example there is only one of the paths that ends with Win64\....exe you can use .EndsWith() method:
$procID = (Get-Process -Name 'RocketLeague').Where({
([string]$_.Path).EndsWith('\Win64\RocketLeague.exe')
}) | Select-Object -Property Id, Path
i have a line in PS script which goes to DC and try to do this:
$SWITCH = Invoke-Command -session $s -ScriptBlock {Get-ADOrganizationalUnit -filter * -Property CanonicalName | Where-Object {$_.CanonicalName -eq $using:listBox2.SelectedItem}}
here are the the variables:
$switch = "OU=office,DC=shahar,DC=local"
$s = credentials to enter the DC with an admin account.
if i run this line on the DC without the invoke command it works. if i run other code lines with invoking commands using these credentials it works as well.
if i run this line on powershell (not as a part of script) it works.
if i replace $switch with the actual string ("DC=...") it still doesnt work.
here is the error and i just cannot figure out whats the problem:
Cannot bind parameter 'Identity'. Cannot convert value "OU=Office,DC=shahar,DC=local" to type
"Microsoft.ActiveDirectory.Management.ADOrganizationalUnit". Error: "Cannot convert the "OU=Office,DC=shahar,DC=local"
value of type "Deserialized.Microsoft.ActiveDirectory.Management.ADOrganizationalUnit" to type
"Microsoft.ActiveDirectory.Management.ADOrganizationalUnit"."
+ CategoryInfo : InvalidArgument: (:) [Get-ADOrganizationalUnit], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.GetADOrgani
zationalUnit
+ PSComputerName : dc01
any help would be much appriciated!
by the way the point of this is to get from the DC the GPO's names that linked to that OU.
try this:
ipmo ActiveDirectory,GroupPolicy
$OU = 'OU=office,DC=shahar,DC=local'
(Get-ADOrganizationalUnit $OU).DistinguishedName
$LinkedGPOs = Get-ADOrganizationalUnit $OU | select -ExpandProperty LinkedGroupPolicyObjects
$LinkedGPOGUIDs = $LinkedGPOs | % {$_.Substring(4,36)}
$LinkedGPOGUIDs | % {Get-GPO -Guid $_ | select -ExpandProperty Displayname}
I'm trying to create userprincipalname as combination of username and hardcoded domainname
csv file:
name,displayname,givenname,surname
dhall,Don Hall,Don,Hall
Code:
Import-csv "c:\output.csv" | ForEach-Object {new-aduser -name $_.name -UserPrincipalName ("{0}#{1}" -f $_.name,"Dev.domain.Net") -DisplayName "$($_.givenname $_.surname)" -givenName $_.givenname -surname $_.surname -path "OU=Workspaces,DC=Dev,DC=domain,DC=Net" -AccountPassword (convertto-securestring passs -asplaintext -force) -Enabled [System.Convert]::toboolean($true)) -ChangePasswordAtLogon ([system.convert]::ToBoolean($true))}
And getting:
At line:1 char:159
+ ... -f $_.name,"Dev.domain.Net") -DisplayNa
+
Unexpected token '$_' in expression or stateme
+ CategoryInfo : ParserError: (:)
+ FullyQualifiedErrorId : UnexpectedToken
Tried also -UserPrincipalName ([string]::Concat($_.name,"#dev.domain.net"))
but same error
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 14393 1944
Windows server 2016
Not sure what's causing that error (don't have an AD controller to test against at the moment so can't validate) but in cases where I'm going to need to reuse a property multiple times I tend to assign it to a temporary variable (makes it slightly easier to write the code and don't run into issues with the pipeline variable getting updated).
Import-CSV "c:\output.csv" | ForEach-Object {
$name = $_.name
$upn = "{0}#{1}" -f $name,"dev.domain.net"
New-ADUser -Name $name -UserPrincipalName $upn #...
}
Does anyone have any idea why Remove-Item would fail while Delete works?
In below script, I get a list of files I'd like to delete.
Using Remove-Item I get following error message:
VERBOSE: Performing the operation "Remove File" on target
"\\UncPath\Folder\test.rtf". Remove-Item : Cannot remove item
\\UncPath\Folder\test.rtf: Access to the path is denied.
but using Delete is deleting those files as we speak.
Script
$files = gci \\UncPath\Folder| ?{ $_.LastWriteTime -le (Get-Date).addDays(-28) }
# This doesn't work
$files | Remove-Item -force -verbose
# But this does
$files | % { $_.Delete() }
powershell may act strange with UNC path, I think it prepends the UNC Path with the current provider you can verify this with :
cd c:
test-path \\127.0.0.1\c$
returns TRUE
cd HKCU:
test-path \\127.0.0.1\c$
returns FALSE
when specifying the fullpath we're telling powershell to use the filesystem provider, that solves the problem. you could also specify the provider like remove-item filesystem::\\uncpath\folder
I can finally repro this and IMO it appears to be a bug. The repro is to have an open share like C$ but to set Deny Modify perms for the user on the file. When I do that, I observe this:
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
ri : Cannot remove item \\Keith-PC\C$\Users\Keith\foo.txt: Access to the path is denied.
At line:1 char:43
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (\\Keith-PC\C$\Users\Keith\foo.txt:FileInfo) [Remove-Item], ArgumentExc
eption
+ FullyQualifiedErrorId : RemoveFileSystemItemArgumentError,Microsoft.PowerShell.Commands.RemoveItemCommand
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Delete()} # <== this works!
I also observe that removing the -Force parameter deletes the file without error as well. The deny perms still allow me to delete the file from Windows Explorer so that leads me to believe that the file should delete. So what is up with using the -Force parameter? When I delve into the ErrorRecord I see this:
Message : Access to the path is denied.
ParamName :
Data : {}
InnerException :
TargetSite : Void set_Attributes(System.IO.FileAttributes)
StackTrace : at System.IO.FileSystemInfo.set_Attributes(FileAttributes value)
at Microsoft.PowerShell.Commands.FileSystemProvider.RemoveFileSystemItem(FileSystemInfo
fileSystemInfo, Boolean force)
It seems that the -Force parameter is trying to set (more likely reset) attributes and the permissions on the file don't allow it e.g.:
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
Exception setting "Attributes": "Access to the path is denied."
At line:1 char:45
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
So it seems to me that PowerShell should first try as if the -Force weren't present and if that fails, then try resetting attributes.